builderthread.py 21 KB

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