builder.py 47 KB

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