builder.py 46 KB

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