builderthread.py 18 KB

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