builder.py 70 KB

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