builder.py 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446
  1. # Copyright (c) 2013 The Chromium OS Authors.
  2. #
  3. # Bloat-o-meter code used here Copyright 2004 Matt Mackall <mpm@selenic.com>
  4. #
  5. # SPDX-License-Identifier: GPL-2.0+
  6. #
  7. import collections
  8. from datetime import datetime, timedelta
  9. import glob
  10. import os
  11. import re
  12. import Queue
  13. import shutil
  14. import string
  15. import sys
  16. import time
  17. import builderthread
  18. import command
  19. import gitutil
  20. import terminal
  21. from terminal import Print
  22. import toolchain
  23. """
  24. Theory of Operation
  25. Please see README for user documentation, and you should be familiar with
  26. that before trying to make sense of this.
  27. Buildman works by keeping the machine as busy as possible, building different
  28. commits for different boards on multiple CPUs at once.
  29. The source repo (self.git_dir) contains all the commits to be built. Each
  30. thread works on a single board at a time. It checks out the first commit,
  31. configures it for that board, then builds it. Then it checks out the next
  32. commit and builds it (typically without re-configuring). When it runs out
  33. of commits, it gets another job from the builder and starts again with that
  34. board.
  35. Clearly the builder threads could work either way - they could check out a
  36. commit and then built it for all boards. Using separate directories for each
  37. commit/board pair they could leave their build product around afterwards
  38. also.
  39. The intent behind building a single board for multiple commits, is to make
  40. use of incremental builds. Since each commit is built incrementally from
  41. the previous one, builds are faster. Reconfiguring for a different board
  42. removes all intermediate object files.
  43. Many threads can be working at once, but each has its own working directory.
  44. When a thread finishes a build, it puts the output files into a result
  45. directory.
  46. The base directory used by buildman is normally '../<branch>', i.e.
  47. a directory higher than the source repository and named after the branch
  48. being built.
  49. Within the base directory, we have one subdirectory for each commit. Within
  50. that is one subdirectory for each board. Within that is the build output for
  51. that commit/board combination.
  52. Buildman also create working directories for each thread, in a .bm-work/
  53. subdirectory in the base dir.
  54. As an example, say we are building branch 'us-net' for boards 'sandbox' and
  55. 'seaboard', and say that us-net has two commits. We will have directories
  56. like this:
  57. us-net/ base directory
  58. 01_of_02_g4ed4ebc_net--Add-tftp-speed-/
  59. sandbox/
  60. u-boot.bin
  61. seaboard/
  62. u-boot.bin
  63. 02_of_02_g4ed4ebc_net--Check-tftp-comp/
  64. sandbox/
  65. u-boot.bin
  66. seaboard/
  67. u-boot.bin
  68. .bm-work/
  69. 00/ working directory for thread 0 (contains source checkout)
  70. build/ build output
  71. 01/ working directory for thread 1
  72. build/ build output
  73. ...
  74. u-boot/ source directory
  75. .git/ repository
  76. """
  77. # Possible build outcomes
  78. OUTCOME_OK, OUTCOME_WARNING, OUTCOME_ERROR, OUTCOME_UNKNOWN = range(4)
  79. # Translate a commit subject into a valid filename
  80. trans_valid_chars = string.maketrans("/: ", "---")
  81. CONFIG_FILENAMES = [
  82. '.config', '.config-spl', '.config-tpl',
  83. 'autoconf.mk', 'autoconf-spl.mk', 'autoconf-tpl.mk',
  84. 'autoconf.h', 'autoconf-spl.h','autoconf-tpl.h',
  85. 'u-boot.cfg', 'u-boot-spl.cfg', 'u-boot-tpl.cfg'
  86. ]
  87. class Config:
  88. """Holds information about configuration settings for a board."""
  89. def __init__(self, target):
  90. self.target = target
  91. self.config = {}
  92. for fname in CONFIG_FILENAMES:
  93. self.config[fname] = {}
  94. def Add(self, fname, key, value):
  95. self.config[fname][key] = value
  96. def __hash__(self):
  97. val = 0
  98. for fname in self.config:
  99. for key, value in self.config[fname].iteritems():
  100. print key, value
  101. val = val ^ hash(key) & hash(value)
  102. return val
  103. class Builder:
  104. """Class for building U-Boot for a particular commit.
  105. Public members: (many should ->private)
  106. active: True if the builder is active and has not been stopped
  107. already_done: Number of builds already completed
  108. base_dir: Base directory to use for builder
  109. checkout: True to check out source, False to skip that step.
  110. This is used for testing.
  111. col: terminal.Color() object
  112. count: Number of commits to build
  113. do_make: Method to call to invoke Make
  114. fail: Number of builds that failed due to error
  115. force_build: Force building even if a build already exists
  116. force_config_on_failure: If a commit fails for a board, disable
  117. incremental building for the next commit we build for that
  118. board, so that we will see all warnings/errors again.
  119. force_build_failures: If a previously-built build (i.e. built on
  120. a previous run of buildman) is marked as failed, rebuild it.
  121. git_dir: Git directory containing source repository
  122. last_line_len: Length of the last line we printed (used for erasing
  123. it with new progress information)
  124. num_jobs: Number of jobs to run at once (passed to make as -j)
  125. num_threads: Number of builder threads to run
  126. out_queue: Queue of results to process
  127. re_make_err: Compiled regular expression for ignore_lines
  128. queue: Queue of jobs to run
  129. threads: List of active threads
  130. toolchains: Toolchains object to use for building
  131. upto: Current commit number we are building (0.count-1)
  132. warned: Number of builds that produced at least one warning
  133. force_reconfig: Reconfigure U-Boot on each comiit. This disables
  134. incremental building, where buildman reconfigures on the first
  135. commit for a baord, and then just does an incremental build for
  136. the following commits. In fact buildman will reconfigure and
  137. retry for any failing commits, so generally the only effect of
  138. this option is to slow things down.
  139. in_tree: Build U-Boot in-tree instead of specifying an output
  140. directory separate from the source code. This option is really
  141. only useful for testing in-tree builds.
  142. Private members:
  143. _base_board_dict: Last-summarised Dict of boards
  144. _base_err_lines: Last-summarised list of errors
  145. _base_warn_lines: Last-summarised list of warnings
  146. _build_period_us: Time taken for a single build (float object).
  147. _complete_delay: Expected delay until completion (timedelta)
  148. _next_delay_update: Next time we plan to display a progress update
  149. (datatime)
  150. _show_unknown: Show unknown boards (those not built) in summary
  151. _timestamps: List of timestamps for the completion of the last
  152. last _timestamp_count builds. Each is a datetime object.
  153. _timestamp_count: Number of timestamps to keep in our list.
  154. _working_dir: Base working directory containing all threads
  155. """
  156. class Outcome:
  157. """Records a build outcome for a single make invocation
  158. Public Members:
  159. rc: Outcome value (OUTCOME_...)
  160. err_lines: List of error lines or [] if none
  161. sizes: Dictionary of image size information, keyed by filename
  162. - Each value is itself a dictionary containing
  163. values for 'text', 'data' and 'bss', being the integer
  164. size in bytes of each section.
  165. func_sizes: Dictionary keyed by filename - e.g. 'u-boot'. Each
  166. value is itself a dictionary:
  167. key: function name
  168. value: Size of function in bytes
  169. config: Dictionary keyed by filename - e.g. '.config'. Each
  170. value is itself a dictionary:
  171. key: config name
  172. value: config value
  173. """
  174. def __init__(self, rc, err_lines, sizes, func_sizes, config):
  175. self.rc = rc
  176. self.err_lines = err_lines
  177. self.sizes = sizes
  178. self.func_sizes = func_sizes
  179. self.config = config
  180. def __init__(self, toolchains, base_dir, git_dir, num_threads, num_jobs,
  181. gnu_make='make', checkout=True, show_unknown=True, step=1,
  182. no_subdirs=False, full_path=False, verbose_build=False,
  183. incremental=False, per_board_out_dir=False):
  184. """Create a new Builder object
  185. Args:
  186. toolchains: Toolchains object to use for building
  187. base_dir: Base directory to use for builder
  188. git_dir: Git directory containing source repository
  189. num_threads: Number of builder threads to run
  190. num_jobs: Number of jobs to run at once (passed to make as -j)
  191. gnu_make: the command name of GNU Make.
  192. checkout: True to check out source, False to skip that step.
  193. This is used for testing.
  194. show_unknown: Show unknown boards (those not built) in summary
  195. step: 1 to process every commit, n to process every nth commit
  196. no_subdirs: Don't create subdirectories when building current
  197. source for a single board
  198. full_path: Return the full path in CROSS_COMPILE and don't set
  199. PATH
  200. verbose_build: Run build with V=1 and don't use 'make -s'
  201. incremental: Always perform incremental builds; don't run make
  202. mrproper when configuring
  203. per_board_out_dir: Build in a separate persistent directory per
  204. board rather than a thread-specific directory
  205. """
  206. self.toolchains = toolchains
  207. self.base_dir = base_dir
  208. self._working_dir = os.path.join(base_dir, '.bm-work')
  209. self.threads = []
  210. self.active = True
  211. self.do_make = self.Make
  212. self.gnu_make = gnu_make
  213. self.checkout = checkout
  214. self.num_threads = num_threads
  215. self.num_jobs = num_jobs
  216. self.already_done = 0
  217. self.force_build = False
  218. self.git_dir = git_dir
  219. self._show_unknown = show_unknown
  220. self._timestamp_count = 10
  221. self._build_period_us = None
  222. self._complete_delay = None
  223. self._next_delay_update = datetime.now()
  224. self.force_config_on_failure = True
  225. self.force_build_failures = False
  226. self.force_reconfig = False
  227. self._step = step
  228. self.in_tree = False
  229. self._error_lines = 0
  230. self.no_subdirs = no_subdirs
  231. self.full_path = full_path
  232. self.verbose_build = verbose_build
  233. self.col = terminal.Color()
  234. self._re_function = re.compile('(.*): In function.*')
  235. self._re_files = re.compile('In file included from.*')
  236. self._re_warning = re.compile('(.*):(\d*):(\d*): warning: .*')
  237. self._re_note = re.compile('(.*):(\d*):(\d*): note: this is the location of the previous.*')
  238. self.queue = Queue.Queue()
  239. self.out_queue = Queue.Queue()
  240. for i in range(self.num_threads):
  241. t = builderthread.BuilderThread(self, i, incremental,
  242. per_board_out_dir)
  243. t.setDaemon(True)
  244. t.start()
  245. self.threads.append(t)
  246. self.last_line_len = 0
  247. t = builderthread.ResultThread(self)
  248. t.setDaemon(True)
  249. t.start()
  250. self.threads.append(t)
  251. ignore_lines = ['(make.*Waiting for unfinished)', '(Segmentation fault)']
  252. self.re_make_err = re.compile('|'.join(ignore_lines))
  253. def __del__(self):
  254. """Get rid of all threads created by the builder"""
  255. for t in self.threads:
  256. del t
  257. def SetDisplayOptions(self, show_errors=False, show_sizes=False,
  258. show_detail=False, show_bloat=False,
  259. list_error_boards=False, show_config=False):
  260. """Setup display options for the builder.
  261. show_errors: True to show summarised error/warning info
  262. show_sizes: Show size deltas
  263. show_detail: Show detail for each board
  264. show_bloat: Show detail for each function
  265. list_error_boards: Show the boards which caused each error/warning
  266. show_config: Show config deltas
  267. """
  268. self._show_errors = show_errors
  269. self._show_sizes = show_sizes
  270. self._show_detail = show_detail
  271. self._show_bloat = show_bloat
  272. self._list_error_boards = list_error_boards
  273. self._show_config = show_config
  274. def _AddTimestamp(self):
  275. """Add a new timestamp to the list and record the build period.
  276. The build period is the length of time taken to perform a single
  277. build (one board, one commit).
  278. """
  279. now = datetime.now()
  280. self._timestamps.append(now)
  281. count = len(self._timestamps)
  282. delta = self._timestamps[-1] - self._timestamps[0]
  283. seconds = delta.total_seconds()
  284. # If we have enough data, estimate build period (time taken for a
  285. # single build) and therefore completion time.
  286. if count > 1 and self._next_delay_update < now:
  287. self._next_delay_update = now + timedelta(seconds=2)
  288. if seconds > 0:
  289. self._build_period = float(seconds) / count
  290. todo = self.count - self.upto
  291. self._complete_delay = timedelta(microseconds=
  292. self._build_period * todo * 1000000)
  293. # Round it
  294. self._complete_delay -= timedelta(
  295. microseconds=self._complete_delay.microseconds)
  296. if seconds > 60:
  297. self._timestamps.popleft()
  298. count -= 1
  299. def ClearLine(self, length):
  300. """Clear any characters on the current line
  301. Make way for a new line of length 'length', by outputting enough
  302. spaces to clear out the old line. Then remember the new length for
  303. next time.
  304. Args:
  305. length: Length of new line, in characters
  306. """
  307. if length < self.last_line_len:
  308. Print(' ' * (self.last_line_len - length), newline=False)
  309. Print('\r', newline=False)
  310. self.last_line_len = length
  311. sys.stdout.flush()
  312. def SelectCommit(self, commit, checkout=True):
  313. """Checkout the selected commit for this build
  314. """
  315. self.commit = commit
  316. if checkout and self.checkout:
  317. gitutil.Checkout(commit.hash)
  318. def Make(self, commit, brd, stage, cwd, *args, **kwargs):
  319. """Run make
  320. Args:
  321. commit: Commit object that is being built
  322. brd: Board object that is being built
  323. stage: Stage that we are at (mrproper, config, build)
  324. cwd: Directory where make should be run
  325. args: Arguments to pass to make
  326. kwargs: Arguments to pass to command.RunPipe()
  327. """
  328. cmd = [self.gnu_make] + list(args)
  329. result = command.RunPipe([cmd], capture=True, capture_stderr=True,
  330. cwd=cwd, raise_on_error=False, **kwargs)
  331. if self.verbose_build:
  332. result.stdout = '%s\n' % (' '.join(cmd)) + result.stdout
  333. result.combined = '%s\n' % (' '.join(cmd)) + result.combined
  334. return result
  335. def ProcessResult(self, result):
  336. """Process the result of a build, showing progress information
  337. Args:
  338. result: A CommandResult object, which indicates the result for
  339. a single build
  340. """
  341. col = terminal.Color()
  342. if result:
  343. target = result.brd.target
  344. if result.return_code < 0:
  345. self.active = False
  346. command.StopAll()
  347. return
  348. self.upto += 1
  349. if result.return_code != 0:
  350. self.fail += 1
  351. elif result.stderr:
  352. self.warned += 1
  353. if result.already_done:
  354. self.already_done += 1
  355. if self._verbose:
  356. Print('\r', newline=False)
  357. self.ClearLine(0)
  358. boards_selected = {target : result.brd}
  359. self.ResetResultSummary(boards_selected)
  360. self.ProduceResultSummary(result.commit_upto, self.commits,
  361. boards_selected)
  362. else:
  363. target = '(starting)'
  364. # Display separate counts for ok, warned and fail
  365. ok = self.upto - self.warned - self.fail
  366. line = '\r' + self.col.Color(self.col.GREEN, '%5d' % ok)
  367. line += self.col.Color(self.col.YELLOW, '%5d' % self.warned)
  368. line += self.col.Color(self.col.RED, '%5d' % self.fail)
  369. name = ' /%-5d ' % self.count
  370. # Add our current completion time estimate
  371. self._AddTimestamp()
  372. if self._complete_delay:
  373. name += '%s : ' % self._complete_delay
  374. # When building all boards for a commit, we can print a commit
  375. # progress message.
  376. if result and result.commit_upto is None:
  377. name += 'commit %2d/%-3d' % (self.commit_upto + 1,
  378. self.commit_count)
  379. name += target
  380. Print(line + name, newline=False)
  381. length = 14 + len(name)
  382. self.ClearLine(length)
  383. def _GetOutputDir(self, commit_upto):
  384. """Get the name of the output directory for a commit number
  385. The output directory is typically .../<branch>/<commit>.
  386. Args:
  387. commit_upto: Commit number to use (0..self.count-1)
  388. """
  389. commit_dir = None
  390. if self.commits:
  391. commit = self.commits[commit_upto]
  392. subject = commit.subject.translate(trans_valid_chars)
  393. commit_dir = ('%02d_of_%02d_g%s_%s' % (commit_upto + 1,
  394. self.commit_count, commit.hash, subject[:20]))
  395. elif not self.no_subdirs:
  396. commit_dir = 'current'
  397. if not commit_dir:
  398. return self.base_dir
  399. return os.path.join(self.base_dir, commit_dir)
  400. def GetBuildDir(self, commit_upto, target):
  401. """Get the name of the build directory for a commit number
  402. The build directory is typically .../<branch>/<commit>/<target>.
  403. Args:
  404. commit_upto: Commit number to use (0..self.count-1)
  405. target: Target name
  406. """
  407. output_dir = self._GetOutputDir(commit_upto)
  408. return os.path.join(output_dir, target)
  409. def GetDoneFile(self, commit_upto, target):
  410. """Get the name of the done file for a commit number
  411. Args:
  412. commit_upto: Commit number to use (0..self.count-1)
  413. target: Target name
  414. """
  415. return os.path.join(self.GetBuildDir(commit_upto, target), 'done')
  416. def GetSizesFile(self, commit_upto, target):
  417. """Get the name of the sizes file for a commit number
  418. Args:
  419. commit_upto: Commit number to use (0..self.count-1)
  420. target: Target name
  421. """
  422. return os.path.join(self.GetBuildDir(commit_upto, target), 'sizes')
  423. def GetFuncSizesFile(self, commit_upto, target, elf_fname):
  424. """Get the name of the funcsizes file for a commit number and ELF file
  425. Args:
  426. commit_upto: Commit number to use (0..self.count-1)
  427. target: Target name
  428. elf_fname: Filename of elf image
  429. """
  430. return os.path.join(self.GetBuildDir(commit_upto, target),
  431. '%s.sizes' % elf_fname.replace('/', '-'))
  432. def GetObjdumpFile(self, commit_upto, target, elf_fname):
  433. """Get the name of the objdump file for a commit number and ELF file
  434. Args:
  435. commit_upto: Commit number to use (0..self.count-1)
  436. target: Target name
  437. elf_fname: Filename of elf image
  438. """
  439. return os.path.join(self.GetBuildDir(commit_upto, target),
  440. '%s.objdump' % elf_fname.replace('/', '-'))
  441. def GetErrFile(self, commit_upto, target):
  442. """Get the name of the err file for a commit number
  443. Args:
  444. commit_upto: Commit number to use (0..self.count-1)
  445. target: Target name
  446. """
  447. output_dir = self.GetBuildDir(commit_upto, target)
  448. return os.path.join(output_dir, 'err')
  449. def FilterErrors(self, lines):
  450. """Filter out errors in which we have no interest
  451. We should probably use map().
  452. Args:
  453. lines: List of error lines, each a string
  454. Returns:
  455. New list with only interesting lines included
  456. """
  457. out_lines = []
  458. for line in lines:
  459. if not self.re_make_err.search(line):
  460. out_lines.append(line)
  461. return out_lines
  462. def ReadFuncSizes(self, fname, fd):
  463. """Read function sizes from the output of 'nm'
  464. Args:
  465. fd: File containing data to read
  466. fname: Filename we are reading from (just for errors)
  467. Returns:
  468. Dictionary containing size of each function in bytes, indexed by
  469. function name.
  470. """
  471. sym = {}
  472. for line in fd.readlines():
  473. try:
  474. size, type, name = line[:-1].split()
  475. except:
  476. Print("Invalid line in file '%s': '%s'" % (fname, line[:-1]))
  477. continue
  478. if type in 'tTdDbB':
  479. # function names begin with '.' on 64-bit powerpc
  480. if '.' in name[1:]:
  481. name = 'static.' + name.split('.')[0]
  482. sym[name] = sym.get(name, 0) + int(size, 16)
  483. return sym
  484. def _ProcessConfig(self, fname):
  485. """Read in a .config, autoconf.mk or autoconf.h file
  486. This function handles all config file types. It ignores comments and
  487. any #defines which don't start with CONFIG_.
  488. Args:
  489. fname: Filename to read
  490. Returns:
  491. Dictionary:
  492. key: Config name (e.g. CONFIG_DM)
  493. value: Config value (e.g. 1)
  494. """
  495. config = {}
  496. if os.path.exists(fname):
  497. with open(fname) as fd:
  498. for line in fd:
  499. line = line.strip()
  500. if line.startswith('#define'):
  501. values = line[8:].split(' ', 1)
  502. if len(values) > 1:
  503. key, value = values
  504. else:
  505. key = values[0]
  506. value = ''
  507. if not key.startswith('CONFIG_'):
  508. continue
  509. elif not line or line[0] in ['#', '*', '/']:
  510. continue
  511. else:
  512. key, value = line.split('=', 1)
  513. config[key] = value
  514. return config
  515. def GetBuildOutcome(self, commit_upto, target, read_func_sizes,
  516. read_config):
  517. """Work out the outcome of a build.
  518. Args:
  519. commit_upto: Commit number to check (0..n-1)
  520. target: Target board to check
  521. read_func_sizes: True to read function size information
  522. read_config: True to read .config and autoconf.h files
  523. Returns:
  524. Outcome object
  525. """
  526. done_file = self.GetDoneFile(commit_upto, target)
  527. sizes_file = self.GetSizesFile(commit_upto, target)
  528. sizes = {}
  529. func_sizes = {}
  530. config = {}
  531. if os.path.exists(done_file):
  532. with open(done_file, 'r') as fd:
  533. return_code = int(fd.readline())
  534. err_lines = []
  535. err_file = self.GetErrFile(commit_upto, target)
  536. if os.path.exists(err_file):
  537. with open(err_file, 'r') as fd:
  538. err_lines = self.FilterErrors(fd.readlines())
  539. # Decide whether the build was ok, failed or created warnings
  540. if return_code:
  541. rc = OUTCOME_ERROR
  542. elif len(err_lines):
  543. rc = OUTCOME_WARNING
  544. else:
  545. rc = OUTCOME_OK
  546. # Convert size information to our simple format
  547. if os.path.exists(sizes_file):
  548. with open(sizes_file, 'r') as fd:
  549. for line in fd.readlines():
  550. values = line.split()
  551. rodata = 0
  552. if len(values) > 6:
  553. rodata = int(values[6], 16)
  554. size_dict = {
  555. 'all' : int(values[0]) + int(values[1]) +
  556. int(values[2]),
  557. 'text' : int(values[0]) - rodata,
  558. 'data' : int(values[1]),
  559. 'bss' : int(values[2]),
  560. 'rodata' : rodata,
  561. }
  562. sizes[values[5]] = size_dict
  563. if read_func_sizes:
  564. pattern = self.GetFuncSizesFile(commit_upto, target, '*')
  565. for fname in glob.glob(pattern):
  566. with open(fname, 'r') as fd:
  567. dict_name = os.path.basename(fname).replace('.sizes',
  568. '')
  569. func_sizes[dict_name] = self.ReadFuncSizes(fname, fd)
  570. if read_config:
  571. output_dir = self.GetBuildDir(commit_upto, target)
  572. for name in CONFIG_FILENAMES:
  573. fname = os.path.join(output_dir, name)
  574. config[name] = self._ProcessConfig(fname)
  575. return Builder.Outcome(rc, err_lines, sizes, func_sizes, config)
  576. return Builder.Outcome(OUTCOME_UNKNOWN, [], {}, {}, {})
  577. def GetResultSummary(self, boards_selected, commit_upto, read_func_sizes,
  578. read_config):
  579. """Calculate a summary of the results of building a commit.
  580. Args:
  581. board_selected: Dict containing boards to summarise
  582. commit_upto: Commit number to summarize (0..self.count-1)
  583. read_func_sizes: True to read function size information
  584. read_config: True to read .config and autoconf.h files
  585. Returns:
  586. Tuple:
  587. Dict containing boards which passed building this commit.
  588. keyed by board.target
  589. List containing a summary of error lines
  590. Dict keyed by error line, containing a list of the Board
  591. objects with that error
  592. List containing a summary of warning lines
  593. Dict keyed by error line, containing a list of the Board
  594. objects with that warning
  595. Dictionary keyed by board.target. Each value is a dictionary:
  596. key: filename - e.g. '.config'
  597. value is itself a dictionary:
  598. key: config name
  599. value: config value
  600. """
  601. def AddLine(lines_summary, lines_boards, line, board):
  602. line = line.rstrip()
  603. if line in lines_boards:
  604. lines_boards[line].append(board)
  605. else:
  606. lines_boards[line] = [board]
  607. lines_summary.append(line)
  608. board_dict = {}
  609. err_lines_summary = []
  610. err_lines_boards = {}
  611. warn_lines_summary = []
  612. warn_lines_boards = {}
  613. config = {}
  614. for board in boards_selected.itervalues():
  615. outcome = self.GetBuildOutcome(commit_upto, board.target,
  616. read_func_sizes, read_config)
  617. board_dict[board.target] = outcome
  618. last_func = None
  619. last_was_warning = False
  620. for line in outcome.err_lines:
  621. if line:
  622. if (self._re_function.match(line) or
  623. self._re_files.match(line)):
  624. last_func = line
  625. else:
  626. is_warning = self._re_warning.match(line)
  627. is_note = self._re_note.match(line)
  628. if is_warning or (last_was_warning and is_note):
  629. if last_func:
  630. AddLine(warn_lines_summary, warn_lines_boards,
  631. last_func, board)
  632. AddLine(warn_lines_summary, warn_lines_boards,
  633. line, board)
  634. else:
  635. if last_func:
  636. AddLine(err_lines_summary, err_lines_boards,
  637. last_func, board)
  638. AddLine(err_lines_summary, err_lines_boards,
  639. line, board)
  640. last_was_warning = is_warning
  641. last_func = None
  642. tconfig = Config(board.target)
  643. for fname in CONFIG_FILENAMES:
  644. if outcome.config:
  645. for key, value in outcome.config[fname].iteritems():
  646. tconfig.Add(fname, key, value)
  647. config[board.target] = tconfig
  648. return (board_dict, err_lines_summary, err_lines_boards,
  649. warn_lines_summary, warn_lines_boards, config)
  650. def AddOutcome(self, board_dict, arch_list, changes, char, color):
  651. """Add an output to our list of outcomes for each architecture
  652. This simple function adds failing boards (changes) to the
  653. relevant architecture string, so we can print the results out
  654. sorted by architecture.
  655. Args:
  656. board_dict: Dict containing all boards
  657. arch_list: Dict keyed by arch name. Value is a string containing
  658. a list of board names which failed for that arch.
  659. changes: List of boards to add to arch_list
  660. color: terminal.Colour object
  661. """
  662. done_arch = {}
  663. for target in changes:
  664. if target in board_dict:
  665. arch = board_dict[target].arch
  666. else:
  667. arch = 'unknown'
  668. str = self.col.Color(color, ' ' + target)
  669. if not arch in done_arch:
  670. str = ' %s %s' % (self.col.Color(color, char), str)
  671. done_arch[arch] = True
  672. if not arch in arch_list:
  673. arch_list[arch] = str
  674. else:
  675. arch_list[arch] += str
  676. def ColourNum(self, num):
  677. color = self.col.RED if num > 0 else self.col.GREEN
  678. if num == 0:
  679. return '0'
  680. return self.col.Color(color, str(num))
  681. def ResetResultSummary(self, board_selected):
  682. """Reset the results summary ready for use.
  683. Set up the base board list to be all those selected, and set the
  684. error lines to empty.
  685. Following this, calls to PrintResultSummary() will use this
  686. information to work out what has changed.
  687. Args:
  688. board_selected: Dict containing boards to summarise, keyed by
  689. board.target
  690. """
  691. self._base_board_dict = {}
  692. for board in board_selected:
  693. self._base_board_dict[board] = Builder.Outcome(0, [], [], {}, {})
  694. self._base_err_lines = []
  695. self._base_warn_lines = []
  696. self._base_err_line_boards = {}
  697. self._base_warn_line_boards = {}
  698. self._base_config = None
  699. def PrintFuncSizeDetail(self, fname, old, new):
  700. grow, shrink, add, remove, up, down = 0, 0, 0, 0, 0, 0
  701. delta, common = [], {}
  702. for a in old:
  703. if a in new:
  704. common[a] = 1
  705. for name in old:
  706. if name not in common:
  707. remove += 1
  708. down += old[name]
  709. delta.append([-old[name], name])
  710. for name in new:
  711. if name not in common:
  712. add += 1
  713. up += new[name]
  714. delta.append([new[name], name])
  715. for name in common:
  716. diff = new.get(name, 0) - old.get(name, 0)
  717. if diff > 0:
  718. grow, up = grow + 1, up + diff
  719. elif diff < 0:
  720. shrink, down = shrink + 1, down - diff
  721. delta.append([diff, name])
  722. delta.sort()
  723. delta.reverse()
  724. args = [add, -remove, grow, -shrink, up, -down, up - down]
  725. if max(args) == 0:
  726. return
  727. args = [self.ColourNum(x) for x in args]
  728. indent = ' ' * 15
  729. Print('%s%s: add: %s/%s, grow: %s/%s bytes: %s/%s (%s)' %
  730. tuple([indent, self.col.Color(self.col.YELLOW, fname)] + args))
  731. Print('%s %-38s %7s %7s %+7s' % (indent, 'function', 'old', 'new',
  732. 'delta'))
  733. for diff, name in delta:
  734. if diff:
  735. color = self.col.RED if diff > 0 else self.col.GREEN
  736. msg = '%s %-38s %7s %7s %+7d' % (indent, name,
  737. old.get(name, '-'), new.get(name,'-'), diff)
  738. Print(msg, colour=color)
  739. def PrintSizeDetail(self, target_list, show_bloat):
  740. """Show details size information for each board
  741. Args:
  742. target_list: List of targets, each a dict containing:
  743. 'target': Target name
  744. 'total_diff': Total difference in bytes across all areas
  745. <part_name>: Difference for that part
  746. show_bloat: Show detail for each function
  747. """
  748. targets_by_diff = sorted(target_list, reverse=True,
  749. key=lambda x: x['_total_diff'])
  750. for result in targets_by_diff:
  751. printed_target = False
  752. for name in sorted(result):
  753. diff = result[name]
  754. if name.startswith('_'):
  755. continue
  756. if diff != 0:
  757. color = self.col.RED if diff > 0 else self.col.GREEN
  758. msg = ' %s %+d' % (name, diff)
  759. if not printed_target:
  760. Print('%10s %-15s:' % ('', result['_target']),
  761. newline=False)
  762. printed_target = True
  763. Print(msg, colour=color, newline=False)
  764. if printed_target:
  765. Print()
  766. if show_bloat:
  767. target = result['_target']
  768. outcome = result['_outcome']
  769. base_outcome = self._base_board_dict[target]
  770. for fname in outcome.func_sizes:
  771. self.PrintFuncSizeDetail(fname,
  772. base_outcome.func_sizes[fname],
  773. outcome.func_sizes[fname])
  774. def PrintSizeSummary(self, board_selected, board_dict, show_detail,
  775. show_bloat):
  776. """Print a summary of image sizes broken down by section.
  777. The summary takes the form of one line per architecture. The
  778. line contains deltas for each of the sections (+ means the section
  779. got bigger, - means smaller). The nunmbers are the average number
  780. of bytes that a board in this section increased by.
  781. For example:
  782. powerpc: (622 boards) text -0.0
  783. arm: (285 boards) text -0.0
  784. nds32: (3 boards) text -8.0
  785. Args:
  786. board_selected: Dict containing boards to summarise, keyed by
  787. board.target
  788. board_dict: Dict containing boards for which we built this
  789. commit, keyed by board.target. The value is an Outcome object.
  790. show_detail: Show detail for each board
  791. show_bloat: Show detail for each function
  792. """
  793. arch_list = {}
  794. arch_count = {}
  795. # Calculate changes in size for different image parts
  796. # The previous sizes are in Board.sizes, for each board
  797. for target in board_dict:
  798. if target not in board_selected:
  799. continue
  800. base_sizes = self._base_board_dict[target].sizes
  801. outcome = board_dict[target]
  802. sizes = outcome.sizes
  803. # Loop through the list of images, creating a dict of size
  804. # changes for each image/part. We end up with something like
  805. # {'target' : 'snapper9g45, 'data' : 5, 'u-boot-spl:text' : -4}
  806. # which means that U-Boot data increased by 5 bytes and SPL
  807. # text decreased by 4.
  808. err = {'_target' : target}
  809. for image in sizes:
  810. if image in base_sizes:
  811. base_image = base_sizes[image]
  812. # Loop through the text, data, bss parts
  813. for part in sorted(sizes[image]):
  814. diff = sizes[image][part] - base_image[part]
  815. col = None
  816. if diff:
  817. if image == 'u-boot':
  818. name = part
  819. else:
  820. name = image + ':' + part
  821. err[name] = diff
  822. arch = board_selected[target].arch
  823. if not arch in arch_count:
  824. arch_count[arch] = 1
  825. else:
  826. arch_count[arch] += 1
  827. if not sizes:
  828. pass # Only add to our list when we have some stats
  829. elif not arch in arch_list:
  830. arch_list[arch] = [err]
  831. else:
  832. arch_list[arch].append(err)
  833. # We now have a list of image size changes sorted by arch
  834. # Print out a summary of these
  835. for arch, target_list in arch_list.iteritems():
  836. # Get total difference for each type
  837. totals = {}
  838. for result in target_list:
  839. total = 0
  840. for name, diff in result.iteritems():
  841. if name.startswith('_'):
  842. continue
  843. total += diff
  844. if name in totals:
  845. totals[name] += diff
  846. else:
  847. totals[name] = diff
  848. result['_total_diff'] = total
  849. result['_outcome'] = board_dict[result['_target']]
  850. count = len(target_list)
  851. printed_arch = False
  852. for name in sorted(totals):
  853. diff = totals[name]
  854. if diff:
  855. # Display the average difference in this name for this
  856. # architecture
  857. avg_diff = float(diff) / count
  858. color = self.col.RED if avg_diff > 0 else self.col.GREEN
  859. msg = ' %s %+1.1f' % (name, avg_diff)
  860. if not printed_arch:
  861. Print('%10s: (for %d/%d boards)' % (arch, count,
  862. arch_count[arch]), newline=False)
  863. printed_arch = True
  864. Print(msg, colour=color, newline=False)
  865. if printed_arch:
  866. Print()
  867. if show_detail:
  868. self.PrintSizeDetail(target_list, show_bloat)
  869. def PrintResultSummary(self, board_selected, board_dict, err_lines,
  870. err_line_boards, warn_lines, warn_line_boards,
  871. config, show_sizes, show_detail, show_bloat,
  872. show_config):
  873. """Compare results with the base results and display delta.
  874. Only boards mentioned in board_selected will be considered. This
  875. function is intended to be called repeatedly with the results of
  876. each commit. It therefore shows a 'diff' between what it saw in
  877. the last call and what it sees now.
  878. Args:
  879. board_selected: Dict containing boards to summarise, keyed by
  880. board.target
  881. board_dict: Dict containing boards for which we built this
  882. commit, keyed by board.target. The value is an Outcome object.
  883. err_lines: A list of errors for this commit, or [] if there is
  884. none, or we don't want to print errors
  885. err_line_boards: Dict keyed by error line, containing a list of
  886. the Board objects with that error
  887. warn_lines: A list of warnings for this commit, or [] if there is
  888. none, or we don't want to print errors
  889. warn_line_boards: Dict keyed by warning line, containing a list of
  890. the Board objects with that warning
  891. config: Dictionary keyed by filename - e.g. '.config'. Each
  892. value is itself a dictionary:
  893. key: config name
  894. value: config value
  895. show_sizes: Show image size deltas
  896. show_detail: Show detail for each board
  897. show_bloat: Show detail for each function
  898. show_config: Show config changes
  899. """
  900. def _BoardList(line, line_boards):
  901. """Helper function to get a line of boards containing a line
  902. Args:
  903. line: Error line to search for
  904. Return:
  905. String containing a list of boards with that error line, or
  906. '' if the user has not requested such a list
  907. """
  908. if self._list_error_boards:
  909. names = []
  910. for board in line_boards[line]:
  911. if not board.target in names:
  912. names.append(board.target)
  913. names_str = '(%s) ' % ','.join(names)
  914. else:
  915. names_str = ''
  916. return names_str
  917. def _CalcErrorDelta(base_lines, base_line_boards, lines, line_boards,
  918. char):
  919. better_lines = []
  920. worse_lines = []
  921. for line in lines:
  922. if line not in base_lines:
  923. worse_lines.append(char + '+' +
  924. _BoardList(line, line_boards) + line)
  925. for line in base_lines:
  926. if line not in lines:
  927. better_lines.append(char + '-' +
  928. _BoardList(line, base_line_boards) + line)
  929. return better_lines, worse_lines
  930. def _CalcConfig(delta, name, config):
  931. """Calculate configuration changes
  932. Args:
  933. delta: Type of the delta, e.g. '+'
  934. name: name of the file which changed (e.g. .config)
  935. config: configuration change dictionary
  936. key: config name
  937. value: config value
  938. Returns:
  939. String containing the configuration changes which can be
  940. printed
  941. """
  942. out = ''
  943. for key in sorted(config.keys()):
  944. out += '%s=%s ' % (key, config[key])
  945. return '%s %s: %s' % (delta, name, out)
  946. def _AddConfig(lines, name, config_plus, config_minus, config_change):
  947. """Add changes in configuration to a list
  948. Args:
  949. lines: list to add to
  950. name: config file name
  951. config_plus: configurations added, dictionary
  952. key: config name
  953. value: config value
  954. config_minus: configurations removed, dictionary
  955. key: config name
  956. value: config value
  957. config_change: configurations changed, dictionary
  958. key: config name
  959. value: config value
  960. """
  961. if config_plus:
  962. lines.append(_CalcConfig('+', name, config_plus))
  963. if config_minus:
  964. lines.append(_CalcConfig('-', name, config_minus))
  965. if config_change:
  966. lines.append(_CalcConfig('c', name, config_change))
  967. def _OutputConfigInfo(lines):
  968. for line in lines:
  969. if not line:
  970. continue
  971. if line[0] == '+':
  972. col = self.col.GREEN
  973. elif line[0] == '-':
  974. col = self.col.RED
  975. elif line[0] == 'c':
  976. col = self.col.YELLOW
  977. Print(' ' + line, newline=True, colour=col)
  978. better = [] # List of boards fixed since last commit
  979. worse = [] # List of new broken boards since last commit
  980. new = [] # List of boards that didn't exist last time
  981. unknown = [] # List of boards that were not built
  982. for target in board_dict:
  983. if target not in board_selected:
  984. continue
  985. # If the board was built last time, add its outcome to a list
  986. if target in self._base_board_dict:
  987. base_outcome = self._base_board_dict[target].rc
  988. outcome = board_dict[target]
  989. if outcome.rc == OUTCOME_UNKNOWN:
  990. unknown.append(target)
  991. elif outcome.rc < base_outcome:
  992. better.append(target)
  993. elif outcome.rc > base_outcome:
  994. worse.append(target)
  995. else:
  996. new.append(target)
  997. # Get a list of errors that have appeared, and disappeared
  998. better_err, worse_err = _CalcErrorDelta(self._base_err_lines,
  999. self._base_err_line_boards, err_lines, err_line_boards, '')
  1000. better_warn, worse_warn = _CalcErrorDelta(self._base_warn_lines,
  1001. self._base_warn_line_boards, warn_lines, warn_line_boards, 'w')
  1002. # Display results by arch
  1003. if (better or worse or unknown or new or worse_err or better_err
  1004. or worse_warn or better_warn):
  1005. arch_list = {}
  1006. self.AddOutcome(board_selected, arch_list, better, '',
  1007. self.col.GREEN)
  1008. self.AddOutcome(board_selected, arch_list, worse, '+',
  1009. self.col.RED)
  1010. self.AddOutcome(board_selected, arch_list, new, '*', self.col.BLUE)
  1011. if self._show_unknown:
  1012. self.AddOutcome(board_selected, arch_list, unknown, '?',
  1013. self.col.MAGENTA)
  1014. for arch, target_list in arch_list.iteritems():
  1015. Print('%10s: %s' % (arch, target_list))
  1016. self._error_lines += 1
  1017. if better_err:
  1018. Print('\n'.join(better_err), colour=self.col.GREEN)
  1019. self._error_lines += 1
  1020. if worse_err:
  1021. Print('\n'.join(worse_err), colour=self.col.RED)
  1022. self._error_lines += 1
  1023. if better_warn:
  1024. Print('\n'.join(better_warn), colour=self.col.CYAN)
  1025. self._error_lines += 1
  1026. if worse_warn:
  1027. Print('\n'.join(worse_warn), colour=self.col.MAGENTA)
  1028. self._error_lines += 1
  1029. if show_sizes:
  1030. self.PrintSizeSummary(board_selected, board_dict, show_detail,
  1031. show_bloat)
  1032. if show_config and self._base_config:
  1033. summary = {}
  1034. arch_config_plus = {}
  1035. arch_config_minus = {}
  1036. arch_config_change = {}
  1037. arch_list = []
  1038. for target in board_dict:
  1039. if target not in board_selected:
  1040. continue
  1041. arch = board_selected[target].arch
  1042. if arch not in arch_list:
  1043. arch_list.append(arch)
  1044. for arch in arch_list:
  1045. arch_config_plus[arch] = {}
  1046. arch_config_minus[arch] = {}
  1047. arch_config_change[arch] = {}
  1048. for name in CONFIG_FILENAMES:
  1049. arch_config_plus[arch][name] = {}
  1050. arch_config_minus[arch][name] = {}
  1051. arch_config_change[arch][name] = {}
  1052. for target in board_dict:
  1053. if target not in board_selected:
  1054. continue
  1055. arch = board_selected[target].arch
  1056. all_config_plus = {}
  1057. all_config_minus = {}
  1058. all_config_change = {}
  1059. tbase = self._base_config[target]
  1060. tconfig = config[target]
  1061. lines = []
  1062. for name in CONFIG_FILENAMES:
  1063. if not tconfig.config[name]:
  1064. continue
  1065. config_plus = {}
  1066. config_minus = {}
  1067. config_change = {}
  1068. base = tbase.config[name]
  1069. for key, value in tconfig.config[name].iteritems():
  1070. if key not in base:
  1071. config_plus[key] = value
  1072. all_config_plus[key] = value
  1073. for key, value in base.iteritems():
  1074. if key not in tconfig.config[name]:
  1075. config_minus[key] = value
  1076. all_config_minus[key] = value
  1077. for key, value in base.iteritems():
  1078. new_value = tconfig.config.get(key)
  1079. if new_value and value != new_value:
  1080. desc = '%s -> %s' % (value, new_value)
  1081. config_change[key] = desc
  1082. all_config_change[key] = desc
  1083. arch_config_plus[arch][name].update(config_plus)
  1084. arch_config_minus[arch][name].update(config_minus)
  1085. arch_config_change[arch][name].update(config_change)
  1086. _AddConfig(lines, name, config_plus, config_minus,
  1087. config_change)
  1088. _AddConfig(lines, 'all', all_config_plus, all_config_minus,
  1089. all_config_change)
  1090. summary[target] = '\n'.join(lines)
  1091. lines_by_target = {}
  1092. for target, lines in summary.iteritems():
  1093. if lines in lines_by_target:
  1094. lines_by_target[lines].append(target)
  1095. else:
  1096. lines_by_target[lines] = [target]
  1097. for arch in arch_list:
  1098. lines = []
  1099. all_plus = {}
  1100. all_minus = {}
  1101. all_change = {}
  1102. for name in CONFIG_FILENAMES:
  1103. all_plus.update(arch_config_plus[arch][name])
  1104. all_minus.update(arch_config_minus[arch][name])
  1105. all_change.update(arch_config_change[arch][name])
  1106. _AddConfig(lines, name, arch_config_plus[arch][name],
  1107. arch_config_minus[arch][name],
  1108. arch_config_change[arch][name])
  1109. _AddConfig(lines, 'all', all_plus, all_minus, all_change)
  1110. #arch_summary[target] = '\n'.join(lines)
  1111. if lines:
  1112. Print('%s:' % arch)
  1113. _OutputConfigInfo(lines)
  1114. for lines, targets in lines_by_target.iteritems():
  1115. if not lines:
  1116. continue
  1117. Print('%s :' % ' '.join(sorted(targets)))
  1118. _OutputConfigInfo(lines.split('\n'))
  1119. # Save our updated information for the next call to this function
  1120. self._base_board_dict = board_dict
  1121. self._base_err_lines = err_lines
  1122. self._base_warn_lines = warn_lines
  1123. self._base_err_line_boards = err_line_boards
  1124. self._base_warn_line_boards = warn_line_boards
  1125. self._base_config = config
  1126. # Get a list of boards that did not get built, if needed
  1127. not_built = []
  1128. for board in board_selected:
  1129. if not board in board_dict:
  1130. not_built.append(board)
  1131. if not_built:
  1132. Print("Boards not built (%d): %s" % (len(not_built),
  1133. ', '.join(not_built)))
  1134. def ProduceResultSummary(self, commit_upto, commits, board_selected):
  1135. (board_dict, err_lines, err_line_boards, warn_lines,
  1136. warn_line_boards, config) = self.GetResultSummary(
  1137. board_selected, commit_upto,
  1138. read_func_sizes=self._show_bloat,
  1139. read_config=self._show_config)
  1140. if commits:
  1141. msg = '%02d: %s' % (commit_upto + 1,
  1142. commits[commit_upto].subject)
  1143. Print(msg, colour=self.col.BLUE)
  1144. self.PrintResultSummary(board_selected, board_dict,
  1145. err_lines if self._show_errors else [], err_line_boards,
  1146. warn_lines if self._show_errors else [], warn_line_boards,
  1147. config, self._show_sizes, self._show_detail,
  1148. self._show_bloat, self._show_config)
  1149. def ShowSummary(self, commits, board_selected):
  1150. """Show a build summary for U-Boot for a given board list.
  1151. Reset the result summary, then repeatedly call GetResultSummary on
  1152. each commit's results, then display the differences we see.
  1153. Args:
  1154. commit: Commit objects to summarise
  1155. board_selected: Dict containing boards to summarise
  1156. """
  1157. self.commit_count = len(commits) if commits else 1
  1158. self.commits = commits
  1159. self.ResetResultSummary(board_selected)
  1160. self._error_lines = 0
  1161. for commit_upto in range(0, self.commit_count, self._step):
  1162. self.ProduceResultSummary(commit_upto, commits, board_selected)
  1163. if not self._error_lines:
  1164. Print('(no errors to report)', colour=self.col.GREEN)
  1165. def SetupBuild(self, board_selected, commits):
  1166. """Set up ready to start a build.
  1167. Args:
  1168. board_selected: Selected boards to build
  1169. commits: Selected commits to build
  1170. """
  1171. # First work out how many commits we will build
  1172. count = (self.commit_count + self._step - 1) / self._step
  1173. self.count = len(board_selected) * count
  1174. self.upto = self.warned = self.fail = 0
  1175. self._timestamps = collections.deque()
  1176. def GetThreadDir(self, thread_num):
  1177. """Get the directory path to the working dir for a thread.
  1178. Args:
  1179. thread_num: Number of thread to check.
  1180. """
  1181. return os.path.join(self._working_dir, '%02d' % thread_num)
  1182. def _PrepareThread(self, thread_num, setup_git):
  1183. """Prepare the working directory for a thread.
  1184. This clones or fetches the repo into the thread's work directory.
  1185. Args:
  1186. thread_num: Thread number (0, 1, ...)
  1187. setup_git: True to set up a git repo clone
  1188. """
  1189. thread_dir = self.GetThreadDir(thread_num)
  1190. builderthread.Mkdir(thread_dir)
  1191. git_dir = os.path.join(thread_dir, '.git')
  1192. # Clone the repo if it doesn't already exist
  1193. # TODO(sjg@chromium): Perhaps some git hackery to symlink instead, so
  1194. # we have a private index but uses the origin repo's contents?
  1195. if setup_git and self.git_dir:
  1196. src_dir = os.path.abspath(self.git_dir)
  1197. if os.path.exists(git_dir):
  1198. gitutil.Fetch(git_dir, thread_dir)
  1199. else:
  1200. Print('\rCloning repo for thread %d' % thread_num,
  1201. newline=False)
  1202. gitutil.Clone(src_dir, thread_dir)
  1203. Print('\r%s\r' % (' ' * 30), newline=False)
  1204. def _PrepareWorkingSpace(self, max_threads, setup_git):
  1205. """Prepare the working directory for use.
  1206. Set up the git repo for each thread.
  1207. Args:
  1208. max_threads: Maximum number of threads we expect to need.
  1209. setup_git: True to set up a git repo clone
  1210. """
  1211. builderthread.Mkdir(self._working_dir)
  1212. for thread in range(max_threads):
  1213. self._PrepareThread(thread, setup_git)
  1214. def _PrepareOutputSpace(self):
  1215. """Get the output directories ready to receive files.
  1216. We delete any output directories which look like ones we need to
  1217. create. Having left over directories is confusing when the user wants
  1218. to check the output manually.
  1219. """
  1220. if not self.commits:
  1221. return
  1222. dir_list = []
  1223. for commit_upto in range(self.commit_count):
  1224. dir_list.append(self._GetOutputDir(commit_upto))
  1225. for dirname in glob.glob(os.path.join(self.base_dir, '*')):
  1226. if dirname not in dir_list:
  1227. shutil.rmtree(dirname)
  1228. def BuildBoards(self, commits, board_selected, keep_outputs, verbose):
  1229. """Build all commits for a list of boards
  1230. Args:
  1231. commits: List of commits to be build, each a Commit object
  1232. boards_selected: Dict of selected boards, key is target name,
  1233. value is Board object
  1234. keep_outputs: True to save build output files
  1235. verbose: Display build results as they are completed
  1236. Returns:
  1237. Tuple containing:
  1238. - number of boards that failed to build
  1239. - number of boards that issued warnings
  1240. """
  1241. self.commit_count = len(commits) if commits else 1
  1242. self.commits = commits
  1243. self._verbose = verbose
  1244. self.ResetResultSummary(board_selected)
  1245. builderthread.Mkdir(self.base_dir, parents = True)
  1246. self._PrepareWorkingSpace(min(self.num_threads, len(board_selected)),
  1247. commits is not None)
  1248. self._PrepareOutputSpace()
  1249. self.SetupBuild(board_selected, commits)
  1250. self.ProcessResult(None)
  1251. # Create jobs to build all commits for each board
  1252. for brd in board_selected.itervalues():
  1253. job = builderthread.BuilderJob()
  1254. job.board = brd
  1255. job.commits = commits
  1256. job.keep_outputs = keep_outputs
  1257. job.step = self._step
  1258. self.queue.put(job)
  1259. # Wait until all jobs are started
  1260. self.queue.join()
  1261. # Wait until we have processed all output
  1262. self.out_queue.join()
  1263. Print()
  1264. self.ClearLine(0)
  1265. return (self.fail, self.warned)