builder.py 58 KB

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