builder.py 71 KB

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