builderthread.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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. if self.builder.warnings_as_errors:
  190. args.append('KCFLAGS=-Werror')
  191. config_args = ['%s_defconfig' % brd.target]
  192. config_out = ''
  193. args.extend(self.builder.toolchains.GetMakeArguments(brd))
  194. # If we need to reconfigure, do that now
  195. if do_config:
  196. config_out = ''
  197. if not self.incremental:
  198. result = self.Make(commit, brd, 'mrproper', cwd,
  199. 'mrproper', *args, env=env)
  200. config_out += result.combined
  201. result = self.Make(commit, brd, 'config', cwd,
  202. *(args + config_args), env=env)
  203. config_out += result.combined
  204. do_config = False # No need to configure next time
  205. if result.return_code == 0:
  206. if config_only:
  207. args.append('cfg')
  208. result = self.Make(commit, brd, 'build', cwd, *args,
  209. env=env)
  210. result.stderr = result.stderr.replace(src_dir + '/', '')
  211. if self.builder.verbose_build:
  212. result.stdout = config_out + result.stdout
  213. else:
  214. result.return_code = 1
  215. result.stderr = 'No tool chain for %s\n' % brd.arch
  216. result.already_done = False
  217. result.toolchain = self.toolchain
  218. result.brd = brd
  219. result.commit_upto = commit_upto
  220. result.out_dir = out_dir
  221. return result, do_config
  222. def _WriteResult(self, result, keep_outputs):
  223. """Write a built result to the output directory.
  224. Args:
  225. result: CommandResult object containing result to write
  226. keep_outputs: True to store the output binaries, False
  227. to delete them
  228. """
  229. # Fatal error
  230. if result.return_code < 0:
  231. return
  232. # If we think this might have been aborted with Ctrl-C, record the
  233. # failure but not that we are 'done' with this board. A retry may fix
  234. # it.
  235. maybe_aborted = result.stderr and 'No child processes' in result.stderr
  236. if result.already_done:
  237. return
  238. # Write the output and stderr
  239. output_dir = self.builder._GetOutputDir(result.commit_upto)
  240. Mkdir(output_dir)
  241. build_dir = self.builder.GetBuildDir(result.commit_upto,
  242. result.brd.target)
  243. Mkdir(build_dir)
  244. outfile = os.path.join(build_dir, 'log')
  245. with open(outfile, 'w') as fd:
  246. if result.stdout:
  247. # We don't want unicode characters in log files
  248. fd.write(result.stdout.decode('UTF-8').encode('ASCII', 'replace'))
  249. errfile = self.builder.GetErrFile(result.commit_upto,
  250. result.brd.target)
  251. if result.stderr:
  252. with open(errfile, 'w') as fd:
  253. # We don't want unicode characters in log files
  254. fd.write(result.stderr.decode('UTF-8').encode('ASCII', 'replace'))
  255. elif os.path.exists(errfile):
  256. os.remove(errfile)
  257. if result.toolchain:
  258. # Write the build result and toolchain information.
  259. done_file = self.builder.GetDoneFile(result.commit_upto,
  260. result.brd.target)
  261. with open(done_file, 'w') as fd:
  262. if maybe_aborted:
  263. # Special code to indicate we need to retry
  264. fd.write('%s' % RETURN_CODE_RETRY)
  265. else:
  266. fd.write('%s' % result.return_code)
  267. with open(os.path.join(build_dir, 'toolchain'), 'w') as fd:
  268. print >>fd, 'gcc', result.toolchain.gcc
  269. print >>fd, 'path', result.toolchain.path
  270. print >>fd, 'cross', result.toolchain.cross
  271. print >>fd, 'arch', result.toolchain.arch
  272. fd.write('%s' % result.return_code)
  273. # Write out the image and function size information and an objdump
  274. env = result.toolchain.MakeEnvironment(self.builder.full_path)
  275. lines = []
  276. for fname in ['u-boot', 'spl/u-boot-spl']:
  277. cmd = ['%snm' % self.toolchain.cross, '--size-sort', fname]
  278. nm_result = command.RunPipe([cmd], capture=True,
  279. capture_stderr=True, cwd=result.out_dir,
  280. raise_on_error=False, env=env)
  281. if nm_result.stdout:
  282. nm = self.builder.GetFuncSizesFile(result.commit_upto,
  283. result.brd.target, fname)
  284. with open(nm, 'w') as fd:
  285. print >>fd, nm_result.stdout,
  286. cmd = ['%sobjdump' % self.toolchain.cross, '-h', fname]
  287. dump_result = command.RunPipe([cmd], capture=True,
  288. capture_stderr=True, cwd=result.out_dir,
  289. raise_on_error=False, env=env)
  290. rodata_size = ''
  291. if dump_result.stdout:
  292. objdump = self.builder.GetObjdumpFile(result.commit_upto,
  293. result.brd.target, fname)
  294. with open(objdump, 'w') as fd:
  295. print >>fd, dump_result.stdout,
  296. for line in dump_result.stdout.splitlines():
  297. fields = line.split()
  298. if len(fields) > 5 and fields[1] == '.rodata':
  299. rodata_size = fields[2]
  300. cmd = ['%ssize' % self.toolchain.cross, fname]
  301. size_result = command.RunPipe([cmd], capture=True,
  302. capture_stderr=True, cwd=result.out_dir,
  303. raise_on_error=False, env=env)
  304. if size_result.stdout:
  305. lines.append(size_result.stdout.splitlines()[1] + ' ' +
  306. rodata_size)
  307. # Write out the image sizes file. This is similar to the output
  308. # of binutil's 'size' utility, but it omits the header line and
  309. # adds an additional hex value at the end of each line for the
  310. # rodata size
  311. if len(lines):
  312. sizes = self.builder.GetSizesFile(result.commit_upto,
  313. result.brd.target)
  314. with open(sizes, 'w') as fd:
  315. print >>fd, '\n'.join(lines)
  316. # Write out the configuration files, with a special case for SPL
  317. for dirname in ['', 'spl', 'tpl']:
  318. self.CopyFiles(result.out_dir, build_dir, dirname, ['u-boot.cfg',
  319. 'spl/u-boot-spl.cfg', 'tpl/u-boot-tpl.cfg', '.config',
  320. 'include/autoconf.mk', 'include/generated/autoconf.h'])
  321. # Now write the actual build output
  322. if keep_outputs:
  323. self.CopyFiles(result.out_dir, build_dir, '', ['u-boot*', '*.bin',
  324. '*.map', '*.img', 'MLO', 'SPL', 'include/autoconf.mk',
  325. 'spl/u-boot-spl*'])
  326. def CopyFiles(self, out_dir, build_dir, dirname, patterns):
  327. """Copy files from the build directory to the output.
  328. Args:
  329. out_dir: Path to output directory containing the files
  330. build_dir: Place to copy the files
  331. dirname: Source directory, '' for normal U-Boot, 'spl' for SPL
  332. patterns: A list of filenames (strings) to copy, each relative
  333. to the build directory
  334. """
  335. for pattern in patterns:
  336. file_list = glob.glob(os.path.join(out_dir, dirname, pattern))
  337. for fname in file_list:
  338. target = os.path.basename(fname)
  339. if dirname:
  340. base, ext = os.path.splitext(target)
  341. if ext:
  342. target = '%s-%s%s' % (base, dirname, ext)
  343. shutil.copy(fname, os.path.join(build_dir, target))
  344. def RunJob(self, job):
  345. """Run a single job
  346. A job consists of a building a list of commits for a particular board.
  347. Args:
  348. job: Job to build
  349. """
  350. brd = job.board
  351. work_dir = self.builder.GetThreadDir(self.thread_num)
  352. self.toolchain = None
  353. if job.commits:
  354. # Run 'make board_defconfig' on the first commit
  355. do_config = True
  356. commit_upto = 0
  357. force_build = False
  358. for commit_upto in range(0, len(job.commits), job.step):
  359. result, request_config = self.RunCommit(commit_upto, brd,
  360. work_dir, do_config, self.builder.config_only,
  361. force_build or self.builder.force_build,
  362. self.builder.force_build_failures)
  363. failed = result.return_code or result.stderr
  364. did_config = do_config
  365. if failed and not do_config:
  366. # If our incremental build failed, try building again
  367. # with a reconfig.
  368. if self.builder.force_config_on_failure:
  369. result, request_config = self.RunCommit(commit_upto,
  370. brd, work_dir, True, False, True, False)
  371. did_config = True
  372. if not self.builder.force_reconfig:
  373. do_config = request_config
  374. # If we built that commit, then config is done. But if we got
  375. # an warning, reconfig next time to force it to build the same
  376. # files that created warnings this time. Otherwise an
  377. # incremental build may not build the same file, and we will
  378. # think that the warning has gone away.
  379. # We could avoid this by using -Werror everywhere...
  380. # For errors, the problem doesn't happen, since presumably
  381. # the build stopped and didn't generate output, so will retry
  382. # that file next time. So we could detect warnings and deal
  383. # with them specially here. For now, we just reconfigure if
  384. # anything goes work.
  385. # Of course this is substantially slower if there are build
  386. # errors/warnings (e.g. 2-3x slower even if only 10% of builds
  387. # have problems).
  388. if (failed and not result.already_done and not did_config and
  389. self.builder.force_config_on_failure):
  390. # If this build failed, try the next one with a
  391. # reconfigure.
  392. # Sometimes if the board_config.h file changes it can mess
  393. # with dependencies, and we get:
  394. # make: *** No rule to make target `include/autoconf.mk',
  395. # needed by `depend'.
  396. do_config = True
  397. force_build = True
  398. else:
  399. force_build = False
  400. if self.builder.force_config_on_failure:
  401. if failed:
  402. do_config = True
  403. result.commit_upto = commit_upto
  404. if result.return_code < 0:
  405. raise ValueError('Interrupt')
  406. # We have the build results, so output the result
  407. self._WriteResult(result, job.keep_outputs)
  408. self.builder.out_queue.put(result)
  409. else:
  410. # Just build the currently checked-out build
  411. result, request_config = self.RunCommit(None, brd, work_dir, True,
  412. self.builder.config_only, True,
  413. self.builder.force_build_failures)
  414. result.commit_upto = 0
  415. self._WriteResult(result, job.keep_outputs)
  416. self.builder.out_queue.put(result)
  417. def run(self):
  418. """Our thread's run function
  419. This thread picks a job from the queue, runs it, and then goes to the
  420. next job.
  421. """
  422. while True:
  423. job = self.builder.queue.get()
  424. self.RunJob(job)
  425. self.builder.queue.task_done()