builderthread.py 18 KB

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