builder.py 46 KB

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