builder.py 42 KB

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