builderthread.py 17 KB

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