builderthread.py 23 KB

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