builder.py 58 KB

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