builderthread.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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. mrproper - 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. src_dir = os.path.realpath(work_dir)
  153. if not self.builder.in_tree:
  154. if commit_upto is None:
  155. # In this case we are building in the original source
  156. # directory (i.e. the current directory where buildman
  157. # is invoked. The output directory is set to this
  158. # thread's selected work directory.
  159. #
  160. # Symlinks can confuse U-Boot's Makefile since
  161. # we may use '..' in our path, so remove them.
  162. work_dir = os.path.realpath(work_dir)
  163. args.append('O=%s/build' % work_dir)
  164. cwd = None
  165. src_dir = os.getcwd()
  166. else:
  167. args.append('O=build')
  168. args.append('-s')
  169. if self.builder.num_jobs is not None:
  170. args.extend(['-j', str(self.builder.num_jobs)])
  171. config_args = ['%s_defconfig' % brd.target]
  172. config_out = ''
  173. args.extend(self.builder.toolchains.GetMakeArguments(brd))
  174. # If we need to reconfigure, do that now
  175. if do_config:
  176. result = self.Make(commit, brd, 'mrproper', cwd,
  177. 'mrproper', *args, env=env)
  178. result = self.Make(commit, brd, 'config', cwd,
  179. *(args + config_args), env=env)
  180. config_out = result.combined
  181. do_config = False # No need to configure next time
  182. if result.return_code == 0:
  183. result = self.Make(commit, brd, 'build', cwd, *args,
  184. env=env)
  185. result.stderr = result.stderr.replace(src_dir + '/', '')
  186. else:
  187. result.return_code = 1
  188. result.stderr = 'No tool chain for %s\n' % brd.arch
  189. result.already_done = False
  190. result.toolchain = self.toolchain
  191. result.brd = brd
  192. result.commit_upto = commit_upto
  193. result.out_dir = out_dir
  194. return result, do_config
  195. def _WriteResult(self, result, keep_outputs):
  196. """Write a built result to the output directory.
  197. Args:
  198. result: CommandResult object containing result to write
  199. keep_outputs: True to store the output binaries, False
  200. to delete them
  201. """
  202. # Fatal error
  203. if result.return_code < 0:
  204. return
  205. # Aborted?
  206. if result.stderr and 'No child processes' in result.stderr:
  207. return
  208. if result.already_done:
  209. return
  210. # Write the output and stderr
  211. output_dir = self.builder._GetOutputDir(result.commit_upto)
  212. Mkdir(output_dir)
  213. build_dir = self.builder.GetBuildDir(result.commit_upto,
  214. result.brd.target)
  215. Mkdir(build_dir)
  216. outfile = os.path.join(build_dir, 'log')
  217. with open(outfile, 'w') as fd:
  218. if result.stdout:
  219. fd.write(result.stdout)
  220. errfile = self.builder.GetErrFile(result.commit_upto,
  221. result.brd.target)
  222. if result.stderr:
  223. with open(errfile, 'w') as fd:
  224. fd.write(result.stderr)
  225. elif os.path.exists(errfile):
  226. os.remove(errfile)
  227. if result.toolchain:
  228. # Write the build result and toolchain information.
  229. done_file = self.builder.GetDoneFile(result.commit_upto,
  230. result.brd.target)
  231. with open(done_file, 'w') as fd:
  232. fd.write('%s' % result.return_code)
  233. with open(os.path.join(build_dir, 'toolchain'), 'w') as fd:
  234. print >>fd, 'gcc', result.toolchain.gcc
  235. print >>fd, 'path', result.toolchain.path
  236. print >>fd, 'cross', result.toolchain.cross
  237. print >>fd, 'arch', result.toolchain.arch
  238. fd.write('%s' % result.return_code)
  239. with open(os.path.join(build_dir, 'toolchain'), 'w') as fd:
  240. print >>fd, 'gcc', result.toolchain.gcc
  241. print >>fd, 'path', result.toolchain.path
  242. # Write out the image and function size information and an objdump
  243. env = result.toolchain.MakeEnvironment()
  244. lines = []
  245. for fname in ['u-boot', 'spl/u-boot-spl']:
  246. cmd = ['%snm' % self.toolchain.cross, '--size-sort', fname]
  247. nm_result = command.RunPipe([cmd], capture=True,
  248. capture_stderr=True, cwd=result.out_dir,
  249. raise_on_error=False, env=env)
  250. if nm_result.stdout:
  251. nm = self.builder.GetFuncSizesFile(result.commit_upto,
  252. result.brd.target, fname)
  253. with open(nm, 'w') as fd:
  254. print >>fd, nm_result.stdout,
  255. cmd = ['%sobjdump' % self.toolchain.cross, '-h', fname]
  256. dump_result = command.RunPipe([cmd], capture=True,
  257. capture_stderr=True, cwd=result.out_dir,
  258. raise_on_error=False, env=env)
  259. rodata_size = ''
  260. if dump_result.stdout:
  261. objdump = self.builder.GetObjdumpFile(result.commit_upto,
  262. result.brd.target, fname)
  263. with open(objdump, 'w') as fd:
  264. print >>fd, dump_result.stdout,
  265. for line in dump_result.stdout.splitlines():
  266. fields = line.split()
  267. if len(fields) > 5 and fields[1] == '.rodata':
  268. rodata_size = fields[2]
  269. cmd = ['%ssize' % self.toolchain.cross, fname]
  270. size_result = command.RunPipe([cmd], capture=True,
  271. capture_stderr=True, cwd=result.out_dir,
  272. raise_on_error=False, env=env)
  273. if size_result.stdout:
  274. lines.append(size_result.stdout.splitlines()[1] + ' ' +
  275. rodata_size)
  276. # Write out the image sizes file. This is similar to the output
  277. # of binutil's 'size' utility, but it omits the header line and
  278. # adds an additional hex value at the end of each line for the
  279. # rodata size
  280. if len(lines):
  281. sizes = self.builder.GetSizesFile(result.commit_upto,
  282. result.brd.target)
  283. with open(sizes, 'w') as fd:
  284. print >>fd, '\n'.join(lines)
  285. # Now write the actual build output
  286. if keep_outputs:
  287. patterns = ['u-boot', '*.bin', 'u-boot.dtb', '*.map',
  288. 'include/autoconf.mk', 'spl/u-boot-spl',
  289. 'spl/u-boot-spl.bin']
  290. for pattern in patterns:
  291. file_list = glob.glob(os.path.join(result.out_dir, pattern))
  292. for fname in file_list:
  293. shutil.copy(fname, build_dir)
  294. def RunJob(self, job):
  295. """Run a single job
  296. A job consists of a building a list of commits for a particular board.
  297. Args:
  298. job: Job to build
  299. """
  300. brd = job.board
  301. work_dir = self.builder.GetThreadDir(self.thread_num)
  302. self.toolchain = None
  303. if job.commits:
  304. # Run 'make board_defconfig' on the first commit
  305. do_config = True
  306. commit_upto = 0
  307. force_build = False
  308. for commit_upto in range(0, len(job.commits), job.step):
  309. result, request_config = self.RunCommit(commit_upto, brd,
  310. work_dir, do_config,
  311. force_build or self.builder.force_build,
  312. self.builder.force_build_failures)
  313. failed = result.return_code or result.stderr
  314. did_config = do_config
  315. if failed and not do_config:
  316. # If our incremental build failed, try building again
  317. # with a reconfig.
  318. if self.builder.force_config_on_failure:
  319. result, request_config = self.RunCommit(commit_upto,
  320. brd, work_dir, True, True, False)
  321. did_config = True
  322. if not self.builder.force_reconfig:
  323. do_config = request_config
  324. # If we built that commit, then config is done. But if we got
  325. # an warning, reconfig next time to force it to build the same
  326. # files that created warnings this time. Otherwise an
  327. # incremental build may not build the same file, and we will
  328. # think that the warning has gone away.
  329. # We could avoid this by using -Werror everywhere...
  330. # For errors, the problem doesn't happen, since presumably
  331. # the build stopped and didn't generate output, so will retry
  332. # that file next time. So we could detect warnings and deal
  333. # with them specially here. For now, we just reconfigure if
  334. # anything goes work.
  335. # Of course this is substantially slower if there are build
  336. # errors/warnings (e.g. 2-3x slower even if only 10% of builds
  337. # have problems).
  338. if (failed and not result.already_done and not did_config and
  339. self.builder.force_config_on_failure):
  340. # If this build failed, try the next one with a
  341. # reconfigure.
  342. # Sometimes if the board_config.h file changes it can mess
  343. # with dependencies, and we get:
  344. # make: *** No rule to make target `include/autoconf.mk',
  345. # needed by `depend'.
  346. do_config = True
  347. force_build = True
  348. else:
  349. force_build = False
  350. if self.builder.force_config_on_failure:
  351. if failed:
  352. do_config = True
  353. result.commit_upto = commit_upto
  354. if result.return_code < 0:
  355. raise ValueError('Interrupt')
  356. # We have the build results, so output the result
  357. self._WriteResult(result, job.keep_outputs)
  358. self.builder.out_queue.put(result)
  359. else:
  360. # Just build the currently checked-out build
  361. result, request_config = self.RunCommit(None, brd, work_dir, True,
  362. True, self.builder.force_build_failures)
  363. result.commit_upto = 0
  364. self._WriteResult(result, job.keep_outputs)
  365. self.builder.out_queue.put(result)
  366. def run(self):
  367. """Our thread's run function
  368. This thread picks a job from the queue, runs it, and then goes to the
  369. next job.
  370. """
  371. alive = True
  372. while True:
  373. job = self.builder.queue.get()
  374. if self.builder.active and alive:
  375. self.RunJob(job)
  376. '''
  377. try:
  378. if self.builder.active and alive:
  379. self.RunJob(job)
  380. except Exception as err:
  381. alive = False
  382. print err
  383. '''
  384. self.builder.queue.task_done()