builderthread.py 18 KB

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