builderthread.py 22 KB

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