builder.py 58 KB

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