Loading...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 | # SPDX-License-Identifier: GPL-2.0+ # Copyright (c) 2013 The Chromium OS Authors. # # Bloat-o-meter code used here Copyright 2004 Matt Mackall <mpm@selenic.com> # """Build manager for U-Boot builds across multiple boards and commits""" # pylint: disable=R0902,R0903 import collections from datetime import datetime, timedelta import glob import os import re import queue import shutil import signal import sys import threading from buildman import builderthread from buildman.cfgutil import Config, process_config from buildman.outcome import (DisplayOptions, Outcome, OUTCOME_OK, OUTCOME_WARNING, OUTCOME_ERROR, OUTCOME_UNKNOWN) from u_boot_pylib import command from u_boot_pylib import gitutil from u_boot_pylib import terminal from u_boot_pylib import tools from u_boot_pylib.terminal import tprint # This indicates an new int or hex Kconfig property with no default # It hangs the build since the 'conf' tool cannot proceed without valid input. # # We get a repeat sequence of something like this: # >> # Break things (BREAK_ME) [] (NEW) # Error in reading or end of file. # << # which indicates that BREAK_ME has an empty default RE_NO_DEFAULT = re.compile(br'\((\w+)\) \[] \(NEW\)') # Regex patterns for matching compiler output RE_FUNCTION = re.compile('(.*): In function.*') RE_FILES = re.compile('In file included from.*') RE_WARNING = re.compile(r'(.*):(\d*):(\d*): warning: .*') RE_DTB_WARNING = re.compile('(.*): Warning .*') RE_NOTE = re.compile( r'(.*):(\d*):(\d*): note: this is the location of the previous.*') RE_MIGRATION_WARNING = re.compile(r'^={21} WARNING ={22}\n.*\n=+\n', re.MULTILINE | re.DOTALL) RE_MAKE_ERR = re.compile('(make.*Waiting for unfinished)|(Segmentation fault)') # Symbol types which appear in the bloat feature (-B). Others are silently # dropped when reading in the 'nm' output NM_SYMBOL_TYPES = 'tTdDbBr' """ Theory of Operation Please see README for user documentation, and you should be familiar with that before trying to make sense of this. Buildman works by keeping the machine as busy as possible, building different commits for different boards on multiple CPUs at once. The source repo (self.git_dir) contains all the commits to be built. Each thread works on a single board at a time. It checks out the first commit, configures it for that board, then builds it. Then it checks out the next commit and builds it (typically without re-configuring). When it runs out of commits, it gets another job from the builder and starts again with that board. Clearly the builder threads could work either way - they could check out a commit and then built it for all boards. Using separate directories for each commit/board pair they could leave their build product around afterwards also. The intent behind building a single board for multiple commits, is to make use of incremental builds. Since each commit is built incrementally from the previous one, builds are faster. Reconfiguring for a different board removes all intermediate object files. Many threads can be working at once, but each has its own working directory. When a thread finishes a build, it puts the output files into a result directory. The base directory used by buildman is normally '../<branch>', i.e. a directory higher than the source repository and named after the branch being built. Within the base directory, we have one subdirectory for each commit. Within that is one subdirectory for each board. Within that is the build output for that commit/board combination. Buildman also create working directories for each thread, in a .bm-work/ subdirectory in the base dir. As an example, say we are building branch 'us-net' for boards 'sandbox' and 'seaboard', and say that us-net has two commits. We will have directories like this: us-net/ base directory 01_g4ed4ebc_net--Add-tftp-speed-/ sandbox/ u-boot.bin seaboard/ u-boot.bin 02_g4ed4ebc_net--Check-tftp-comp/ sandbox/ u-boot.bin seaboard/ u-boot.bin .bm-work/ 00/ working directory for thread 0 (contains source checkout) build/ build output 01/ working directory for thread 1 build/ build output ... u-boot/ source directory .git/ repository """ # Translate a commit subject into a valid filename (and handle unicode) trans_valid_chars = str.maketrans('/: ', '---') BASE_CONFIG_FILENAMES = [ 'u-boot.cfg', 'u-boot-spl.cfg', 'u-boot-tpl.cfg' ] EXTRA_CONFIG_FILENAMES = [ '.config', '.config-spl', '.config-tpl', 'autoconf.mk', 'autoconf-spl.mk', 'autoconf-tpl.mk', 'autoconf.h', 'autoconf-spl.h','autoconf-tpl.h', ] class Environment: """Holds information about environment variables for a board.""" def __init__(self, target): self.target = target self.environment = {} def add(self, key, value): """Add an environment variable Args: key (str): Environment variable name value (str): Environment variable value """ self.environment[key] = value class Builder: """Class for building U-Boot for a particular commit. Public members: base_dir: Base directory to use for builder checkout: True to check out source, False to skip that step. This is used for testing. commit_count: Number of commits being built commits: List of commits being built count: Total number of commits to build, which is the number of commits multiplied by the number of boards do_make: Method to call to invoke Make fail: Number of builds that failed due to error force_build: Force building even if a build already exists force_config_on_failure: If a commit fails for a board, disable incremental building for the next commit we build for that board, so that we will see all warnings/errors again. force_build_failures: If a previously-built build (i.e. built on a previous run of buildman) is marked as failed, rebuild it. git_dir: Git directory containing source repository gnu_make: Command name for GNU Make in_tree: Build U-Boot in-tree instead of specifying an output directory separate from the source code. This option is really only useful for testing in-tree builds. kconfig_reconfig: Number of builds triggered by Kconfig changes num_jobs: Number of jobs to run at once (passed to make as -j) out_queue: Queue of results to process queue: Queue of jobs to run force_reconfig: Reconfigure U-Boot on each comiit. This disables incremental building, where buildman reconfigures on the first commit for a baord, and then just does an incremental build for the following commits. In fact buildman will reconfigure and retry for any failing commits, so generally the only effect of this option is to slow things down. thread_exceptions: List of exceptions raised by thread jobs toolchains: Toolchains object to use for building work_in_output: Use the output directory as the work directory and don't write to a separate output directory. no_lto (bool): True to set the NO_LTO flag when building reproducible_builds (bool): True to set SOURCE_DATE_EPOCH=0 for builds Private members: _already_done: Number of builds already completed _build_period_us: Time taken for a single build (float object). _col: terminal.Color() object _commit: Current commit being built _complete_delay: Expected delay until completion (timedelta) _next_delay_update: Next time we plan to display a progress update (datatime) _opts: DisplayOptions for result output _re_make_err: Compiled regex for make error detection _restarting_config: True if 'Restart config' is detected in output _result_handler: ResultHandler for displaying results _single_builder: BuilderThread object for the singer builder, if threading is not being used _terminated: Thread was terminated due to an error _threads: List of active threads _timestamps: List of timestamps for the completion of the last last _timestamp_count builds. Each is a datetime object. _timestamp_count: Number of timestamps to keep in our list. _upto: Current commit number we are building (0.count-1) _warned: Number of builds that produced at least one warning _working_dir: Base working directory containing all threads """ def __init__(self, toolchains, base_dir, git_dir, num_threads, num_jobs, col, result_handler, gnu_make='make', checkout=True, step=1, no_subdirs=False, full_path=False, verbose_build=False, mrproper=False, fallback_mrproper=False, per_board_out_dir=False, config_only=False, squash_config_y=False, warnings_as_errors=False, work_in_output=False, test_thread_exceptions=False, adjust_cfg=None, allow_missing=False, no_lto=False, reproducible_builds=False, force_build=False, force_build_failures=False, kconfig_check=True, force_reconfig=False, in_tree=False, force_config_on_failure=False, make_func=None, dtc_skip=False, build_target=None, thread_class=builderthread.BuilderThread, handle_signals=True, lazy_thread_setup=False): """Create a new Builder object Args: toolchains: Toolchains object to use for building base_dir: Base directory to use for builder git_dir: Git directory containing source repository result_handler: ResultHandler object for displaying results num_threads: Number of builder threads to run num_jobs: Number of jobs to run at once (passed to make as -j) col: terminal.Color object for coloured output gnu_make: the command name of GNU Make. checkout: True to check out source, False to skip that step. This is used for testing. step: 1 to process every commit, n to process every nth commit no_subdirs: Don't create subdirectories when building current source for a single board full_path: Return the full path in CROSS_COMPILE and don't set PATH verbose_build: Run build with V=1 and don't use 'make -s' mrproper: Always run 'make mrproper' when configuring fallback_mrproper: Run 'make mrproper' and retry on build failure per_board_out_dir: Build in a separate persistent directory per board rather than a thread-specific directory config_only: Only configure each build, don't build it squash_config_y: Convert CONFIG options with the value 'y' to '1' warnings_as_errors: Treat all compiler warnings as errors work_in_output: Use the output directory as the work directory and don't write to a separate output directory. test_thread_exceptions: Uses for tests only, True to make the threads raise an exception instead of reporting their result. This simulates a failure in the code somewhere adjust_cfg_list (list of str): List of changes to make to .config file before building. Each is one of (where C is the config option with or without the CONFIG_ prefix) C to enable C ~C to disable C C=val to set the value of C (val must have quotes if C is a string Kconfig allow_missing: Run build with BINMAN_ALLOW_MISSING=1 no_lto (bool): True to set the NO_LTO flag when building force_build (bool): Rebuild even commits that are already built force_build_failures (bool): Rebuild commits that have not been built, or failed to build kconfig_check (bool): Check if Kconfig files have changed and force a rebuild if so (default True) force_reconfig (bool): Reconfigure on each commit in_tree (bool): Bulid in tree instead of out-of-tree force_config_on_failure (bool): Reconfigure the build before retrying a failed build make_func (function): Function to call to run 'make' dtc_skip (bool): True to skip building dtc and use the system one build_target (str): Build target to use (None to use the default) thread_class (type): BuilderThread subclass to use (default builderthread.BuilderThread). This allows the caller to override how results are processed, e.g. sending over SSH instead of writing to disk. handle_signals (bool): True to register SIGINT handler (default True). Set to False when running inside a worker that has its own signal handling. """ self.toolchains = toolchains self.base_dir = base_dir if work_in_output: self._working_dir = base_dir else: self._working_dir = os.path.join(base_dir, '.bm-work') self._threads = [] self.do_make = make_func or self.make self.gnu_make = gnu_make self.checkout = checkout self.num_threads = num_threads self.num_jobs = num_jobs self.active_boards = 0 self.max_boards = 0 self.active_lock = threading.Lock() self._already_done = 0 self.kconfig_reconfig = 0 self.force_build = False self.git_dir = git_dir self._setup_git = False self._timestamp_count = 10 self._build_period_us = None self._complete_delay = None self._next_delay_update = datetime.now() self.start_time = None self.step = step self.no_subdirs = no_subdirs self.full_path = full_path self.verbose_build = verbose_build self.config_only = config_only self.squash_config_y = squash_config_y self.config_filenames = BASE_CONFIG_FILENAMES self.work_in_output = work_in_output self.adjust_cfg = adjust_cfg self.allow_missing = allow_missing self.no_lto = no_lto self.reproducible_builds = reproducible_builds self.force_build = force_build self.force_build_failures = force_build_failures self.kconfig_check = kconfig_check self.force_reconfig = force_reconfig self.in_tree = in_tree self.force_config_on_failure = force_config_on_failure self.fallback_mrproper = fallback_mrproper if dtc_skip: self.dtc = shutil.which('dtc') if not self.dtc: raise ValueError('Cannot find dtc') else: self.dtc = None self.build_target = build_target if not self.squash_config_y: self.config_filenames += EXTRA_CONFIG_FILENAMES self._terminated = False self._restarting_config = False self.warnings_as_errors = warnings_as_errors self.col = col self._result_handler = result_handler self.thread_exceptions = [] self.test_thread_exceptions = test_thread_exceptions # Attributes used by set_display_options() self._opts = DisplayOptions( show_errors=True, show_sizes=False, show_detail=False, show_bloat=False, show_config=False, show_environment=False, show_unknown=True, ide=False, list_error_boards=False) self._filter_dtb_warnings = False self._filter_migration_warnings = False # Attributes set by other methods self._build_period = None self._commit = None self.upto = 0 self._warned = 0 self.fail = 0 self.commit_count = 0 self.commits = None self.count = 0 self.timestamps = collections.deque() self.verbose = False self.progress = '' # Note: baseline state for result summaries is now in ResultHandler self._thread_class = thread_class self._lazy_thread_setup = lazy_thread_setup self._setup_threads(mrproper, per_board_out_dir, test_thread_exceptions) ignore_lines = ['(make.*Waiting for unfinished)', '(Segmentation fault)'] self._re_make_err = re.compile('|'.join(ignore_lines)) # Handle existing graceful with SIGINT / Ctrl-C if handle_signals: signal.signal(signal.SIGINT, self._signal_handler) def _setup_threads(self, mrproper, per_board_out_dir, test_thread_exceptions): """Set up builder threads Args: mrproper (bool): True to run 'make mrproper' before building per_board_out_dir (bool): True to use a separate output directory per board test_thread_exceptions (bool): True to make threads raise an exception instead of reporting their result (for tests) """ if self.num_threads: self._single_builder = None self.queue = queue.Queue() self.out_queue = queue.Queue() for i in range(self.num_threads): t = self._thread_class( self, i, mrproper, per_board_out_dir, test_exception=test_thread_exceptions) t.daemon = True t.start() self._threads.append(t) t = builderthread.ResultThread(self) t.daemon = True t.start() self._threads.append(t) else: self._single_builder = self._thread_class( self, -1, mrproper, per_board_out_dir) def __del__(self): """Get rid of all threads created by the builder""" self._threads.clear() def _signal_handler(self, _signum, _frame): """Handle a signal by exiting""" sys.exit(1) def make_environment(self, toolchain): """Create the environment to use for building Args: toolchain (Toolchain): Toolchain to use for building Returns: dict: key (str): Variable name value (str): Variable value """ env = toolchain.make_environment(self.full_path) if self.dtc: env[b'DTC'] = tools.to_bytes(self.dtc) return env def set_display_options(self, display_options, filter_dtb_warnings=False, filter_migration_warnings=False): """Setup display options for the builder. Args: display_options (DisplayOptions): Named tuple containing display settings (show_errors, show_sizes, show_detail, show_bloat, show_config, show_environment, show_unknown, ide, list_error_boards) filter_dtb_warnings (bool): Filter out any warnings from the device-tree compiler filter_migration_warnings (bool): Filter out any warnings about migrating a board to driver model """ self._opts = display_options self._filter_dtb_warnings = filter_dtb_warnings self._filter_migration_warnings = filter_migration_warnings @property def result_handler(self): """Get the result handler for this builder""" return self._result_handler def _add_timestamp(self): """Add a new timestamp to the list and record the build period. The build period is the length of time taken to perform a single build (one board, one commit). """ now = datetime.now() self.timestamps.append(now) count = len(self.timestamps) delta = self.timestamps[-1] - self.timestamps[0] seconds = delta.total_seconds() # If we have enough data, estimate build period (time taken for a # single build) and therefore completion time. if count > 1 and self._next_delay_update < now: self._next_delay_update = now + timedelta(seconds=2) if seconds > 0: self._build_period = float(seconds) / count todo = self.count - self.upto self._complete_delay = timedelta(microseconds= self._build_period * todo * 1000000) # Round it self._complete_delay -= timedelta( microseconds=self._complete_delay.microseconds) if seconds > 60: self.timestamps.popleft() count -= 1 def _select_commit(self, commit, checkout=True): """Checkout the selected commit for this build Args: commit (Commit): Commit object that is being built checkout (bool): True to checkout the commit """ self._commit = commit if checkout and self.checkout: gitutil.checkout(commit.hash) def _check_output_for_loop(self, data): """Check output for config restart loops This detects when Kconfig enters a restart loop due to missing defaults. It looks for 'Restart config' followed by multiple occurrences of the same Kconfig item with no default. Args: data (bytes): Output data to check Returns: bool: True to terminate the command, False to continue """ if b'Restart config' in data: self._restarting_config = True # If we see 'Restart config' followed by multiple errors if self._restarting_config: matches = RE_NO_DEFAULT.findall(data) # Number of occurrences of each Kconfig item multiple = [matches.count(val) for val in set(matches)] # If any of them occur more than once, we have a loop if [val for val in multiple if val > 1]: self._terminated = True return True return False def make(self, _commit, _brd, _stage, cwd, *args, **kwargs): """Run make Args: cwd (str): Directory where make should be run args: Arguments to pass to make kwargs: Arguments to pass to command.run_one() Returns: CommandResult: Result of the make operation """ self._restarting_config = False self._terminated = False cmd = [self.gnu_make] + list(args) result = command.run_one( *cmd, capture=True, capture_stderr=True, cwd=cwd, raise_on_error=False, infile='/dev/null', output_func=lambda stream, data: self._check_output_for_loop(data), **kwargs) if self._terminated: # Try to be helpful result.stderr += \ '(** did you define an int/hex Kconfig with no default? **)' if self.verbose_build: result.stdout = f"{' '.join(cmd)}\n" + result.stdout result.combined = f"{' '.join(cmd)}\n" + result.combined return result def process_result(self, result): """Process the result of a build, showing progress information Args: result (CommandResult): Result object, which indicates the result for a single build """ if result: target = result.brd.target self.upto += 1 if result.return_code != 0: self.fail += 1 elif result.stderr: self._warned += 1 if result.already_done: self._already_done += 1 if result.kconfig_reconfig: self.kconfig_reconfig += 1 if self._opts.ide: if result.stderr: sys.stderr.write(result.stderr) elif self.verbose: terminal.print_clear() machine = result.remote if machine and (result.return_code or result.stderr): tprint(f'[{machine}]') boards_selected = {target : result.brd} self._result_handler.reset_result_summary(boards_selected) self._result_handler.produce_result_summary( result.commit_upto, self.commits, boards_selected) else: target = '(starting)' # Display separate counts for ok, warned and fail ok = self.upto - self._warned - self.fail line = '\r' + self.col.build(self.col.GREEN, f'{ok:5d}') line += self.col.build(self.col.YELLOW, f'{self._warned:5d}') line += self.col.build(self.col.RED, f'{self.fail:5d}') line += f' /{self.count:<5d} ' remaining = self.count - self.upto if remaining: line += self.col.build(self.col.MAGENTA, f' -{remaining:<5d} ') else: line += ' ' * 8 # Add our current completion time estimate self._add_timestamp() if self._complete_delay: line += f'{self._complete_delay} : ' machine = result.remote if result else None if machine: line += f'{target} [{machine}]' elif self.progress: line += f'{target} [{self.progress}]' else: line += f'{target} [local]' if not self._opts.ide: terminal.print_clear() tprint(line, newline=False, limit_to_line=True) def get_output_dir(self, commit_upto): """Get the name of the output directory for a commit number The output directory is typically .../<branch>/<commit>. Args: commit_upto (int): Commit number to use (0..self.count-1) Returns: str: Path to the output directory """ if self.work_in_output: return self._working_dir commit_dir = None if self.commits: commit = self.commits[commit_upto] subject = commit.subject.translate(trans_valid_chars) # See _get_output_space_removals() which parses this name commit_dir = f'{commit_upto + 1:02d}_g{commit.hash}_{subject[:20]}' elif not self.no_subdirs: commit_dir = 'current' if not commit_dir: return self.base_dir return os.path.join(self.base_dir, commit_dir) def get_build_dir(self, commit_upto, target): """Get the name of the build directory for a commit number The build directory is typically .../<branch>/<commit>/<target>. Args: commit_upto (int): Commit number to use (0..self.count-1) target (str): Target name Return: str: Output directory to use, or '' if None """ output_dir = self.get_output_dir(commit_upto) if self.work_in_output: return output_dir or '' return os.path.join(output_dir, target) def get_done_file(self, commit_upto, target): """Get the name of the done file for a commit number Args: commit_upto (int): Commit number to use (0..self.count-1) target (str): Target name Returns: str: Path to the done file """ return os.path.join(self.get_build_dir(commit_upto, target), 'done') def get_sizes_file(self, commit_upto, target): """Get the name of the sizes file for a commit number Args: commit_upto (int): Commit number to use (0..self.count-1) target (str): Target name Returns: str: Path to the sizes file """ return os.path.join(self.get_build_dir(commit_upto, target), 'sizes') def get_func_sizes_file(self, commit_upto, target, elf_fname): """Get the name of the funcsizes file for a commit number and ELF file Args: commit_upto (int): Commit number to use (0..self.count-1) target (str): Target name elf_fname (str): Filename of elf image Returns: str: Path to the funcsizes file """ return os.path.join(self.get_build_dir(commit_upto, target), f"{elf_fname.replace('/', '-')}.sizes") def get_objdump_file(self, commit_upto, target, elf_fname): """Get the name of the objdump file for a commit number and ELF file Args: commit_upto (int): Commit number to use (0..self.count-1) target (str): Target name elf_fname (str): Filename of elf image Returns: str: Path to the objdump file """ return os.path.join(self.get_build_dir(commit_upto, target), f"{elf_fname.replace('/', '-')}.objdump") def get_err_file(self, commit_upto, target): """Get the name of the err file for a commit number Args: commit_upto (int): Commit number to use (0..self.count-1) target (str): Target name Returns: str: Path to the err file """ output_dir = self.get_build_dir(commit_upto, target) return os.path.join(output_dir, 'err') def _filter_errors(self, lines): """Filter out errors in which we have no interest We should probably use map(). Args: lines (list of str): List of error lines, each a string Returns: list of str: New list with only interesting lines included """ out_lines = [] if self._filter_migration_warnings: text = '\n'.join(lines) text = RE_MIGRATION_WARNING.sub('', text) lines = text.splitlines() for line in lines: if RE_MAKE_ERR.search(line): continue if self._filter_dtb_warnings and RE_DTB_WARNING.search(line): continue out_lines.append(line) return out_lines def read_func_sizes(self, _fname, fd): """Read function sizes from the output of 'nm' Args: fd (file): File containing data to read Returns: dict: Dictionary containing size of each function in bytes, indexed by function name. """ sym = {} for line in fd.readlines(): line = line.strip() parts = line.split() if line and len(parts) == 3: size, sym_type, name = line.split() if sym_type in NM_SYMBOL_TYPES: # function names begin with '.' on 64-bit powerpc if '.' in name[1:]: name = 'static.' + name.split('.')[0] sym[name] = sym.get(name, 0) + int(size, 16) return sym def _process_environment(self, fname): """Read in a uboot.env file This function reads in environment variables from a file. Args: fname: Filename to read Returns: Dictionary: key: environment variable (e.g. bootlimit) value: value of environment variable (e.g. 1) """ environment = {} if os.path.exists(fname): with open(fname, encoding='utf-8') as fd: for line in fd.read().split('\0'): try: key, value = line.split('=', 1) environment[key] = value except ValueError: # ignore lines we can't parse pass return environment def _read_done_file(self, commit_upto, target, done_file, sizes_file): """Read the done file and collect build results Args: commit_upto (int): Commit number to check (0..n-1) target (str): Target board to check done_file (str): Filename of done file sizes_file (str): Filename of sizes file Returns: tuple: (rc, err_lines, sizes) where: rc: OUTCOME_OK, OUTCOME_WARNING or OUTCOME_ERROR err_lines: list of error lines sizes: dict of sizes """ with open(done_file, 'r', encoding='utf-8') as fd: try: return_code = int(fd.readline()) except ValueError: # The file may be empty due to running out of disk space. # Try a rebuild return_code = 1 err_lines = [] err_file = self.get_err_file(commit_upto, target) if os.path.exists(err_file): with open(err_file, 'r', encoding='utf-8') as fd: err_lines = self._filter_errors(fd.readlines()) # Decide whether the build was ok, failed or created warnings if return_code: rc = OUTCOME_ERROR elif err_lines: rc = OUTCOME_WARNING else: rc = OUTCOME_OK # Convert size information to our simple format sizes = {} if os.path.exists(sizes_file): with open(sizes_file, 'r', encoding='utf-8') as fd: for line in fd.readlines(): values = line.split() rodata = 0 if len(values) > 6: rodata = int(values[6], 16) size_dict = { 'all' : int(values[0]) + int(values[1]) + int(values[2]), 'text' : int(values[0]) - rodata, 'data' : int(values[1]), 'bss' : int(values[2]), 'rodata' : rodata, } sizes[values[5]] = size_dict return rc, err_lines, sizes def get_build_outcome(self, commit_upto, target, read_func_sizes, read_config, read_environment): """Work out the outcome of a build. Args: commit_upto (int): Commit number to check (0..n-1) target (str): Target board to check read_func_sizes (bool): True to read function size information read_config (bool): True to read .config and autoconf.h files read_environment (bool): True to read uboot.env files Returns: Outcome: Outcome object """ done_file = self.get_done_file(commit_upto, target) sizes_file = self.get_sizes_file(commit_upto, target) func_sizes = {} config = {} environment = {} if os.path.exists(done_file): rc, err_lines, sizes = self._read_done_file( commit_upto, target, done_file, sizes_file) if read_func_sizes: pattern = self.get_func_sizes_file(commit_upto, target, '*') for fname in glob.glob(pattern): with open(fname, 'r', encoding='utf-8') as fd: dict_name = os.path.basename(fname).replace('.sizes', '') func_sizes[dict_name] = self.read_func_sizes(fname, fd) if read_config: output_dir = self.get_build_dir(commit_upto, target) for name in self.config_filenames: fname = os.path.join(output_dir, name) config[name] = process_config(fname, self.squash_config_y) if read_environment: output_dir = self.get_build_dir(commit_upto, target) fname = os.path.join(output_dir, 'uboot.env') environment = self._process_environment(fname) return Outcome(rc, err_lines, sizes, func_sizes, config, environment) return Outcome(OUTCOME_UNKNOWN, [], {}, {}, {}, {}) @staticmethod def _add_line(lines_summary, lines_boards, line, brd): """Add a line to the summary and boards list Args: lines_summary (list): List of line strings lines_boards (dict): Dict of line strings to list of boards line (str): Line to add brd (Board): Board that produced this line """ line = line.rstrip() if line in lines_boards: lines_boards[line].append(brd) else: lines_boards[line] = [brd] lines_summary.append(line) def _categorise_err_lines(self, err_lines, brd, err_lines_summary, err_lines_boards, warn_lines_summary, warn_lines_boards): """Categorise error lines into errors and warnings Args: err_lines (list): List of error-line strings brd (Board): Board that produced these lines err_lines_summary (list): List of error-line strings err_lines_boards (dict): Dict of error-line strings to boards warn_lines_summary (list): List of warning-line strings warn_lines_boards (dict): Dict of warning-line strings to boards """ last_func = None last_was_warning = False for line in err_lines: if line: if (RE_FUNCTION.match(line) or RE_FILES.match(line)): last_func = line else: is_warning = (RE_WARNING.match(line) or RE_DTB_WARNING.match(line)) is_note = RE_NOTE.match(line) if is_warning or (last_was_warning and is_note): if last_func: self._add_line(warn_lines_summary, warn_lines_boards, last_func, brd) self._add_line(warn_lines_summary, warn_lines_boards, line, brd) else: if last_func: self._add_line(err_lines_summary, err_lines_boards, last_func, brd) self._add_line(err_lines_summary, err_lines_boards, line, brd) last_was_warning = is_warning last_func = None def get_result_summary(self, boards_selected, commit_upto, read_func_sizes, read_config, read_environment): """Calculate a summary of the results of building a commit. Args: boards_selected (dict): Dict containing boards to summarise commit_upto (int): Commit number to summarize (0..self.count-1) read_func_sizes (bool): True to read function size information read_config (bool): True to read .config and autoconf.h files read_environment (bool): True to read uboot.env files Returns: tuple: Tuple containing: Dict containing boards which built this commit: key: board.target value: Outcome object List containing a summary of error lines Dict keyed by error line, containing a list of the Board objects with that error List containing a summary of warning lines Dict keyed by error line, containing a list of the Board objects with that warning Dictionary keyed by board.target. Each value is a dictionary: key: filename - e.g. '.config' value is itself a dictionary: key: config name value: config value Dictionary keyed by board.target. Each value is a dictionary: key: environment variable value: value of environment variable """ board_dict = {} err_lines_summary = [] err_lines_boards = {} warn_lines_summary = [] warn_lines_boards = {} config = {} environment = {} for brd in boards_selected.values(): outcome = self.get_build_outcome(commit_upto, brd.target, read_func_sizes, read_config, read_environment) board_dict[brd.target] = outcome self._categorise_err_lines(outcome.err_lines, brd, err_lines_summary, err_lines_boards, warn_lines_summary, warn_lines_boards) tconfig = Config(self.config_filenames, brd.target) for fname in self.config_filenames: if outcome.config: for key, value in outcome.config[fname].items(): tconfig.add(fname, key, value) config[brd.target] = tconfig tenvironment = Environment(brd.target) if outcome.environment: for key, value in outcome.environment.items(): tenvironment.add(key, value) environment[brd.target] = tenvironment return (board_dict, err_lines_summary, err_lines_boards, warn_lines_summary, warn_lines_boards, config, environment) def _setup_build(self, board_selected, _commits): """Set up ready to start a build. Args: board_selected (dict): Selected boards to build """ # First work out how many commits we will build count = (self.commit_count + self.step - 1) // self.step self.count = len(board_selected) * count self.upto = self._warned = self.fail = 0 self.timestamps = collections.deque() def get_thread_dir(self, thread_num): """Get the directory path to the working dir for a thread. Args: thread_num (int): Number of thread to check (-1 for main process, which is treated as 0) Returns: str: Path to the thread's working directory """ if self.work_in_output: return self._working_dir return os.path.join(self._working_dir, f'{max(thread_num, 0):02d}') def prepare_thread(self, thread_num): """Prepare a single thread's working directory on demand This can be called by a BuilderThread to lazily set up its worktree/clone on first use, rather than doing all threads upfront. Uses the git setup method determined by _detect_git_setup(). Args: thread_num (int): Thread number (0, 1, ...) """ self._prepare_thread(thread_num, self._setup_git) def _prepare_thread(self, thread_num, setup_git): """Prepare the working directory for a thread. This clones or fetches the repo into the thread's work directory. Optionally, it can create a linked working tree of the repo in the thread's work directory instead. Args: thread_num: Thread number (0, 1, ...) setup_git: 'clone' to set up a git clone 'worktree' to set up a git worktree """ thread_dir = self.get_thread_dir(thread_num) builderthread.mkdir(thread_dir) git_dir = os.path.join(thread_dir, '.git') if thread_dir else None # Create a worktree or a git repo clone for this thread if it # doesn't already exist if setup_git and self.git_dir: src_dir = os.path.abspath(self.git_dir) if os.path.isdir(git_dir): # This is a clone of the src_dir repo, we can keep using # it but need to fetch from src_dir. tprint(f'\rFetching repo for thread {thread_num}', newline=False) gitutil.fetch(git_dir, thread_dir) terminal.print_clear() elif os.path.isfile(git_dir): # This is a worktree of the src_dir repo, we don't need to # create it again or update it in any way. pass elif os.path.exists(git_dir): # Don't know what could trigger this, but we probably # can't create a git worktree/clone here. raise ValueError(f'Git dir {git_dir} exists, but is not a ' 'file or a directory.') elif setup_git == 'worktree': tprint(f'\rChecking out worktree for thread {thread_num}', newline=False) gitutil.add_worktree(src_dir, thread_dir) terminal.print_clear() elif setup_git == 'clone' or setup_git is True: tprint(f'\rCloning repo for thread {thread_num}', newline=False) gitutil.clone(src_dir, thread_dir) terminal.print_clear() else: raise ValueError(f"Can't setup git repo with {setup_git}.") def prepare_working_space(self, max_threads, setup_git): """Prepare the working directory for use. Set up the git repo for each thread. Creates a linked working tree if git-worktree is available, or clones the repo if it isn't. When lazy_thread_setup is True, only the working directory and git setup type are determined here. Each thread sets up its own worktree/clone on first use via prepare_thread(), which avoids a long sequential setup phase on machines with many threads. Args: max_threads: Maximum number of threads we expect to need. If 0 then 1 is set up, since the main process still needs somewhere to work setup_git: True to set up a git worktree or a git clone """ builderthread.mkdir(self._working_dir) self._setup_git = self._detect_git_setup(setup_git) if self._lazy_thread_setup: return # Always do at least one thread for thread in range(max(max_threads, 1)): self._prepare_thread(thread, self._setup_git) def _detect_git_setup(self, setup_git): """Determine which git setup method to use Args: setup_git: True to set up git, False to skip Returns: str or False: 'worktree', 'clone', or False """ if setup_git and self.git_dir: src_dir = os.path.abspath(self.git_dir) if gitutil.check_worktree_is_available(src_dir): # If we previously added a worktree but the directory for it # got deleted, we need to prune its files from the repo so # that we can check out another in its place. gitutil.prune_worktrees(src_dir) return 'worktree' return 'clone' return False def _get_output_space_removals(self): """Get the output directories ready to receive files. Figure out what needs to be deleted in the output directory before it can be used. We only delete old buildman directories which have the expected name pattern. See get_output_dir(). Returns: List of full paths of directories to remove """ if not self.commits: return [] dir_list = [] for commit_upto in range(self.commit_count): dir_list.append(self.get_output_dir(commit_upto)) to_remove = [] for dirname in glob.glob(os.path.join(self.base_dir, '*')): if dirname not in dir_list: leaf = dirname[len(self.base_dir) + 1:] m = re.match('[0-9]+_g[0-9a-f]+_.*', leaf) if m: to_remove.append(dirname) return to_remove def prepare_output_space(self): """Get the output directories ready to receive files. We delete any output directories which look like ones we need to create. Having left over directories is confusing when the user wants to check the output manually. """ to_remove = self._get_output_space_removals() if to_remove: tprint(f'Removing {len(to_remove)} old build directories...', newline=False) for dirname in to_remove: shutil.rmtree(dirname) terminal.print_clear() def init_build(self, commits, board_selected, keep_outputs, verbose, fragments, extra_count=0): """Initialise a build: prepare working space and create jobs This sets up the working directory, output space and job queue but does not start the build threads. Call run_build() after this to start the build. Args: commits (list): List of commits to be build, each a Commit object board_selected (dict): Dict of selected boards, key is target name, value is Board object keep_outputs (bool): True to save build output files verbose (bool): Display build results as they are completed fragments (str): config fragments added to defconfig extra_count (int): Additional builds expected from external sources (e.g. distributed workers) to include in the progress total """ self.commit_count = len(commits) if commits else 1 self.commits = commits self.verbose = verbose self._result_handler.reset_result_summary(board_selected) builderthread.mkdir(self.base_dir, parents = True) self.prepare_working_space(min(self.num_threads, len(board_selected)), board_selected and commits is not None) self.prepare_output_space() if not self._opts.ide: tprint('\rStarting build...', newline=False) self.start_time = datetime.now() self._setup_build(board_selected, commits) self.count += extra_count self.process_result(None) self.thread_exceptions = [] # Create jobs to build all commits for each board for brd in board_selected.values(): job = builderthread.BuilderJob() job.brd = brd job.commits = commits job.keep_outputs = keep_outputs job.work_in_output = self.work_in_output job.adjust_cfg = self.adjust_cfg job.fragments = fragments job.step = self.step if self.num_threads: self.queue.put(job) else: self._single_builder.run_job(job) def run_build(self, delay_summary=False): """Run the build to completion Waits for all jobs to finish and optionally prints a summary. Call init_build() first to set up the jobs. Args: delay_summary (bool): True to skip printing the build summary at the end (caller will print it later) Returns: tuple: Tuple containing: - number of boards that failed to build - number of boards that issued warnings - list of thread exceptions raised """ if self.num_threads: term = threading.Thread(target=self.queue.join) term.daemon = True term.start() while term.is_alive(): term.join(100) # Wait until we have processed all output self.out_queue.join() if not self._opts.ide and not delay_summary: self.print_summary() return (self.fail, self._warned, self.thread_exceptions) def build_boards(self, commits, board_selected, keep_outputs, verbose, fragments, extra_count=0, delay_summary=False): """Build all commits for a list of boards Convenience method that calls init_build() then run_build(). Args: commits (list): List of commits to be build, each a Commit object board_selected (dict): Dict of selected boards, key is target name, value is Board object keep_outputs (bool): True to save build output files verbose (bool): Display build results as they are completed fragments (str): config fragments added to defconfig extra_count (int): Additional builds expected from external sources (e.g. distributed workers) to include in the progress total delay_summary (bool): True to skip printing the build summary at the end (caller will print it later) Returns: tuple: Tuple containing: - number of boards that failed to build - number of boards that issued warnings - list of thread exceptions raised """ self.init_build(commits, board_selected, keep_outputs, verbose, fragments, extra_count) return self.run_build(delay_summary) def print_summary(self): """Print the build summary line Shows total built, time taken, and any thread exceptions. """ self._result_handler.print_build_summary( self.count, self._already_done, self.kconfig_reconfig, self.start_time, self.thread_exceptions) |