builder.py 58 KB

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