builderthread.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. # SPDX-License-Identifier: GPL-2.0+
  2. # Copyright (c) 2014 Google, Inc
  3. #
  4. import errno
  5. import glob
  6. import os
  7. import shutil
  8. import sys
  9. import threading
  10. from patman import command
  11. from patman import gitutil
  12. RETURN_CODE_RETRY = -1
  13. BASE_ELF_FILENAMES = ['u-boot', 'spl/u-boot-spl', 'tpl/u-boot-tpl']
  14. def Mkdir(dirname, parents = False):
  15. """Make a directory if it doesn't already exist.
  16. Args:
  17. dirname: Directory to create
  18. """
  19. try:
  20. if parents:
  21. os.makedirs(dirname)
  22. else:
  23. os.mkdir(dirname)
  24. except OSError as err:
  25. if err.errno == errno.EEXIST:
  26. if os.path.realpath('.') == os.path.realpath(dirname):
  27. print("Cannot create the current working directory '%s'!" % dirname)
  28. sys.exit(1)
  29. pass
  30. else:
  31. raise
  32. class BuilderJob:
  33. """Holds information about a job to be performed by a thread
  34. Members:
  35. board: Board object to build
  36. commits: List of Commit objects to build
  37. keep_outputs: True to save build output files
  38. step: 1 to process every commit, n to process every nth commit
  39. work_in_output: Use the output directory as the work directory and
  40. don't write to a separate output directory.
  41. """
  42. def __init__(self):
  43. self.board = None
  44. self.commits = []
  45. self.keep_outputs = False
  46. self.step = 1
  47. self.work_in_output = False
  48. class ResultThread(threading.Thread):
  49. """This thread processes results from builder threads.
  50. It simply passes the results on to the builder. There is only one
  51. result thread, and this helps to serialise the build output.
  52. """
  53. def __init__(self, builder):
  54. """Set up a new result thread
  55. Args:
  56. builder: Builder which will be sent each result
  57. """
  58. threading.Thread.__init__(self)
  59. self.builder = builder
  60. def run(self):
  61. """Called to start up the result thread.
  62. We collect the next result job and pass it on to the build.
  63. """
  64. while True:
  65. result = self.builder.out_queue.get()
  66. self.builder.ProcessResult(result)
  67. self.builder.out_queue.task_done()
  68. class BuilderThread(threading.Thread):
  69. """This thread builds U-Boot for a particular board.
  70. An input queue provides each new job. We run 'make' to build U-Boot
  71. and then pass the results on to the output queue.
  72. Members:
  73. builder: The builder which contains information we might need
  74. thread_num: Our thread number (0-n-1), used to decide on a
  75. temporary directory. If this is -1 then there are no threads
  76. and we are the (only) main process
  77. mrproper: Use 'make mrproper' before each reconfigure
  78. per_board_out_dir: True to build in a separate persistent directory per
  79. board rather than a thread-specific directory
  80. test_exception: Used for testing; True to raise an exception instead of
  81. reporting the build result
  82. """
  83. """Set up a new builder thread"""
  84. threading.Thread.__init__(self)
  85. self.builder = builder
  86. self.thread_num = thread_num
  87. self.mrproper = mrproper
  88. self.per_board_out_dir = per_board_out_dir
  89. def Make(self, commit, brd, stage, cwd, *args, **kwargs):
  90. """Run 'make' on a particular commit and board.
  91. The source code will already be checked out, so the 'commit'
  92. argument is only for information.
  93. Args:
  94. commit: Commit object that is being built
  95. brd: Board object that is being built
  96. stage: Stage of the build. Valid stages are:
  97. mrproper - can be called to clean source
  98. config - called to configure for a board
  99. build - the main make invocation - it does the build
  100. args: A list of arguments to pass to 'make'
  101. kwargs: A list of keyword arguments to pass to command.RunPipe()
  102. Returns:
  103. CommandResult object
  104. """
  105. return self.builder.do_make(commit, brd, stage, cwd, *args,
  106. **kwargs)
  107. def RunCommit(self, commit_upto, brd, work_dir, do_config, config_only,
  108. force_build, force_build_failures, work_in_output):
  109. """Build a particular commit.
  110. If the build is already done, and we are not forcing a build, we skip
  111. the build and just return the previously-saved results.
  112. Args:
  113. commit_upto: Commit number to build (0...n-1)
  114. brd: Board object to build
  115. work_dir: Directory to which the source will be checked out
  116. do_config: True to run a make <board>_defconfig on the source
  117. config_only: Only configure the source, do not build it
  118. force_build: Force a build even if one was previously done
  119. force_build_failures: Force a bulid if the previous result showed
  120. failure
  121. work_in_output: Use the output directory as the work directory and
  122. don't write to a separate output directory.
  123. Returns:
  124. tuple containing:
  125. - CommandResult object containing the results of the build
  126. - boolean indicating whether 'make config' is still needed
  127. """
  128. # Create a default result - it will be overwritte by the call to
  129. # self.Make() below, in the event that we do a build.
  130. result = command.CommandResult()
  131. result.return_code = 0
  132. if work_in_output or self.builder.in_tree:
  133. out_dir = work_dir
  134. else:
  135. if self.per_board_out_dir:
  136. out_rel_dir = os.path.join('..', brd.target)
  137. else:
  138. out_rel_dir = 'build'
  139. out_dir = os.path.join(work_dir, out_rel_dir)
  140. # Check if the job was already completed last time
  141. done_file = self.builder.GetDoneFile(commit_upto, brd.target)
  142. result.already_done = os.path.exists(done_file)
  143. will_build = (force_build or force_build_failures or
  144. not result.already_done)
  145. if result.already_done:
  146. # Get the return code from that build and use it
  147. with open(done_file, 'r') as fd:
  148. try:
  149. result.return_code = int(fd.readline())
  150. except ValueError:
  151. # The file may be empty due to running out of disk space.
  152. # Try a rebuild
  153. result.return_code = RETURN_CODE_RETRY
  154. # Check the signal that the build needs to be retried
  155. if result.return_code == RETURN_CODE_RETRY:
  156. will_build = True
  157. elif will_build:
  158. err_file = self.builder.GetErrFile(commit_upto, brd.target)
  159. if os.path.exists(err_file) and os.stat(err_file).st_size:
  160. result.stderr = 'bad'
  161. elif not force_build:
  162. # The build passed, so no need to build it again
  163. will_build = False
  164. if will_build:
  165. # We are going to have to build it. First, get a toolchain
  166. if not self.toolchain:
  167. try:
  168. self.toolchain = self.builder.toolchains.Select(brd.arch)
  169. except ValueError as err:
  170. result.return_code = 10
  171. result.stdout = ''
  172. result.stderr = str(err)
  173. # TODO(sjg@chromium.org): This gets swallowed, but needs
  174. # to be reported.
  175. if self.toolchain:
  176. # Checkout the right commit
  177. if self.builder.commits:
  178. commit = self.builder.commits[commit_upto]
  179. if self.builder.checkout:
  180. git_dir = os.path.join(work_dir, '.git')
  181. gitutil.Checkout(commit.hash, git_dir, work_dir,
  182. force=True)
  183. else:
  184. commit = 'current'
  185. # Set up the environment and command line
  186. env = self.toolchain.MakeEnvironment(self.builder.full_path)
  187. Mkdir(out_dir)
  188. args = []
  189. cwd = work_dir
  190. src_dir = os.path.realpath(work_dir)
  191. if not self.builder.in_tree:
  192. if commit_upto is None:
  193. # In this case we are building in the original source
  194. # directory (i.e. the current directory where buildman
  195. # is invoked. The output directory is set to this
  196. # thread's selected work directory.
  197. #
  198. # Symlinks can confuse U-Boot's Makefile since
  199. # we may use '..' in our path, so remove them.
  200. out_dir = os.path.realpath(out_dir)
  201. args.append('O=%s' % out_dir)
  202. cwd = None
  203. src_dir = os.getcwd()
  204. else:
  205. args.append('O=%s' % out_rel_dir)
  206. if self.builder.verbose_build:
  207. args.append('V=1')
  208. else:
  209. args.append('-s')
  210. if self.builder.num_jobs is not None:
  211. args.extend(['-j', str(self.builder.num_jobs)])
  212. if self.builder.warnings_as_errors:
  213. args.append('KCFLAGS=-Werror')
  214. config_args = ['%s_defconfig' % brd.target]
  215. config_out = ''
  216. args.extend(self.builder.toolchains.GetMakeArguments(brd))
  217. args.extend(self.toolchain.MakeArgs())
  218. # Remove any output targets. Since we use a build directory that
  219. # was previously used by another board, it may have produced an
  220. # SPL image. If we don't remove it (i.e. see do_config and
  221. # self.mrproper below) then it will appear to be the output of
  222. # this build, even if it does not produce SPL images.
  223. build_dir = self.builder.GetBuildDir(commit_upto, brd.target)
  224. for elf in BASE_ELF_FILENAMES:
  225. fname = os.path.join(out_dir, elf)
  226. if os.path.exists(fname):
  227. os.remove(fname)
  228. # If we need to reconfigure, do that now
  229. if do_config:
  230. config_out = ''
  231. if self.mrproper:
  232. result = self.Make(commit, brd, 'mrproper', cwd,
  233. 'mrproper', *args, env=env)
  234. config_out += result.combined
  235. result = self.Make(commit, brd, 'config', cwd,
  236. *(args + config_args), env=env)
  237. config_out += result.combined
  238. do_config = False # No need to configure next time
  239. if result.return_code == 0:
  240. if config_only:
  241. args.append('cfg')
  242. result = self.Make(commit, brd, 'build', cwd, *args,
  243. env=env)
  244. result.stderr = result.stderr.replace(src_dir + '/', '')
  245. if self.builder.verbose_build:
  246. result.stdout = config_out + result.stdout
  247. else:
  248. result.return_code = 1
  249. result.stderr = 'No tool chain for %s\n' % brd.arch
  250. result.already_done = False
  251. result.toolchain = self.toolchain
  252. result.brd = brd
  253. result.commit_upto = commit_upto
  254. result.out_dir = out_dir
  255. return result, do_config
  256. def _WriteResult(self, result, keep_outputs, work_in_output):
  257. """Write a built result to the output directory.
  258. Args:
  259. result: CommandResult object containing result to write
  260. keep_outputs: True to store the output binaries, False
  261. to delete them
  262. work_in_output: Use the output directory as the work directory and
  263. don't write to a separate output directory.
  264. """
  265. # Fatal error
  266. if result.return_code < 0:
  267. return
  268. # If we think this might have been aborted with Ctrl-C, record the
  269. # failure but not that we are 'done' with this board. A retry may fix
  270. # it.
  271. maybe_aborted = result.stderr and 'No child processes' in result.stderr
  272. if result.already_done:
  273. return
  274. # Write the output and stderr
  275. output_dir = self.builder._GetOutputDir(result.commit_upto)
  276. Mkdir(output_dir)
  277. build_dir = self.builder.GetBuildDir(result.commit_upto,
  278. result.brd.target)
  279. Mkdir(build_dir)
  280. outfile = os.path.join(build_dir, 'log')
  281. with open(outfile, 'w') as fd:
  282. if result.stdout:
  283. fd.write(result.stdout)
  284. errfile = self.builder.GetErrFile(result.commit_upto,
  285. result.brd.target)
  286. if result.stderr:
  287. with open(errfile, 'w') as fd:
  288. fd.write(result.stderr)
  289. elif os.path.exists(errfile):
  290. os.remove(errfile)
  291. if result.toolchain:
  292. # Write the build result and toolchain information.
  293. done_file = self.builder.GetDoneFile(result.commit_upto,
  294. result.brd.target)
  295. with open(done_file, 'w') as fd:
  296. if maybe_aborted:
  297. # Special code to indicate we need to retry
  298. fd.write('%s' % RETURN_CODE_RETRY)
  299. else:
  300. fd.write('%s' % result.return_code)
  301. with open(os.path.join(build_dir, 'toolchain'), 'w') as fd:
  302. print('gcc', result.toolchain.gcc, file=fd)
  303. print('path', result.toolchain.path, file=fd)
  304. print('cross', result.toolchain.cross, file=fd)
  305. print('arch', result.toolchain.arch, file=fd)
  306. fd.write('%s' % result.return_code)
  307. # Write out the image and function size information and an objdump
  308. env = result.toolchain.MakeEnvironment(self.builder.full_path)
  309. with open(os.path.join(build_dir, 'out-env'), 'w',
  310. encoding='utf-8') as fd:
  311. for var in sorted(env.keys()):
  312. print('%s="%s"' % (var, env[var]), file=fd)
  313. lines = []
  314. for fname in BASE_ELF_FILENAMES:
  315. cmd = ['%snm' % self.toolchain.cross, '--size-sort', fname]
  316. nm_result = command.RunPipe([cmd], capture=True,
  317. capture_stderr=True, cwd=result.out_dir,
  318. raise_on_error=False, env=env)
  319. if nm_result.stdout:
  320. nm = self.builder.GetFuncSizesFile(result.commit_upto,
  321. result.brd.target, fname)
  322. with open(nm, 'w') as fd:
  323. print(nm_result.stdout, end=' ', file=fd)
  324. cmd = ['%sobjdump' % self.toolchain.cross, '-h', fname]
  325. dump_result = command.RunPipe([cmd], capture=True,
  326. capture_stderr=True, cwd=result.out_dir,
  327. raise_on_error=False, env=env)
  328. rodata_size = ''
  329. if dump_result.stdout:
  330. objdump = self.builder.GetObjdumpFile(result.commit_upto,
  331. result.brd.target, fname)
  332. with open(objdump, 'w') as fd:
  333. print(dump_result.stdout, end=' ', file=fd)
  334. for line in dump_result.stdout.splitlines():
  335. fields = line.split()
  336. if len(fields) > 5 and fields[1] == '.rodata':
  337. rodata_size = fields[2]
  338. cmd = ['%ssize' % self.toolchain.cross, fname]
  339. size_result = command.RunPipe([cmd], capture=True,
  340. capture_stderr=True, cwd=result.out_dir,
  341. raise_on_error=False, env=env)
  342. if size_result.stdout:
  343. lines.append(size_result.stdout.splitlines()[1] + ' ' +
  344. rodata_size)
  345. # Extract the environment from U-Boot and dump it out
  346. cmd = ['%sobjcopy' % self.toolchain.cross, '-O', 'binary',
  347. '-j', '.rodata.default_environment',
  348. 'env/built-in.o', 'uboot.env']
  349. command.RunPipe([cmd], capture=True,
  350. capture_stderr=True, cwd=result.out_dir,
  351. raise_on_error=False, env=env)
  352. ubootenv = os.path.join(result.out_dir, 'uboot.env')
  353. if not work_in_output:
  354. self.CopyFiles(result.out_dir, build_dir, '', ['uboot.env'])
  355. # Write out the image sizes file. This is similar to the output
  356. # of binutil's 'size' utility, but it omits the header line and
  357. # adds an additional hex value at the end of each line for the
  358. # rodata size
  359. if len(lines):
  360. sizes = self.builder.GetSizesFile(result.commit_upto,
  361. result.brd.target)
  362. with open(sizes, 'w') as fd:
  363. print('\n'.join(lines), file=fd)
  364. if not work_in_output:
  365. # Write out the configuration files, with a special case for SPL
  366. for dirname in ['', 'spl', 'tpl']:
  367. self.CopyFiles(
  368. result.out_dir, build_dir, dirname,
  369. ['u-boot.cfg', 'spl/u-boot-spl.cfg', 'tpl/u-boot-tpl.cfg',
  370. '.config', 'include/autoconf.mk',
  371. 'include/generated/autoconf.h'])
  372. # Now write the actual build output
  373. if keep_outputs:
  374. self.CopyFiles(
  375. result.out_dir, build_dir, '',
  376. ['u-boot*', '*.bin', '*.map', '*.img', 'MLO', 'SPL',
  377. 'include/autoconf.mk', 'spl/u-boot-spl*'])
  378. def CopyFiles(self, out_dir, build_dir, dirname, patterns):
  379. """Copy files from the build directory to the output.
  380. Args:
  381. out_dir: Path to output directory containing the files
  382. build_dir: Place to copy the files
  383. dirname: Source directory, '' for normal U-Boot, 'spl' for SPL
  384. patterns: A list of filenames (strings) to copy, each relative
  385. to the build directory
  386. """
  387. for pattern in patterns:
  388. file_list = glob.glob(os.path.join(out_dir, dirname, pattern))
  389. for fname in file_list:
  390. target = os.path.basename(fname)
  391. if dirname:
  392. base, ext = os.path.splitext(target)
  393. if ext:
  394. target = '%s-%s%s' % (base, dirname, ext)
  395. shutil.copy(fname, os.path.join(build_dir, target))
  396. def _SendResult(self, result):
  397. """Send a result to the builder for processing
  398. Args:
  399. result: CommandResult object containing the results of the build
  400. """
  401. if self.thread_num != -1:
  402. self.builder.out_queue.put(result)
  403. else:
  404. self.builder.ProcessResult(result)
  405. def RunJob(self, job):
  406. """Run a single job
  407. A job consists of a building a list of commits for a particular board.
  408. Args:
  409. job: Job to build
  410. Returns:
  411. List of Result objects
  412. """
  413. brd = job.board
  414. work_dir = self.builder.GetThreadDir(self.thread_num)
  415. self.toolchain = None
  416. if job.commits:
  417. # Run 'make board_defconfig' on the first commit
  418. do_config = True
  419. commit_upto = 0
  420. force_build = False
  421. for commit_upto in range(0, len(job.commits), job.step):
  422. result, request_config = self.RunCommit(commit_upto, brd,
  423. work_dir, do_config, self.builder.config_only,
  424. force_build or self.builder.force_build,
  425. self.builder.force_build_failures,
  426. work_in_output=job.work_in_output)
  427. failed = result.return_code or result.stderr
  428. did_config = do_config
  429. if failed and not do_config:
  430. # If our incremental build failed, try building again
  431. # with a reconfig.
  432. if self.builder.force_config_on_failure:
  433. result, request_config = self.RunCommit(commit_upto,
  434. brd, work_dir, True, False, True, False,
  435. work_in_output=job.work_in_output)
  436. did_config = True
  437. if not self.builder.force_reconfig:
  438. do_config = request_config
  439. # If we built that commit, then config is done. But if we got
  440. # an warning, reconfig next time to force it to build the same
  441. # files that created warnings this time. Otherwise an
  442. # incremental build may not build the same file, and we will
  443. # think that the warning has gone away.
  444. # We could avoid this by using -Werror everywhere...
  445. # For errors, the problem doesn't happen, since presumably
  446. # the build stopped and didn't generate output, so will retry
  447. # that file next time. So we could detect warnings and deal
  448. # with them specially here. For now, we just reconfigure if
  449. # anything goes work.
  450. # Of course this is substantially slower if there are build
  451. # errors/warnings (e.g. 2-3x slower even if only 10% of builds
  452. # have problems).
  453. if (failed and not result.already_done and not did_config and
  454. self.builder.force_config_on_failure):
  455. # If this build failed, try the next one with a
  456. # reconfigure.
  457. # Sometimes if the board_config.h file changes it can mess
  458. # with dependencies, and we get:
  459. # make: *** No rule to make target `include/autoconf.mk',
  460. # needed by `depend'.
  461. do_config = True
  462. force_build = True
  463. else:
  464. force_build = False
  465. if self.builder.force_config_on_failure:
  466. if failed:
  467. do_config = True
  468. result.commit_upto = commit_upto
  469. if result.return_code < 0:
  470. raise ValueError('Interrupt')
  471. # We have the build results, so output the result
  472. self._WriteResult(result, job.keep_outputs, job.work_in_output)
  473. self._SendResult(result)
  474. else:
  475. # Just build the currently checked-out build
  476. result, request_config = self.RunCommit(None, brd, work_dir, True,
  477. self.builder.config_only, True,
  478. self.builder.force_build_failures,
  479. work_in_output=job.work_in_output)
  480. result.commit_upto = 0
  481. self._WriteResult(result, job.keep_outputs, job.work_in_output)
  482. self._SendResult(result)
  483. def run(self):
  484. """Our thread's run function
  485. This thread picks a job from the queue, runs it, and then goes to the
  486. next job.
  487. """
  488. while True:
  489. job = self.builder.queue.get()
  490. self.RunJob(job)
  491. self.builder.queue.task_done()