builder.py 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168
  1. # Copyright (c) 2013 The Chromium OS Authors.
  2. #
  3. # Bloat-o-meter code used here Copyright 2004 Matt Mackall <mpm@selenic.com>
  4. #
  5. # SPDX-License-Identifier: GPL-2.0+
  6. #
  7. import collections
  8. from datetime import datetime, timedelta
  9. import glob
  10. import os
  11. import re
  12. import Queue
  13. import shutil
  14. import string
  15. import sys
  16. import time
  17. import builderthread
  18. import command
  19. import gitutil
  20. import terminal
  21. from terminal import Print
  22. import toolchain
  23. """
  24. Theory of Operation
  25. Please see README for user documentation, and you should be familiar with
  26. that before trying to make sense of this.
  27. Buildman works by keeping the machine as busy as possible, building different
  28. commits for different boards on multiple CPUs at once.
  29. The source repo (self.git_dir) contains all the commits to be built. Each
  30. thread works on a single board at a time. It checks out the first commit,
  31. configures it for that board, then builds it. Then it checks out the next
  32. commit and builds it (typically without re-configuring). When it runs out
  33. of commits, it gets another job from the builder and starts again with that
  34. board.
  35. Clearly the builder threads could work either way - they could check out a
  36. commit and then built it for all boards. Using separate directories for each
  37. commit/board pair they could leave their build product around afterwards
  38. also.
  39. The intent behind building a single board for multiple commits, is to make
  40. use of incremental builds. Since each commit is built incrementally from
  41. the previous one, builds are faster. Reconfiguring for a different board
  42. removes all intermediate object files.
  43. Many threads can be working at once, but each has its own working directory.
  44. When a thread finishes a build, it puts the output files into a result
  45. directory.
  46. The base directory used by buildman is normally '../<branch>', i.e.
  47. a directory higher than the source repository and named after the branch
  48. being built.
  49. Within the base directory, we have one subdirectory for each commit. Within
  50. that is one subdirectory for each board. Within that is the build output for
  51. that commit/board combination.
  52. Buildman also create working directories for each thread, in a .bm-work/
  53. subdirectory in the base dir.
  54. As an example, say we are building branch 'us-net' for boards 'sandbox' and
  55. 'seaboard', and say that us-net has two commits. We will have directories
  56. like this:
  57. us-net/ base directory
  58. 01_of_02_g4ed4ebc_net--Add-tftp-speed-/
  59. sandbox/
  60. u-boot.bin
  61. seaboard/
  62. u-boot.bin
  63. 02_of_02_g4ed4ebc_net--Check-tftp-comp/
  64. sandbox/
  65. u-boot.bin
  66. seaboard/
  67. u-boot.bin
  68. .bm-work/
  69. 00/ working directory for thread 0 (contains source checkout)
  70. build/ build output
  71. 01/ working directory for thread 1
  72. build/ build output
  73. ...
  74. u-boot/ source directory
  75. .git/ repository
  76. """
  77. # Possible build outcomes
  78. OUTCOME_OK, OUTCOME_WARNING, OUTCOME_ERROR, OUTCOME_UNKNOWN = range(4)
  79. # Translate a commit subject into a valid filename
  80. trans_valid_chars = string.maketrans("/: ", "---")
  81. class Builder:
  82. """Class for building U-Boot for a particular commit.
  83. Public members: (many should ->private)
  84. active: True if the builder is active and has not been stopped
  85. already_done: Number of builds already completed
  86. base_dir: Base directory to use for builder
  87. checkout: True to check out source, False to skip that step.
  88. This is used for testing.
  89. col: terminal.Color() object
  90. count: Number of commits to build
  91. do_make: Method to call to invoke Make
  92. fail: Number of builds that failed due to error
  93. force_build: Force building even if a build already exists
  94. force_config_on_failure: If a commit fails for a board, disable
  95. incremental building for the next commit we build for that
  96. board, so that we will see all warnings/errors again.
  97. force_build_failures: If a previously-built build (i.e. built on
  98. a previous run of buildman) is marked as failed, rebuild it.
  99. git_dir: Git directory containing source repository
  100. last_line_len: Length of the last line we printed (used for erasing
  101. it with new progress information)
  102. num_jobs: Number of jobs to run at once (passed to make as -j)
  103. num_threads: Number of builder threads to run
  104. out_queue: Queue of results to process
  105. re_make_err: Compiled regular expression for ignore_lines
  106. queue: Queue of jobs to run
  107. threads: List of active threads
  108. toolchains: Toolchains object to use for building
  109. upto: Current commit number we are building (0.count-1)
  110. warned: Number of builds that produced at least one warning
  111. force_reconfig: Reconfigure U-Boot on each comiit. This disables
  112. incremental building, where buildman reconfigures on the first
  113. commit for a baord, and then just does an incremental build for
  114. the following commits. In fact buildman will reconfigure and
  115. retry for any failing commits, so generally the only effect of
  116. this option is to slow things down.
  117. in_tree: Build U-Boot in-tree instead of specifying an output
  118. directory separate from the source code. This option is really
  119. only useful for testing in-tree builds.
  120. Private members:
  121. _base_board_dict: Last-summarised Dict of boards
  122. _base_err_lines: Last-summarised list of errors
  123. _base_warn_lines: Last-summarised list of warnings
  124. _build_period_us: Time taken for a single build (float object).
  125. _complete_delay: Expected delay until completion (timedelta)
  126. _next_delay_update: Next time we plan to display a progress update
  127. (datatime)
  128. _show_unknown: Show unknown boards (those not built) in summary
  129. _timestamps: List of timestamps for the completion of the last
  130. last _timestamp_count builds. Each is a datetime object.
  131. _timestamp_count: Number of timestamps to keep in our list.
  132. _working_dir: Base working directory containing all threads
  133. """
  134. class Outcome:
  135. """Records a build outcome for a single make invocation
  136. Public Members:
  137. rc: Outcome value (OUTCOME_...)
  138. err_lines: List of error lines or [] if none
  139. sizes: Dictionary of image size information, keyed by filename
  140. - Each value is itself a dictionary containing
  141. values for 'text', 'data' and 'bss', being the integer
  142. size in bytes of each section.
  143. func_sizes: Dictionary keyed by filename - e.g. 'u-boot'. Each
  144. value is itself a dictionary:
  145. key: function name
  146. value: Size of function in bytes
  147. """
  148. def __init__(self, rc, err_lines, sizes, func_sizes):
  149. self.rc = rc
  150. self.err_lines = err_lines
  151. self.sizes = sizes
  152. self.func_sizes = func_sizes
  153. def __init__(self, toolchains, base_dir, git_dir, num_threads, num_jobs,
  154. gnu_make='make', checkout=True, show_unknown=True, step=1):
  155. """Create a new Builder object
  156. Args:
  157. toolchains: Toolchains object to use for building
  158. base_dir: Base directory to use for builder
  159. git_dir: Git directory containing source repository
  160. num_threads: Number of builder threads to run
  161. num_jobs: Number of jobs to run at once (passed to make as -j)
  162. gnu_make: the command name of GNU Make.
  163. checkout: True to check out source, False to skip that step.
  164. This is used for testing.
  165. show_unknown: Show unknown boards (those not built) in summary
  166. step: 1 to process every commit, n to process every nth commit
  167. """
  168. self.toolchains = toolchains
  169. self.base_dir = base_dir
  170. self._working_dir = os.path.join(base_dir, '.bm-work')
  171. self.threads = []
  172. self.active = True
  173. self.do_make = self.Make
  174. self.gnu_make = gnu_make
  175. self.checkout = checkout
  176. self.num_threads = num_threads
  177. self.num_jobs = num_jobs
  178. self.already_done = 0
  179. self.force_build = False
  180. self.git_dir = git_dir
  181. self._show_unknown = show_unknown
  182. self._timestamp_count = 10
  183. self._build_period_us = None
  184. self._complete_delay = None
  185. self._next_delay_update = datetime.now()
  186. self.force_config_on_failure = True
  187. self.force_build_failures = False
  188. self.force_reconfig = False
  189. self._step = step
  190. self.in_tree = False
  191. self._error_lines = 0
  192. self.col = terminal.Color()
  193. self._re_function = re.compile('(.*): In function.*')
  194. self._re_files = re.compile('In file included from.*')
  195. self._re_warning = re.compile('(.*):(\d*):(\d*): warning: .*')
  196. self._re_note = re.compile('(.*):(\d*):(\d*): note: this is the location of the previous.*')
  197. self.queue = Queue.Queue()
  198. self.out_queue = Queue.Queue()
  199. for i in range(self.num_threads):
  200. t = builderthread.BuilderThread(self, i)
  201. t.setDaemon(True)
  202. t.start()
  203. self.threads.append(t)
  204. self.last_line_len = 0
  205. t = builderthread.ResultThread(self)
  206. t.setDaemon(True)
  207. t.start()
  208. self.threads.append(t)
  209. ignore_lines = ['(make.*Waiting for unfinished)', '(Segmentation fault)']
  210. self.re_make_err = re.compile('|'.join(ignore_lines))
  211. def __del__(self):
  212. """Get rid of all threads created by the builder"""
  213. for t in self.threads:
  214. del t
  215. def SetDisplayOptions(self, show_errors=False, show_sizes=False,
  216. show_detail=False, show_bloat=False,
  217. list_error_boards=False):
  218. """Setup display options for the builder.
  219. show_errors: True to show summarised error/warning info
  220. show_sizes: Show size deltas
  221. show_detail: Show detail for each board
  222. show_bloat: Show detail for each function
  223. list_error_boards: Show the boards which caused each error/warning
  224. """
  225. self._show_errors = show_errors
  226. self._show_sizes = show_sizes
  227. self._show_detail = show_detail
  228. self._show_bloat = show_bloat
  229. self._list_error_boards = list_error_boards
  230. def _AddTimestamp(self):
  231. """Add a new timestamp to the list and record the build period.
  232. The build period is the length of time taken to perform a single
  233. build (one board, one commit).
  234. """
  235. now = datetime.now()
  236. self._timestamps.append(now)
  237. count = len(self._timestamps)
  238. delta = self._timestamps[-1] - self._timestamps[0]
  239. seconds = delta.total_seconds()
  240. # If we have enough data, estimate build period (time taken for a
  241. # single build) and therefore completion time.
  242. if count > 1 and self._next_delay_update < now:
  243. self._next_delay_update = now + timedelta(seconds=2)
  244. if seconds > 0:
  245. self._build_period = float(seconds) / count
  246. todo = self.count - self.upto
  247. self._complete_delay = timedelta(microseconds=
  248. self._build_period * todo * 1000000)
  249. # Round it
  250. self._complete_delay -= timedelta(
  251. microseconds=self._complete_delay.microseconds)
  252. if seconds > 60:
  253. self._timestamps.popleft()
  254. count -= 1
  255. def ClearLine(self, length):
  256. """Clear any characters on the current line
  257. Make way for a new line of length 'length', by outputting enough
  258. spaces to clear out the old line. Then remember the new length for
  259. next time.
  260. Args:
  261. length: Length of new line, in characters
  262. """
  263. if length < self.last_line_len:
  264. Print(' ' * (self.last_line_len - length), newline=False)
  265. Print('\r', newline=False)
  266. self.last_line_len = length
  267. sys.stdout.flush()
  268. def SelectCommit(self, commit, checkout=True):
  269. """Checkout the selected commit for this build
  270. """
  271. self.commit = commit
  272. if checkout and self.checkout:
  273. gitutil.Checkout(commit.hash)
  274. def Make(self, commit, brd, stage, cwd, *args, **kwargs):
  275. """Run make
  276. Args:
  277. commit: Commit object that is being built
  278. brd: Board object that is being built
  279. stage: Stage that we are at (mrproper, config, build)
  280. cwd: Directory where make should be run
  281. args: Arguments to pass to make
  282. kwargs: Arguments to pass to command.RunPipe()
  283. """
  284. cmd = [self.gnu_make] + list(args)
  285. result = command.RunPipe([cmd], capture=True, capture_stderr=True,
  286. cwd=cwd, raise_on_error=False, **kwargs)
  287. return result
  288. def ProcessResult(self, result):
  289. """Process the result of a build, showing progress information
  290. Args:
  291. result: A CommandResult object, which indicates the result for
  292. a single build
  293. """
  294. col = terminal.Color()
  295. if result:
  296. target = result.brd.target
  297. if result.return_code < 0:
  298. self.active = False
  299. command.StopAll()
  300. return
  301. self.upto += 1
  302. if result.return_code != 0:
  303. self.fail += 1
  304. elif result.stderr:
  305. self.warned += 1
  306. if result.already_done:
  307. self.already_done += 1
  308. if self._verbose:
  309. Print('\r', newline=False)
  310. self.ClearLine(0)
  311. boards_selected = {target : result.brd}
  312. self.ResetResultSummary(boards_selected)
  313. self.ProduceResultSummary(result.commit_upto, self.commits,
  314. boards_selected)
  315. else:
  316. target = '(starting)'
  317. # Display separate counts for ok, warned and fail
  318. ok = self.upto - self.warned - self.fail
  319. line = '\r' + self.col.Color(self.col.GREEN, '%5d' % ok)
  320. line += self.col.Color(self.col.YELLOW, '%5d' % self.warned)
  321. line += self.col.Color(self.col.RED, '%5d' % self.fail)
  322. name = ' /%-5d ' % self.count
  323. # Add our current completion time estimate
  324. self._AddTimestamp()
  325. if self._complete_delay:
  326. name += '%s : ' % self._complete_delay
  327. # When building all boards for a commit, we can print a commit
  328. # progress message.
  329. if result and result.commit_upto is None:
  330. name += 'commit %2d/%-3d' % (self.commit_upto + 1,
  331. self.commit_count)
  332. name += target
  333. Print(line + name, newline=False)
  334. length = 14 + len(name)
  335. self.ClearLine(length)
  336. def _GetOutputDir(self, commit_upto):
  337. """Get the name of the output directory for a commit number
  338. The output directory is typically .../<branch>/<commit>.
  339. Args:
  340. commit_upto: Commit number to use (0..self.count-1)
  341. """
  342. if self.commits:
  343. commit = self.commits[commit_upto]
  344. subject = commit.subject.translate(trans_valid_chars)
  345. commit_dir = ('%02d_of_%02d_g%s_%s' % (commit_upto + 1,
  346. self.commit_count, commit.hash, subject[:20]))
  347. else:
  348. commit_dir = 'current'
  349. output_dir = os.path.join(self.base_dir, commit_dir)
  350. return output_dir
  351. def GetBuildDir(self, commit_upto, target):
  352. """Get the name of the build directory for a commit number
  353. The build directory is typically .../<branch>/<commit>/<target>.
  354. Args:
  355. commit_upto: Commit number to use (0..self.count-1)
  356. target: Target name
  357. """
  358. output_dir = self._GetOutputDir(commit_upto)
  359. return os.path.join(output_dir, target)
  360. def GetDoneFile(self, commit_upto, target):
  361. """Get the name of the done file for a commit number
  362. Args:
  363. commit_upto: Commit number to use (0..self.count-1)
  364. target: Target name
  365. """
  366. return os.path.join(self.GetBuildDir(commit_upto, target), 'done')
  367. def GetSizesFile(self, commit_upto, target):
  368. """Get the name of the sizes file for a commit number
  369. Args:
  370. commit_upto: Commit number to use (0..self.count-1)
  371. target: Target name
  372. """
  373. return os.path.join(self.GetBuildDir(commit_upto, target), 'sizes')
  374. def GetFuncSizesFile(self, commit_upto, target, elf_fname):
  375. """Get the name of the funcsizes file for a commit number and ELF file
  376. Args:
  377. commit_upto: Commit number to use (0..self.count-1)
  378. target: Target name
  379. elf_fname: Filename of elf image
  380. """
  381. return os.path.join(self.GetBuildDir(commit_upto, target),
  382. '%s.sizes' % elf_fname.replace('/', '-'))
  383. def GetObjdumpFile(self, commit_upto, target, elf_fname):
  384. """Get the name of the objdump file for a commit number and ELF file
  385. Args:
  386. commit_upto: Commit number to use (0..self.count-1)
  387. target: Target name
  388. elf_fname: Filename of elf image
  389. """
  390. return os.path.join(self.GetBuildDir(commit_upto, target),
  391. '%s.objdump' % elf_fname.replace('/', '-'))
  392. def GetErrFile(self, commit_upto, target):
  393. """Get the name of the err file for a commit number
  394. Args:
  395. commit_upto: Commit number to use (0..self.count-1)
  396. target: Target name
  397. """
  398. output_dir = self.GetBuildDir(commit_upto, target)
  399. return os.path.join(output_dir, 'err')
  400. def FilterErrors(self, lines):
  401. """Filter out errors in which we have no interest
  402. We should probably use map().
  403. Args:
  404. lines: List of error lines, each a string
  405. Returns:
  406. New list with only interesting lines included
  407. """
  408. out_lines = []
  409. for line in lines:
  410. if not self.re_make_err.search(line):
  411. out_lines.append(line)
  412. return out_lines
  413. def ReadFuncSizes(self, fname, fd):
  414. """Read function sizes from the output of 'nm'
  415. Args:
  416. fd: File containing data to read
  417. fname: Filename we are reading from (just for errors)
  418. Returns:
  419. Dictionary containing size of each function in bytes, indexed by
  420. function name.
  421. """
  422. sym = {}
  423. for line in fd.readlines():
  424. try:
  425. size, type, name = line[:-1].split()
  426. except:
  427. Print("Invalid line in file '%s': '%s'" % (fname, line[:-1]))
  428. continue
  429. if type in 'tTdDbB':
  430. # function names begin with '.' on 64-bit powerpc
  431. if '.' in name[1:]:
  432. name = 'static.' + name.split('.')[0]
  433. sym[name] = sym.get(name, 0) + int(size, 16)
  434. return sym
  435. def GetBuildOutcome(self, commit_upto, target, read_func_sizes):
  436. """Work out the outcome of a build.
  437. Args:
  438. commit_upto: Commit number to check (0..n-1)
  439. target: Target board to check
  440. read_func_sizes: True to read function size information
  441. Returns:
  442. Outcome object
  443. """
  444. done_file = self.GetDoneFile(commit_upto, target)
  445. sizes_file = self.GetSizesFile(commit_upto, target)
  446. sizes = {}
  447. func_sizes = {}
  448. if os.path.exists(done_file):
  449. with open(done_file, 'r') as fd:
  450. return_code = int(fd.readline())
  451. err_lines = []
  452. err_file = self.GetErrFile(commit_upto, target)
  453. if os.path.exists(err_file):
  454. with open(err_file, 'r') as fd:
  455. err_lines = self.FilterErrors(fd.readlines())
  456. # Decide whether the build was ok, failed or created warnings
  457. if return_code:
  458. rc = OUTCOME_ERROR
  459. elif len(err_lines):
  460. rc = OUTCOME_WARNING
  461. else:
  462. rc = OUTCOME_OK
  463. # Convert size information to our simple format
  464. if os.path.exists(sizes_file):
  465. with open(sizes_file, 'r') as fd:
  466. for line in fd.readlines():
  467. values = line.split()
  468. rodata = 0
  469. if len(values) > 6:
  470. rodata = int(values[6], 16)
  471. size_dict = {
  472. 'all' : int(values[0]) + int(values[1]) +
  473. int(values[2]),
  474. 'text' : int(values[0]) - rodata,
  475. 'data' : int(values[1]),
  476. 'bss' : int(values[2]),
  477. 'rodata' : rodata,
  478. }
  479. sizes[values[5]] = size_dict
  480. if read_func_sizes:
  481. pattern = self.GetFuncSizesFile(commit_upto, target, '*')
  482. for fname in glob.glob(pattern):
  483. with open(fname, 'r') as fd:
  484. dict_name = os.path.basename(fname).replace('.sizes',
  485. '')
  486. func_sizes[dict_name] = self.ReadFuncSizes(fname, fd)
  487. return Builder.Outcome(rc, err_lines, sizes, func_sizes)
  488. return Builder.Outcome(OUTCOME_UNKNOWN, [], {}, {})
  489. def GetResultSummary(self, boards_selected, commit_upto, read_func_sizes):
  490. """Calculate a summary of the results of building a commit.
  491. Args:
  492. board_selected: Dict containing boards to summarise
  493. commit_upto: Commit number to summarize (0..self.count-1)
  494. read_func_sizes: True to read function size information
  495. Returns:
  496. Tuple:
  497. Dict containing boards which passed building this commit.
  498. keyed by board.target
  499. List containing a summary of error lines
  500. Dict keyed by error line, containing a list of the Board
  501. objects with that error
  502. List containing a summary of warning lines
  503. Dict keyed by error line, containing a list of the Board
  504. objects with that warning
  505. """
  506. def AddLine(lines_summary, lines_boards, line, board):
  507. line = line.rstrip()
  508. if line in lines_boards:
  509. lines_boards[line].append(board)
  510. else:
  511. lines_boards[line] = [board]
  512. lines_summary.append(line)
  513. board_dict = {}
  514. err_lines_summary = []
  515. err_lines_boards = {}
  516. warn_lines_summary = []
  517. warn_lines_boards = {}
  518. for board in boards_selected.itervalues():
  519. outcome = self.GetBuildOutcome(commit_upto, board.target,
  520. read_func_sizes)
  521. board_dict[board.target] = outcome
  522. last_func = None
  523. last_was_warning = False
  524. for line in outcome.err_lines:
  525. if line:
  526. if (self._re_function.match(line) or
  527. self._re_files.match(line)):
  528. last_func = line
  529. else:
  530. is_warning = self._re_warning.match(line)
  531. is_note = self._re_note.match(line)
  532. if is_warning or (last_was_warning and is_note):
  533. if last_func:
  534. AddLine(warn_lines_summary, warn_lines_boards,
  535. last_func, board)
  536. AddLine(warn_lines_summary, warn_lines_boards,
  537. line, board)
  538. else:
  539. if last_func:
  540. AddLine(err_lines_summary, err_lines_boards,
  541. last_func, board)
  542. AddLine(err_lines_summary, err_lines_boards,
  543. line, board)
  544. last_was_warning = is_warning
  545. last_func = None
  546. return (board_dict, err_lines_summary, err_lines_boards,
  547. warn_lines_summary, warn_lines_boards)
  548. def AddOutcome(self, board_dict, arch_list, changes, char, color):
  549. """Add an output to our list of outcomes for each architecture
  550. This simple function adds failing boards (changes) to the
  551. relevant architecture string, so we can print the results out
  552. sorted by architecture.
  553. Args:
  554. board_dict: Dict containing all boards
  555. arch_list: Dict keyed by arch name. Value is a string containing
  556. a list of board names which failed for that arch.
  557. changes: List of boards to add to arch_list
  558. color: terminal.Colour object
  559. """
  560. done_arch = {}
  561. for target in changes:
  562. if target in board_dict:
  563. arch = board_dict[target].arch
  564. else:
  565. arch = 'unknown'
  566. str = self.col.Color(color, ' ' + target)
  567. if not arch in done_arch:
  568. str = self.col.Color(color, char) + ' ' + str
  569. done_arch[arch] = True
  570. if not arch in arch_list:
  571. arch_list[arch] = str
  572. else:
  573. arch_list[arch] += str
  574. def ColourNum(self, num):
  575. color = self.col.RED if num > 0 else self.col.GREEN
  576. if num == 0:
  577. return '0'
  578. return self.col.Color(color, str(num))
  579. def ResetResultSummary(self, board_selected):
  580. """Reset the results summary ready for use.
  581. Set up the base board list to be all those selected, and set the
  582. error lines to empty.
  583. Following this, calls to PrintResultSummary() will use this
  584. information to work out what has changed.
  585. Args:
  586. board_selected: Dict containing boards to summarise, keyed by
  587. board.target
  588. """
  589. self._base_board_dict = {}
  590. for board in board_selected:
  591. self._base_board_dict[board] = Builder.Outcome(0, [], [], {})
  592. self._base_err_lines = []
  593. self._base_warn_lines = []
  594. self._base_err_line_boards = {}
  595. self._base_warn_line_boards = {}
  596. def PrintFuncSizeDetail(self, fname, old, new):
  597. grow, shrink, add, remove, up, down = 0, 0, 0, 0, 0, 0
  598. delta, common = [], {}
  599. for a in old:
  600. if a in new:
  601. common[a] = 1
  602. for name in old:
  603. if name not in common:
  604. remove += 1
  605. down += old[name]
  606. delta.append([-old[name], name])
  607. for name in new:
  608. if name not in common:
  609. add += 1
  610. up += new[name]
  611. delta.append([new[name], name])
  612. for name in common:
  613. diff = new.get(name, 0) - old.get(name, 0)
  614. if diff > 0:
  615. grow, up = grow + 1, up + diff
  616. elif diff < 0:
  617. shrink, down = shrink + 1, down - diff
  618. delta.append([diff, name])
  619. delta.sort()
  620. delta.reverse()
  621. args = [add, -remove, grow, -shrink, up, -down, up - down]
  622. if max(args) == 0:
  623. return
  624. args = [self.ColourNum(x) for x in args]
  625. indent = ' ' * 15
  626. Print('%s%s: add: %s/%s, grow: %s/%s bytes: %s/%s (%s)' %
  627. tuple([indent, self.col.Color(self.col.YELLOW, fname)] + args))
  628. Print('%s %-38s %7s %7s %+7s' % (indent, 'function', 'old', 'new',
  629. 'delta'))
  630. for diff, name in delta:
  631. if diff:
  632. color = self.col.RED if diff > 0 else self.col.GREEN
  633. msg = '%s %-38s %7s %7s %+7d' % (indent, name,
  634. old.get(name, '-'), new.get(name,'-'), diff)
  635. Print(msg, colour=color)
  636. def PrintSizeDetail(self, target_list, show_bloat):
  637. """Show details size information for each board
  638. Args:
  639. target_list: List of targets, each a dict containing:
  640. 'target': Target name
  641. 'total_diff': Total difference in bytes across all areas
  642. <part_name>: Difference for that part
  643. show_bloat: Show detail for each function
  644. """
  645. targets_by_diff = sorted(target_list, reverse=True,
  646. key=lambda x: x['_total_diff'])
  647. for result in targets_by_diff:
  648. printed_target = False
  649. for name in sorted(result):
  650. diff = result[name]
  651. if name.startswith('_'):
  652. continue
  653. if diff != 0:
  654. color = self.col.RED if diff > 0 else self.col.GREEN
  655. msg = ' %s %+d' % (name, diff)
  656. if not printed_target:
  657. Print('%10s %-15s:' % ('', result['_target']),
  658. newline=False)
  659. printed_target = True
  660. Print(msg, colour=color, newline=False)
  661. if printed_target:
  662. Print()
  663. if show_bloat:
  664. target = result['_target']
  665. outcome = result['_outcome']
  666. base_outcome = self._base_board_dict[target]
  667. for fname in outcome.func_sizes:
  668. self.PrintFuncSizeDetail(fname,
  669. base_outcome.func_sizes[fname],
  670. outcome.func_sizes[fname])
  671. def PrintSizeSummary(self, board_selected, board_dict, show_detail,
  672. show_bloat):
  673. """Print a summary of image sizes broken down by section.
  674. The summary takes the form of one line per architecture. The
  675. line contains deltas for each of the sections (+ means the section
  676. got bigger, - means smaller). The nunmbers are the average number
  677. of bytes that a board in this section increased by.
  678. For example:
  679. powerpc: (622 boards) text -0.0
  680. arm: (285 boards) text -0.0
  681. nds32: (3 boards) text -8.0
  682. Args:
  683. board_selected: Dict containing boards to summarise, keyed by
  684. board.target
  685. board_dict: Dict containing boards for which we built this
  686. commit, keyed by board.target. The value is an Outcome object.
  687. show_detail: Show detail for each board
  688. show_bloat: Show detail for each function
  689. """
  690. arch_list = {}
  691. arch_count = {}
  692. # Calculate changes in size for different image parts
  693. # The previous sizes are in Board.sizes, for each board
  694. for target in board_dict:
  695. if target not in board_selected:
  696. continue
  697. base_sizes = self._base_board_dict[target].sizes
  698. outcome = board_dict[target]
  699. sizes = outcome.sizes
  700. # Loop through the list of images, creating a dict of size
  701. # changes for each image/part. We end up with something like
  702. # {'target' : 'snapper9g45, 'data' : 5, 'u-boot-spl:text' : -4}
  703. # which means that U-Boot data increased by 5 bytes and SPL
  704. # text decreased by 4.
  705. err = {'_target' : target}
  706. for image in sizes:
  707. if image in base_sizes:
  708. base_image = base_sizes[image]
  709. # Loop through the text, data, bss parts
  710. for part in sorted(sizes[image]):
  711. diff = sizes[image][part] - base_image[part]
  712. col = None
  713. if diff:
  714. if image == 'u-boot':
  715. name = part
  716. else:
  717. name = image + ':' + part
  718. err[name] = diff
  719. arch = board_selected[target].arch
  720. if not arch in arch_count:
  721. arch_count[arch] = 1
  722. else:
  723. arch_count[arch] += 1
  724. if not sizes:
  725. pass # Only add to our list when we have some stats
  726. elif not arch in arch_list:
  727. arch_list[arch] = [err]
  728. else:
  729. arch_list[arch].append(err)
  730. # We now have a list of image size changes sorted by arch
  731. # Print out a summary of these
  732. for arch, target_list in arch_list.iteritems():
  733. # Get total difference for each type
  734. totals = {}
  735. for result in target_list:
  736. total = 0
  737. for name, diff in result.iteritems():
  738. if name.startswith('_'):
  739. continue
  740. total += diff
  741. if name in totals:
  742. totals[name] += diff
  743. else:
  744. totals[name] = diff
  745. result['_total_diff'] = total
  746. result['_outcome'] = board_dict[result['_target']]
  747. count = len(target_list)
  748. printed_arch = False
  749. for name in sorted(totals):
  750. diff = totals[name]
  751. if diff:
  752. # Display the average difference in this name for this
  753. # architecture
  754. avg_diff = float(diff) / count
  755. color = self.col.RED if avg_diff > 0 else self.col.GREEN
  756. msg = ' %s %+1.1f' % (name, avg_diff)
  757. if not printed_arch:
  758. Print('%10s: (for %d/%d boards)' % (arch, count,
  759. arch_count[arch]), newline=False)
  760. printed_arch = True
  761. Print(msg, colour=color, newline=False)
  762. if printed_arch:
  763. Print()
  764. if show_detail:
  765. self.PrintSizeDetail(target_list, show_bloat)
  766. def PrintResultSummary(self, board_selected, board_dict, err_lines,
  767. err_line_boards, warn_lines, warn_line_boards,
  768. show_sizes, show_detail, show_bloat):
  769. """Compare results with the base results and display delta.
  770. Only boards mentioned in board_selected will be considered. This
  771. function is intended to be called repeatedly with the results of
  772. each commit. It therefore shows a 'diff' between what it saw in
  773. the last call and what it sees now.
  774. Args:
  775. board_selected: Dict containing boards to summarise, keyed by
  776. board.target
  777. board_dict: Dict containing boards for which we built this
  778. commit, keyed by board.target. The value is an Outcome object.
  779. err_lines: A list of errors for this commit, or [] if there is
  780. none, or we don't want to print errors
  781. err_line_boards: Dict keyed by error line, containing a list of
  782. the Board objects with that error
  783. warn_lines: A list of warnings for this commit, or [] if there is
  784. none, or we don't want to print errors
  785. warn_line_boards: Dict keyed by warning line, containing a list of
  786. the Board objects with that warning
  787. show_sizes: Show image size deltas
  788. show_detail: Show detail for each board
  789. show_bloat: Show detail for each function
  790. """
  791. def _BoardList(line, line_boards):
  792. """Helper function to get a line of boards containing a line
  793. Args:
  794. line: Error line to search for
  795. Return:
  796. String containing a list of boards with that error line, or
  797. '' if the user has not requested such a list
  798. """
  799. if self._list_error_boards:
  800. names = []
  801. for board in line_boards[line]:
  802. if not board.target in names:
  803. names.append(board.target)
  804. names_str = '(%s) ' % ','.join(names)
  805. else:
  806. names_str = ''
  807. return names_str
  808. def _CalcErrorDelta(base_lines, base_line_boards, lines, line_boards,
  809. char):
  810. better_lines = []
  811. worse_lines = []
  812. for line in lines:
  813. if line not in base_lines:
  814. worse_lines.append(char + '+' +
  815. _BoardList(line, line_boards) + line)
  816. for line in base_lines:
  817. if line not in lines:
  818. better_lines.append(char + '-' +
  819. _BoardList(line, base_line_boards) + line)
  820. return better_lines, worse_lines
  821. better = [] # List of boards fixed since last commit
  822. worse = [] # List of new broken boards since last commit
  823. new = [] # List of boards that didn't exist last time
  824. unknown = [] # List of boards that were not built
  825. for target in board_dict:
  826. if target not in board_selected:
  827. continue
  828. # If the board was built last time, add its outcome to a list
  829. if target in self._base_board_dict:
  830. base_outcome = self._base_board_dict[target].rc
  831. outcome = board_dict[target]
  832. if outcome.rc == OUTCOME_UNKNOWN:
  833. unknown.append(target)
  834. elif outcome.rc < base_outcome:
  835. better.append(target)
  836. elif outcome.rc > base_outcome:
  837. worse.append(target)
  838. else:
  839. new.append(target)
  840. # Get a list of errors that have appeared, and disappeared
  841. better_err, worse_err = _CalcErrorDelta(self._base_err_lines,
  842. self._base_err_line_boards, err_lines, err_line_boards, '')
  843. better_warn, worse_warn = _CalcErrorDelta(self._base_warn_lines,
  844. self._base_warn_line_boards, warn_lines, warn_line_boards, 'w')
  845. # Display results by arch
  846. if (better or worse or unknown or new or worse_err or better_err
  847. or worse_warn or better_warn):
  848. arch_list = {}
  849. self.AddOutcome(board_selected, arch_list, better, '',
  850. self.col.GREEN)
  851. self.AddOutcome(board_selected, arch_list, worse, '+',
  852. self.col.RED)
  853. self.AddOutcome(board_selected, arch_list, new, '*', self.col.BLUE)
  854. if self._show_unknown:
  855. self.AddOutcome(board_selected, arch_list, unknown, '?',
  856. self.col.MAGENTA)
  857. for arch, target_list in arch_list.iteritems():
  858. Print('%10s: %s' % (arch, target_list))
  859. self._error_lines += 1
  860. if better_err:
  861. Print('\n'.join(better_err), colour=self.col.GREEN)
  862. self._error_lines += 1
  863. if worse_err:
  864. Print('\n'.join(worse_err), colour=self.col.RED)
  865. self._error_lines += 1
  866. if better_warn:
  867. Print('\n'.join(better_warn), colour=self.col.CYAN)
  868. self._error_lines += 1
  869. if worse_warn:
  870. Print('\n'.join(worse_warn), colour=self.col.MAGENTA)
  871. self._error_lines += 1
  872. if show_sizes:
  873. self.PrintSizeSummary(board_selected, board_dict, show_detail,
  874. show_bloat)
  875. # Save our updated information for the next call to this function
  876. self._base_board_dict = board_dict
  877. self._base_err_lines = err_lines
  878. self._base_warn_lines = warn_lines
  879. self._base_err_line_boards = err_line_boards
  880. self._base_warn_line_boards = warn_line_boards
  881. # Get a list of boards that did not get built, if needed
  882. not_built = []
  883. for board in board_selected:
  884. if not board in board_dict:
  885. not_built.append(board)
  886. if not_built:
  887. Print("Boards not built (%d): %s" % (len(not_built),
  888. ', '.join(not_built)))
  889. def ProduceResultSummary(self, commit_upto, commits, board_selected):
  890. (board_dict, err_lines, err_line_boards, warn_lines,
  891. warn_line_boards) = self.GetResultSummary(
  892. board_selected, commit_upto,
  893. read_func_sizes=self._show_bloat)
  894. if commits:
  895. msg = '%02d: %s' % (commit_upto + 1,
  896. commits[commit_upto].subject)
  897. Print(msg, colour=self.col.BLUE)
  898. self.PrintResultSummary(board_selected, board_dict,
  899. err_lines if self._show_errors else [], err_line_boards,
  900. warn_lines if self._show_errors else [], warn_line_boards,
  901. self._show_sizes, self._show_detail, self._show_bloat)
  902. def ShowSummary(self, commits, board_selected):
  903. """Show a build summary for U-Boot for a given board list.
  904. Reset the result summary, then repeatedly call GetResultSummary on
  905. each commit's results, then display the differences we see.
  906. Args:
  907. commit: Commit objects to summarise
  908. board_selected: Dict containing boards to summarise
  909. """
  910. self.commit_count = len(commits) if commits else 1
  911. self.commits = commits
  912. self.ResetResultSummary(board_selected)
  913. self._error_lines = 0
  914. for commit_upto in range(0, self.commit_count, self._step):
  915. self.ProduceResultSummary(commit_upto, commits, board_selected)
  916. if not self._error_lines:
  917. Print('(no errors to report)', colour=self.col.GREEN)
  918. def SetupBuild(self, board_selected, commits):
  919. """Set up ready to start a build.
  920. Args:
  921. board_selected: Selected boards to build
  922. commits: Selected commits to build
  923. """
  924. # First work out how many commits we will build
  925. count = (self.commit_count + self._step - 1) / self._step
  926. self.count = len(board_selected) * count
  927. self.upto = self.warned = self.fail = 0
  928. self._timestamps = collections.deque()
  929. def GetThreadDir(self, thread_num):
  930. """Get the directory path to the working dir for a thread.
  931. Args:
  932. thread_num: Number of thread to check.
  933. """
  934. return os.path.join(self._working_dir, '%02d' % thread_num)
  935. def _PrepareThread(self, thread_num, setup_git):
  936. """Prepare the working directory for a thread.
  937. This clones or fetches the repo into the thread's work directory.
  938. Args:
  939. thread_num: Thread number (0, 1, ...)
  940. setup_git: True to set up a git repo clone
  941. """
  942. thread_dir = self.GetThreadDir(thread_num)
  943. builderthread.Mkdir(thread_dir)
  944. git_dir = os.path.join(thread_dir, '.git')
  945. # Clone the repo if it doesn't already exist
  946. # TODO(sjg@chromium): Perhaps some git hackery to symlink instead, so
  947. # we have a private index but uses the origin repo's contents?
  948. if setup_git and self.git_dir:
  949. src_dir = os.path.abspath(self.git_dir)
  950. if os.path.exists(git_dir):
  951. gitutil.Fetch(git_dir, thread_dir)
  952. else:
  953. Print('Cloning repo for thread %d' % thread_num)
  954. gitutil.Clone(src_dir, thread_dir)
  955. def _PrepareWorkingSpace(self, max_threads, setup_git):
  956. """Prepare the working directory for use.
  957. Set up the git repo for each thread.
  958. Args:
  959. max_threads: Maximum number of threads we expect to need.
  960. setup_git: True to set up a git repo clone
  961. """
  962. builderthread.Mkdir(self._working_dir)
  963. for thread in range(max_threads):
  964. self._PrepareThread(thread, setup_git)
  965. def _PrepareOutputSpace(self):
  966. """Get the output directories ready to receive files.
  967. We delete any output directories which look like ones we need to
  968. create. Having left over directories is confusing when the user wants
  969. to check the output manually.
  970. """
  971. dir_list = []
  972. for commit_upto in range(self.commit_count):
  973. dir_list.append(self._GetOutputDir(commit_upto))
  974. for dirname in glob.glob(os.path.join(self.base_dir, '*')):
  975. if dirname not in dir_list:
  976. shutil.rmtree(dirname)
  977. def BuildBoards(self, commits, board_selected, keep_outputs, verbose):
  978. """Build all commits for a list of boards
  979. Args:
  980. commits: List of commits to be build, each a Commit object
  981. boards_selected: Dict of selected boards, key is target name,
  982. value is Board object
  983. keep_outputs: True to save build output files
  984. verbose: Display build results as they are completed
  985. Returns:
  986. Tuple containing:
  987. - number of boards that failed to build
  988. - number of boards that issued warnings
  989. """
  990. self.commit_count = len(commits) if commits else 1
  991. self.commits = commits
  992. self._verbose = verbose
  993. self.ResetResultSummary(board_selected)
  994. builderthread.Mkdir(self.base_dir, parents = True)
  995. self._PrepareWorkingSpace(min(self.num_threads, len(board_selected)),
  996. commits is not None)
  997. self._PrepareOutputSpace()
  998. self.SetupBuild(board_selected, commits)
  999. self.ProcessResult(None)
  1000. # Create jobs to build all commits for each board
  1001. for brd in board_selected.itervalues():
  1002. job = builderthread.BuilderJob()
  1003. job.board = brd
  1004. job.commits = commits
  1005. job.keep_outputs = keep_outputs
  1006. job.step = self._step
  1007. self.queue.put(job)
  1008. # Wait until all jobs are started
  1009. self.queue.join()
  1010. # Wait until we have processed all output
  1011. self.out_queue.join()
  1012. Print()
  1013. self.ClearLine(0)
  1014. return (self.fail, self.warned)