builderthread.py 20 KB

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