builder.py 41 KB

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