]> Git Repo - J-u-boot.git/blame - tools/buildman/builderthread.py
buildman: Handle exceptions in threads gracefully
[J-u-boot.git] / tools / buildman / builderthread.py
CommitLineData
83d290c5 1# SPDX-License-Identifier: GPL-2.0+
190064b4
SG
2# Copyright (c) 2014 Google, Inc
3#
190064b4
SG
4
5import errno
6import glob
7import os
8import shutil
409fc029 9import sys
190064b4
SG
10import threading
11
bf776679
SG
12from patman import command
13from patman import gitutil
190064b4 14
88c8dcf9 15RETURN_CODE_RETRY = -1
73da3d2c 16BASE_ELF_FILENAMES = ['u-boot', 'spl/u-boot-spl', 'tpl/u-boot-tpl']
88c8dcf9 17
f3d015cb 18def Mkdir(dirname, parents = False):
190064b4
SG
19 """Make a directory if it doesn't already exist.
20
21 Args:
22 dirname: Directory to create
23 """
24 try:
f3d015cb
TR
25 if parents:
26 os.makedirs(dirname)
27 else:
28 os.mkdir(dirname)
190064b4
SG
29 except OSError as err:
30 if err.errno == errno.EEXIST:
409fc029 31 if os.path.realpath('.') == os.path.realpath(dirname):
c05aa036 32 print("Cannot create the current working directory '%s'!" % dirname)
409fc029 33 sys.exit(1)
190064b4
SG
34 pass
35 else:
36 raise
37
38class BuilderJob:
39 """Holds information about a job to be performed by a thread
40
41 Members:
42 board: Board object to build
e9fbbf63
SG
43 commits: List of Commit objects to build
44 keep_outputs: True to save build output files
45 step: 1 to process every commit, n to process every nth commit
d829f121
SG
46 work_in_output: Use the output directory as the work directory and
47 don't write to a separate output directory.
190064b4
SG
48 """
49 def __init__(self):
50 self.board = None
51 self.commits = []
e9fbbf63
SG
52 self.keep_outputs = False
53 self.step = 1
d829f121 54 self.work_in_output = False
190064b4
SG
55
56
57class ResultThread(threading.Thread):
58 """This thread processes results from builder threads.
59
60 It simply passes the results on to the builder. There is only one
61 result thread, and this helps to serialise the build output.
62 """
63 def __init__(self, builder):
64 """Set up a new result thread
65
66 Args:
67 builder: Builder which will be sent each result
68 """
69 threading.Thread.__init__(self)
70 self.builder = builder
71
72 def run(self):
73 """Called to start up the result thread.
74
75 We collect the next result job and pass it on to the build.
76 """
77 while True:
78 result = self.builder.out_queue.get()
79 self.builder.ProcessResult(result)
80 self.builder.out_queue.task_done()
81
82
83class BuilderThread(threading.Thread):
84 """This thread builds U-Boot for a particular board.
85
86 An input queue provides each new job. We run 'make' to build U-Boot
87 and then pass the results on to the output queue.
88
89 Members:
90 builder: The builder which contains information we might need
91 thread_num: Our thread number (0-n-1), used to decide on a
24993313
SG
92 temporary directory. If this is -1 then there are no threads
93 and we are the (only) main process
94 mrproper: Use 'make mrproper' before each reconfigure
95 per_board_out_dir: True to build in a separate persistent directory per
96 board rather than a thread-specific directory
97 test_exception: Used for testing; True to raise an exception instead of
98 reporting the build result
190064b4 99 """
8116c78f
SG
100 def __init__(self, builder, thread_num, mrproper, per_board_out_dir,
101 test_exception=False):
190064b4
SG
102 """Set up a new builder thread"""
103 threading.Thread.__init__(self)
104 self.builder = builder
105 self.thread_num = thread_num
eb70a2c0 106 self.mrproper = mrproper
f79f1e0c 107 self.per_board_out_dir = per_board_out_dir
8116c78f 108 self.test_exception = test_exception
190064b4
SG
109
110 def Make(self, commit, brd, stage, cwd, *args, **kwargs):
111 """Run 'make' on a particular commit and board.
112
113 The source code will already be checked out, so the 'commit'
114 argument is only for information.
115
116 Args:
117 commit: Commit object that is being built
118 brd: Board object that is being built
119 stage: Stage of the build. Valid stages are:
fd18a89e 120 mrproper - can be called to clean source
190064b4
SG
121 config - called to configure for a board
122 build - the main make invocation - it does the build
123 args: A list of arguments to pass to 'make'
124 kwargs: A list of keyword arguments to pass to command.RunPipe()
125
126 Returns:
127 CommandResult object
128 """
129 return self.builder.do_make(commit, brd, stage, cwd, *args,
130 **kwargs)
131
a9401b2b 132 def RunCommit(self, commit_upto, brd, work_dir, do_config, config_only,
d829f121 133 force_build, force_build_failures, work_in_output):
190064b4
SG
134 """Build a particular commit.
135
136 If the build is already done, and we are not forcing a build, we skip
137 the build and just return the previously-saved results.
138
139 Args:
140 commit_upto: Commit number to build (0...n-1)
141 brd: Board object to build
142 work_dir: Directory to which the source will be checked out
143 do_config: True to run a make <board>_defconfig on the source
a9401b2b 144 config_only: Only configure the source, do not build it
190064b4
SG
145 force_build: Force a build even if one was previously done
146 force_build_failures: Force a bulid if the previous result showed
147 failure
d829f121
SG
148 work_in_output: Use the output directory as the work directory and
149 don't write to a separate output directory.
190064b4
SG
150
151 Returns:
152 tuple containing:
153 - CommandResult object containing the results of the build
154 - boolean indicating whether 'make config' is still needed
155 """
156 # Create a default result - it will be overwritte by the call to
157 # self.Make() below, in the event that we do a build.
158 result = command.CommandResult()
159 result.return_code = 0
d829f121 160 if work_in_output or self.builder.in_tree:
190064b4
SG
161 out_dir = work_dir
162 else:
f79f1e0c
SW
163 if self.per_board_out_dir:
164 out_rel_dir = os.path.join('..', brd.target)
165 else:
166 out_rel_dir = 'build'
167 out_dir = os.path.join(work_dir, out_rel_dir)
190064b4
SG
168
169 # Check if the job was already completed last time
170 done_file = self.builder.GetDoneFile(commit_upto, brd.target)
171 result.already_done = os.path.exists(done_file)
172 will_build = (force_build or force_build_failures or
173 not result.already_done)
fb3954f9 174 if result.already_done:
190064b4
SG
175 # Get the return code from that build and use it
176 with open(done_file, 'r') as fd:
e74429bb
SG
177 try:
178 result.return_code = int(fd.readline())
179 except ValueError:
180 # The file may be empty due to running out of disk space.
181 # Try a rebuild
182 result.return_code = RETURN_CODE_RETRY
88c8dcf9
SG
183
184 # Check the signal that the build needs to be retried
185 if result.return_code == RETURN_CODE_RETRY:
186 will_build = True
187 elif will_build:
fb3954f9
SG
188 err_file = self.builder.GetErrFile(commit_upto, brd.target)
189 if os.path.exists(err_file) and os.stat(err_file).st_size:
190 result.stderr = 'bad'
191 elif not force_build:
192 # The build passed, so no need to build it again
193 will_build = False
190064b4
SG
194
195 if will_build:
196 # We are going to have to build it. First, get a toolchain
197 if not self.toolchain:
198 try:
199 self.toolchain = self.builder.toolchains.Select(brd.arch)
200 except ValueError as err:
201 result.return_code = 10
202 result.stdout = ''
203 result.stderr = str(err)
204 # TODO([email protected]): This gets swallowed, but needs
205 # to be reported.
206
207 if self.toolchain:
208 # Checkout the right commit
209 if self.builder.commits:
210 commit = self.builder.commits[commit_upto]
211 if self.builder.checkout:
212 git_dir = os.path.join(work_dir, '.git')
213 gitutil.Checkout(commit.hash, git_dir, work_dir,
214 force=True)
215 else:
216 commit = 'current'
217
218 # Set up the environment and command line
bb1501f2 219 env = self.toolchain.MakeEnvironment(self.builder.full_path)
190064b4
SG
220 Mkdir(out_dir)
221 args = []
222 cwd = work_dir
48c1b6a8 223 src_dir = os.path.realpath(work_dir)
190064b4
SG
224 if not self.builder.in_tree:
225 if commit_upto is None:
226 # In this case we are building in the original source
227 # directory (i.e. the current directory where buildman
228 # is invoked. The output directory is set to this
229 # thread's selected work directory.
230 #
231 # Symlinks can confuse U-Boot's Makefile since
232 # we may use '..' in our path, so remove them.
f79f1e0c
SW
233 out_dir = os.path.realpath(out_dir)
234 args.append('O=%s' % out_dir)
190064b4 235 cwd = None
48c1b6a8 236 src_dir = os.getcwd()
190064b4 237 else:
f79f1e0c 238 args.append('O=%s' % out_rel_dir)
f5e5ece0
TR
239 if self.builder.verbose_build:
240 args.append('V=1')
241 else:
d2ce658d 242 args.append('-s')
190064b4
SG
243 if self.builder.num_jobs is not None:
244 args.extend(['-j', str(self.builder.num_jobs)])
2371d1bc
DS
245 if self.builder.warnings_as_errors:
246 args.append('KCFLAGS=-Werror')
190064b4
SG
247 config_args = ['%s_defconfig' % brd.target]
248 config_out = ''
249 args.extend(self.builder.toolchains.GetMakeArguments(brd))
00beb248 250 args.extend(self.toolchain.MakeArgs())
190064b4 251
73da3d2c
SG
252 # Remove any output targets. Since we use a build directory that
253 # was previously used by another board, it may have produced an
254 # SPL image. If we don't remove it (i.e. see do_config and
255 # self.mrproper below) then it will appear to be the output of
256 # this build, even if it does not produce SPL images.
257 build_dir = self.builder.GetBuildDir(commit_upto, brd.target)
258 for elf in BASE_ELF_FILENAMES:
259 fname = os.path.join(out_dir, elf)
260 if os.path.exists(fname):
261 os.remove(fname)
262
190064b4
SG
263 # If we need to reconfigure, do that now
264 if do_config:
f79f1e0c 265 config_out = ''
eb70a2c0 266 if self.mrproper:
f79f1e0c
SW
267 result = self.Make(commit, brd, 'mrproper', cwd,
268 'mrproper', *args, env=env)
269 config_out += result.combined
190064b4
SG
270 result = self.Make(commit, brd, 'config', cwd,
271 *(args + config_args), env=env)
40f11fce 272 config_out += result.combined
190064b4
SG
273 do_config = False # No need to configure next time
274 if result.return_code == 0:
a9401b2b 275 if config_only:
b50113f3 276 args.append('cfg')
190064b4
SG
277 result = self.Make(commit, brd, 'build', cwd, *args,
278 env=env)
48c1b6a8 279 result.stderr = result.stderr.replace(src_dir + '/', '')
40f11fce
SG
280 if self.builder.verbose_build:
281 result.stdout = config_out + result.stdout
190064b4
SG
282 else:
283 result.return_code = 1
284 result.stderr = 'No tool chain for %s\n' % brd.arch
285 result.already_done = False
286
287 result.toolchain = self.toolchain
288 result.brd = brd
289 result.commit_upto = commit_upto
290 result.out_dir = out_dir
291 return result, do_config
292
d829f121 293 def _WriteResult(self, result, keep_outputs, work_in_output):
190064b4
SG
294 """Write a built result to the output directory.
295
296 Args:
297 result: CommandResult object containing result to write
298 keep_outputs: True to store the output binaries, False
299 to delete them
d829f121
SG
300 work_in_output: Use the output directory as the work directory and
301 don't write to a separate output directory.
190064b4
SG
302 """
303 # Fatal error
304 if result.return_code < 0:
305 return
306
88c8dcf9
SG
307 # If we think this might have been aborted with Ctrl-C, record the
308 # failure but not that we are 'done' with this board. A retry may fix
309 # it.
310 maybe_aborted = result.stderr and 'No child processes' in result.stderr
190064b4
SG
311
312 if result.already_done:
313 return
314
315 # Write the output and stderr
316 output_dir = self.builder._GetOutputDir(result.commit_upto)
317 Mkdir(output_dir)
318 build_dir = self.builder.GetBuildDir(result.commit_upto,
319 result.brd.target)
320 Mkdir(build_dir)
321
322 outfile = os.path.join(build_dir, 'log')
323 with open(outfile, 'w') as fd:
324 if result.stdout:
c05aa036 325 fd.write(result.stdout)
190064b4
SG
326
327 errfile = self.builder.GetErrFile(result.commit_upto,
328 result.brd.target)
329 if result.stderr:
330 with open(errfile, 'w') as fd:
c05aa036 331 fd.write(result.stderr)
190064b4
SG
332 elif os.path.exists(errfile):
333 os.remove(errfile)
334
335 if result.toolchain:
336 # Write the build result and toolchain information.
337 done_file = self.builder.GetDoneFile(result.commit_upto,
338 result.brd.target)
339 with open(done_file, 'w') as fd:
88c8dcf9
SG
340 if maybe_aborted:
341 # Special code to indicate we need to retry
342 fd.write('%s' % RETURN_CODE_RETRY)
343 else:
344 fd.write('%s' % result.return_code)
190064b4 345 with open(os.path.join(build_dir, 'toolchain'), 'w') as fd:
c05aa036
SG
346 print('gcc', result.toolchain.gcc, file=fd)
347 print('path', result.toolchain.path, file=fd)
348 print('cross', result.toolchain.cross, file=fd)
349 print('arch', result.toolchain.arch, file=fd)
190064b4
SG
350 fd.write('%s' % result.return_code)
351
190064b4 352 # Write out the image and function size information and an objdump
bb1501f2 353 env = result.toolchain.MakeEnvironment(self.builder.full_path)
5f86454b
SG
354 with open(os.path.join(build_dir, 'out-env'), 'w',
355 encoding='utf-8') as fd:
e5fc79ea 356 for var in sorted(env.keys()):
c05aa036 357 print('%s="%s"' % (var, env[var]), file=fd)
190064b4 358 lines = []
73da3d2c 359 for fname in BASE_ELF_FILENAMES:
190064b4
SG
360 cmd = ['%snm' % self.toolchain.cross, '--size-sort', fname]
361 nm_result = command.RunPipe([cmd], capture=True,
362 capture_stderr=True, cwd=result.out_dir,
363 raise_on_error=False, env=env)
364 if nm_result.stdout:
365 nm = self.builder.GetFuncSizesFile(result.commit_upto,
366 result.brd.target, fname)
367 with open(nm, 'w') as fd:
c05aa036 368 print(nm_result.stdout, end=' ', file=fd)
190064b4
SG
369
370 cmd = ['%sobjdump' % self.toolchain.cross, '-h', fname]
371 dump_result = command.RunPipe([cmd], capture=True,
372 capture_stderr=True, cwd=result.out_dir,
373 raise_on_error=False, env=env)
374 rodata_size = ''
375 if dump_result.stdout:
376 objdump = self.builder.GetObjdumpFile(result.commit_upto,
377 result.brd.target, fname)
378 with open(objdump, 'w') as fd:
c05aa036 379 print(dump_result.stdout, end=' ', file=fd)
190064b4
SG
380 for line in dump_result.stdout.splitlines():
381 fields = line.split()
382 if len(fields) > 5 and fields[1] == '.rodata':
383 rodata_size = fields[2]
384
385 cmd = ['%ssize' % self.toolchain.cross, fname]
386 size_result = command.RunPipe([cmd], capture=True,
387 capture_stderr=True, cwd=result.out_dir,
388 raise_on_error=False, env=env)
389 if size_result.stdout:
390 lines.append(size_result.stdout.splitlines()[1] + ' ' +
391 rodata_size)
392
0ddc510e
AK
393 # Extract the environment from U-Boot and dump it out
394 cmd = ['%sobjcopy' % self.toolchain.cross, '-O', 'binary',
395 '-j', '.rodata.default_environment',
396 'env/built-in.o', 'uboot.env']
397 command.RunPipe([cmd], capture=True,
398 capture_stderr=True, cwd=result.out_dir,
399 raise_on_error=False, env=env)
400 ubootenv = os.path.join(result.out_dir, 'uboot.env')
60b285f8
SG
401 if not work_in_output:
402 self.CopyFiles(result.out_dir, build_dir, '', ['uboot.env'])
0ddc510e 403
190064b4
SG
404 # Write out the image sizes file. This is similar to the output
405 # of binutil's 'size' utility, but it omits the header line and
406 # adds an additional hex value at the end of each line for the
407 # rodata size
408 if len(lines):
409 sizes = self.builder.GetSizesFile(result.commit_upto,
410 result.brd.target)
411 with open(sizes, 'w') as fd:
c05aa036 412 print('\n'.join(lines), file=fd)
190064b4 413
60b285f8
SG
414 if not work_in_output:
415 # Write out the configuration files, with a special case for SPL
416 for dirname in ['', 'spl', 'tpl']:
417 self.CopyFiles(
418 result.out_dir, build_dir, dirname,
419 ['u-boot.cfg', 'spl/u-boot-spl.cfg', 'tpl/u-boot-tpl.cfg',
420 '.config', 'include/autoconf.mk',
421 'include/generated/autoconf.h'])
422
423 # Now write the actual build output
424 if keep_outputs:
425 self.CopyFiles(
426 result.out_dir, build_dir, '',
427 ['u-boot*', '*.bin', '*.map', '*.img', 'MLO', 'SPL',
428 'include/autoconf.mk', 'spl/u-boot-spl*'])
970f932a
SG
429
430 def CopyFiles(self, out_dir, build_dir, dirname, patterns):
431 """Copy files from the build directory to the output.
190064b4 432
970f932a
SG
433 Args:
434 out_dir: Path to output directory containing the files
435 build_dir: Place to copy the files
436 dirname: Source directory, '' for normal U-Boot, 'spl' for SPL
437 patterns: A list of filenames (strings) to copy, each relative
438 to the build directory
439 """
440 for pattern in patterns:
441 file_list = glob.glob(os.path.join(out_dir, dirname, pattern))
442 for fname in file_list:
443 target = os.path.basename(fname)
444 if dirname:
445 base, ext = os.path.splitext(target)
446 if ext:
447 target = '%s-%s%s' % (base, dirname, ext)
448 shutil.copy(fname, os.path.join(build_dir, target))
190064b4 449
ab9b4f35
SG
450 def _SendResult(self, result):
451 """Send a result to the builder for processing
452
453 Args:
454 result: CommandResult object containing the results of the build
8116c78f
SG
455
456 Raises:
457 ValueError if self.test_exception is true (for testing)
ab9b4f35 458 """
8116c78f
SG
459 if self.test_exception:
460 raise ValueError('test exception')
ab9b4f35
SG
461 if self.thread_num != -1:
462 self.builder.out_queue.put(result)
463 else:
464 self.builder.ProcessResult(result)
465
190064b4
SG
466 def RunJob(self, job):
467 """Run a single job
468
469 A job consists of a building a list of commits for a particular board.
470
471 Args:
472 job: Job to build
b82492bb
SG
473
474 Returns:
475 List of Result objects
190064b4
SG
476 """
477 brd = job.board
478 work_dir = self.builder.GetThreadDir(self.thread_num)
479 self.toolchain = None
480 if job.commits:
481 # Run 'make board_defconfig' on the first commit
482 do_config = True
483 commit_upto = 0
484 force_build = False
485 for commit_upto in range(0, len(job.commits), job.step):
486 result, request_config = self.RunCommit(commit_upto, brd,
a9401b2b 487 work_dir, do_config, self.builder.config_only,
190064b4 488 force_build or self.builder.force_build,
d829f121
SG
489 self.builder.force_build_failures,
490 work_in_output=job.work_in_output)
190064b4
SG
491 failed = result.return_code or result.stderr
492 did_config = do_config
493 if failed and not do_config:
494 # If our incremental build failed, try building again
495 # with a reconfig.
496 if self.builder.force_config_on_failure:
497 result, request_config = self.RunCommit(commit_upto,
d829f121
SG
498 brd, work_dir, True, False, True, False,
499 work_in_output=job.work_in_output)
190064b4
SG
500 did_config = True
501 if not self.builder.force_reconfig:
502 do_config = request_config
503
504 # If we built that commit, then config is done. But if we got
505 # an warning, reconfig next time to force it to build the same
506 # files that created warnings this time. Otherwise an
507 # incremental build may not build the same file, and we will
508 # think that the warning has gone away.
509 # We could avoid this by using -Werror everywhere...
510 # For errors, the problem doesn't happen, since presumably
511 # the build stopped and didn't generate output, so will retry
512 # that file next time. So we could detect warnings and deal
513 # with them specially here. For now, we just reconfigure if
514 # anything goes work.
515 # Of course this is substantially slower if there are build
516 # errors/warnings (e.g. 2-3x slower even if only 10% of builds
517 # have problems).
518 if (failed and not result.already_done and not did_config and
519 self.builder.force_config_on_failure):
520 # If this build failed, try the next one with a
521 # reconfigure.
522 # Sometimes if the board_config.h file changes it can mess
523 # with dependencies, and we get:
524 # make: *** No rule to make target `include/autoconf.mk',
525 # needed by `depend'.
526 do_config = True
527 force_build = True
528 else:
529 force_build = False
530 if self.builder.force_config_on_failure:
531 if failed:
532 do_config = True
533 result.commit_upto = commit_upto
534 if result.return_code < 0:
535 raise ValueError('Interrupt')
536
537 # We have the build results, so output the result
d829f121 538 self._WriteResult(result, job.keep_outputs, job.work_in_output)
ab9b4f35 539 self._SendResult(result)
190064b4
SG
540 else:
541 # Just build the currently checked-out build
542 result, request_config = self.RunCommit(None, brd, work_dir, True,
a9401b2b 543 self.builder.config_only, True,
d829f121
SG
544 self.builder.force_build_failures,
545 work_in_output=job.work_in_output)
190064b4 546 result.commit_upto = 0
d829f121 547 self._WriteResult(result, job.keep_outputs, job.work_in_output)
ab9b4f35 548 self._SendResult(result)
190064b4
SG
549
550 def run(self):
551 """Our thread's run function
552
553 This thread picks a job from the queue, runs it, and then goes to the
554 next job.
555 """
190064b4
SG
556 while True:
557 job = self.builder.queue.get()
8116c78f
SG
558 try:
559 self.RunJob(job)
560 except Exception as e:
561 print('Thread exception:', e)
562 self.builder.thread_exceptions.append(e)
190064b4 563 self.builder.queue.task_done()
This page took 0.381198 seconds and 4 git commands to generate.