builder.py 58 KB

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