builder.py 62 KB

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