builder.py 57 KB

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