builder.py 41 KB

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