Skip to content
Snippets Groups Projects
builder.py 56.9 KiB
Newer Older
  • Learn to ignore specific revisions
  • 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 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
            """Reset the results summary ready for use.
    
            Set up the base board list to be all those selected, and set the
            error lines to empty.
    
            Following this, calls to PrintResultSummary() will use this
            information to work out what has changed.
    
            Args:
                board_selected: Dict containing boards to summarise, keyed by
                    board.target
            """
            self._base_board_dict = {}
            for board in board_selected:
                self._base_board_dict[board] = Builder.Outcome(0, [], [], {})
            self._base_err_lines = []
    
        def PrintFuncSizeDetail(self, fname, old, new):
            grow, shrink, add, remove, up, down = 0, 0, 0, 0, 0, 0
            delta, common = [], {}
    
            for a in old:
                if a in new:
                    common[a] = 1
    
            for name in old:
                if name not in common:
                    remove += 1
                    down += old[name]
                    delta.append([-old[name], name])
    
            for name in new:
                if name not in common:
                    add += 1
                    up += new[name]
                    delta.append([new[name], name])
    
            for name in common:
                    diff = new.get(name, 0) - old.get(name, 0)
                    if diff > 0:
                        grow, up = grow + 1, up + diff
                    elif diff < 0:
                        shrink, down = shrink + 1, down - diff
                    delta.append([diff, name])
    
            delta.sort()
            delta.reverse()
    
            args = [add, -remove, grow, -shrink, up, -down, up - down]
            if max(args) == 0:
                return
            args = [self.ColourNum(x) for x in args]
            indent = ' ' * 15
            print ('%s%s: add: %s/%s, grow: %s/%s bytes: %s/%s (%s)' %
                   tuple([indent, self.col.Color(self.col.YELLOW, fname)] + args))
            print '%s  %-38s %7s %7s %+7s' % (indent, 'function', 'old', 'new',
                                            'delta')
            for diff, name in delta:
                if diff:
                    color = self.col.RED if diff > 0 else self.col.GREEN
                    msg = '%s  %-38s %7s %7s %+7d' % (indent, name,
                            old.get(name, '-'), new.get(name,'-'), diff)
                    print self.col.Color(color, msg)
    
    
        def PrintSizeDetail(self, target_list, show_bloat):
            """Show details size information for each board
    
            Args:
                target_list: List of targets, each a dict containing:
                        'target': Target name
                        'total_diff': Total difference in bytes across all areas
                        <part_name>: Difference for that part
                show_bloat: Show detail for each function
            """
            targets_by_diff = sorted(target_list, reverse=True,
            key=lambda x: x['_total_diff'])
            for result in targets_by_diff:
                printed_target = False
                for name in sorted(result):
                    diff = result[name]
                    if name.startswith('_'):
                        continue
                    if diff != 0:
                        color = self.col.RED if diff > 0 else self.col.GREEN
                    msg = ' %s %+d' % (name, diff)
                    if not printed_target:
                        print '%10s  %-15s:' % ('', result['_target']),
                        printed_target = True
                    print self.col.Color(color, msg),
                if printed_target:
                    print
                    if show_bloat:
                        target = result['_target']
                        outcome = result['_outcome']
                        base_outcome = self._base_board_dict[target]
                        for fname in outcome.func_sizes:
                            self.PrintFuncSizeDetail(fname,
                                                     base_outcome.func_sizes[fname],
                                                     outcome.func_sizes[fname])
    
    
        def PrintSizeSummary(self, board_selected, board_dict, show_detail,
                             show_bloat):
            """Print a summary of image sizes broken down by section.
    
            The summary takes the form of one line per architecture. The
            line contains deltas for each of the sections (+ means the section
            got bigger, - means smaller). The nunmbers are the average number
            of bytes that a board in this section increased by.
    
            For example:
               powerpc: (622 boards)   text -0.0
              arm: (285 boards)   text -0.0
              nds32: (3 boards)   text -8.0
    
            Args:
                board_selected: Dict containing boards to summarise, keyed by
                    board.target
                board_dict: Dict containing boards for which we built this
                    commit, keyed by board.target. The value is an Outcome object.
                show_detail: Show detail for each board
                show_bloat: Show detail for each function
            """
            arch_list = {}
            arch_count = {}
    
            # Calculate changes in size for different image parts
            # The previous sizes are in Board.sizes, for each board
            for target in board_dict:
                if target not in board_selected:
                    continue
                base_sizes = self._base_board_dict[target].sizes
                outcome = board_dict[target]
                sizes = outcome.sizes
    
                # Loop through the list of images, creating a dict of size
                # changes for each image/part. We end up with something like
                # {'target' : 'snapper9g45, 'data' : 5, 'u-boot-spl:text' : -4}
                # which means that U-Boot data increased by 5 bytes and SPL
                # text decreased by 4.
                err = {'_target' : target}
                for image in sizes:
                    if image in base_sizes:
                        base_image = base_sizes[image]
                        # Loop through the text, data, bss parts
                        for part in sorted(sizes[image]):
                            diff = sizes[image][part] - base_image[part]
                            col = None
                            if diff:
                                if image == 'u-boot':
                                    name = part
                                else:
                                    name = image + ':' + part
                                err[name] = diff
                arch = board_selected[target].arch
                if not arch in arch_count:
                    arch_count[arch] = 1
                else:
                    arch_count[arch] += 1
                if not sizes:
                    pass    # Only add to our list when we have some stats
                elif not arch in arch_list:
                    arch_list[arch] = [err]
                else:
                    arch_list[arch].append(err)
    
            # We now have a list of image size changes sorted by arch
            # Print out a summary of these
            for arch, target_list in arch_list.iteritems():
                # Get total difference for each type
                totals = {}
                for result in target_list:
                    total = 0
                    for name, diff in result.iteritems():
                        if name.startswith('_'):
                            continue
                        total += diff
                        if name in totals:
                            totals[name] += diff
                        else:
                            totals[name] = diff
                    result['_total_diff'] = total
                    result['_outcome'] = board_dict[result['_target']]
    
                count = len(target_list)
                printed_arch = False
                for name in sorted(totals):
                    diff = totals[name]
                    if diff:
                        # Display the average difference in this name for this
                        # architecture
                        avg_diff = float(diff) / count
                        color = self.col.RED if avg_diff > 0 else self.col.GREEN
                        msg = ' %s %+1.1f' % (name, avg_diff)
                        if not printed_arch:
                            print '%10s: (for %d/%d boards)' % (arch, count,
                                    arch_count[arch]),
                            printed_arch = True
                        print self.col.Color(color, msg),
    
                if printed_arch:
                    print
                    if show_detail:
                        self.PrintSizeDetail(target_list, show_bloat)
    
    
        def PrintResultSummary(self, board_selected, board_dict, err_lines,
                               show_sizes, show_detail, show_bloat):
            """Compare results with the base results and display delta.
    
            Only boards mentioned in board_selected will be considered. This
            function is intended to be called repeatedly with the results of
            each commit. It therefore shows a 'diff' between what it saw in
            the last call and what it sees now.
    
            Args:
                board_selected: Dict containing boards to summarise, keyed by
                    board.target
                board_dict: Dict containing boards for which we built this
                    commit, keyed by board.target. The value is an Outcome object.
                err_lines: A list of errors for this commit, or [] if there is
                    none, or we don't want to print errors
                show_sizes: Show image size deltas
                show_detail: Show detail for each board
                show_bloat: Show detail for each function
            """
            better = []     # List of boards fixed since last commit
            worse = []      # List of new broken boards since last commit
            new = []        # List of boards that didn't exist last time
            unknown = []    # List of boards that were not built
    
            for target in board_dict:
                if target not in board_selected:
                    continue
    
                # If the board was built last time, add its outcome to a list
                if target in self._base_board_dict:
                    base_outcome = self._base_board_dict[target].rc
                    outcome = board_dict[target]
                    if outcome.rc == OUTCOME_UNKNOWN:
                        unknown.append(target)
                    elif outcome.rc < base_outcome:
                        better.append(target)
                    elif outcome.rc > base_outcome:
                        worse.append(target)
                else:
                    new.append(target)
    
            # Get a list of errors that have appeared, and disappeared
            better_err = []
            worse_err = []
            for line in err_lines:
                if line not in self._base_err_lines:
                    worse_err.append('+' + line)
            for line in self._base_err_lines:
                if line not in err_lines:
                    better_err.append('-' + line)
    
            # Display results by arch
            if better or worse or unknown or new or worse_err or better_err:
                arch_list = {}
                self.AddOutcome(board_selected, arch_list, better, '',
                        self.col.GREEN)
                self.AddOutcome(board_selected, arch_list, worse, '+',
                        self.col.RED)
                self.AddOutcome(board_selected, arch_list, new, '*', self.col.BLUE)
                if self._show_unknown:
                    self.AddOutcome(board_selected, arch_list, unknown, '?',
                            self.col.MAGENTA)
                for arch, target_list in arch_list.iteritems():
                    print '%10s: %s' % (arch, target_list)
                if better_err:
                    print self.col.Color(self.col.GREEN, '\n'.join(better_err))
                if worse_err:
                    print self.col.Color(self.col.RED, '\n'.join(worse_err))
    
            if show_sizes:
                self.PrintSizeSummary(board_selected, board_dict, show_detail,
                                      show_bloat)
    
            # Save our updated information for the next call to this function
            self._base_board_dict = board_dict
            self._base_err_lines = err_lines
    
            # Get a list of boards that did not get built, if needed
            not_built = []
            for board in board_selected:
                if not board in board_dict:
                    not_built.append(board)
            if not_built:
                print "Boards not built (%d): %s" % (len(not_built),
                        ', '.join(not_built))
    
    
        def ShowSummary(self, commits, board_selected, show_errors, show_sizes,
                        show_detail, show_bloat):
            """Show a build summary for U-Boot for a given board list.
    
            Reset the result summary, then repeatedly call GetResultSummary on
            each commit's results, then display the differences we see.
    
            Args:
                commit: Commit objects to summarise
                board_selected: Dict containing boards to summarise
                show_errors: Show errors that occured
                show_sizes: Show size deltas
                show_detail: Show detail for each board
                show_bloat: Show detail for each function
            """
            self.commit_count = len(commits)
            self.commits = commits
            self.ResetResultSummary(board_selected)
    
            for commit_upto in range(0, self.commit_count, self._step):
                board_dict, err_lines = self.GetResultSummary(board_selected,
                        commit_upto, read_func_sizes=show_bloat)
                msg = '%02d: %s' % (commit_upto + 1, commits[commit_upto].subject)
                print self.col.Color(self.col.BLUE, msg)
                self.PrintResultSummary(board_selected, board_dict,
                        err_lines if show_errors else [], show_sizes, show_detail,
                        show_bloat)
    
    
        def SetupBuild(self, board_selected, commits):
            """Set up ready to start a build.
    
            Args:
                board_selected: Selected boards to build
                commits: Selected commits to build
            """
            # First work out how many commits we will build
            count = (len(commits) + self._step - 1) / self._step
            self.count = len(board_selected) * count
            self.upto = self.warned = self.fail = 0
            self._timestamps = collections.deque()
    
        def BuildBoardsForCommit(self, board_selected, keep_outputs):
            """Build all boards for a single commit"""
            self.SetupBuild(board_selected)
            self.count = len(board_selected)
            for brd in board_selected.itervalues():
                job = BuilderJob()
                job.board = brd
                job.commits = None
                job.keep_outputs = keep_outputs
                self.queue.put(brd)
    
            self.queue.join()
            self.out_queue.join()
            print
            self.ClearLine(0)
    
        def BuildCommits(self, commits, board_selected, show_errors, keep_outputs):
            """Build all boards for all commits (non-incremental)"""
            self.commit_count = len(commits)
    
            self.ResetResultSummary(board_selected)
            for self.commit_upto in range(self.commit_count):
                self.SelectCommit(commits[self.commit_upto])
                self.SelectOutputDir()
                Mkdir(self.output_dir)
    
                self.BuildBoardsForCommit(board_selected, keep_outputs)
                board_dict, err_lines = self.GetResultSummary()
                self.PrintResultSummary(board_selected, board_dict,
                    err_lines if show_errors else [])
    
            if self.already_done:
                print '%d builds already done' % self.already_done
    
        def GetThreadDir(self, thread_num):
            """Get the directory path to the working dir for a thread.
    
            Args:
                thread_num: Number of thread to check.
            """
            return os.path.join(self._working_dir, '%02d' % thread_num)
    
        def _PrepareThread(self, thread_num):
            """Prepare the working directory for a thread.
    
            This clones or fetches the repo into the thread's work directory.
    
            Args:
                thread_num: Thread number (0, 1, ...)
            """
            thread_dir = self.GetThreadDir(thread_num)
            Mkdir(thread_dir)
            git_dir = os.path.join(thread_dir, '.git')
    
            # Clone the repo if it doesn't already exist
            # TODO(sjg@chromium): Perhaps some git hackery to symlink instead, so
            # we have a private index but uses the origin repo's contents?
            if self.git_dir:
                src_dir = os.path.abspath(self.git_dir)
                if os.path.exists(git_dir):
                    gitutil.Fetch(git_dir, thread_dir)
                else:
                    print 'Cloning repo for thread %d' % thread_num
                    gitutil.Clone(src_dir, thread_dir)
    
        def _PrepareWorkingSpace(self, max_threads):
            """Prepare the working directory for use.
    
            Set up the git repo for each thread.
    
            Args:
                max_threads: Maximum number of threads we expect to need.
            """
            Mkdir(self._working_dir)
            for thread in range(max_threads):
                self._PrepareThread(thread)
    
        def _PrepareOutputSpace(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.
            """
            dir_list = []
            for commit_upto in range(self.commit_count):
                dir_list.append(self._GetOutputDir(commit_upto))
    
            for dirname in glob.glob(os.path.join(self.base_dir, '*')):
                if dirname not in dir_list:
                    shutil.rmtree(dirname)
    
        def BuildBoards(self, commits, board_selected, show_errors, keep_outputs):
            """Build all commits for a list of boards
    
            Args:
                commits: List of commits to be build, each a Commit object
                boards_selected: Dict of selected boards, key is target name,
                        value is Board object
                show_errors: True to show summarised error/warning info
                keep_outputs: True to save build output files
            """
            self.commit_count = len(commits)
            self.commits = commits
    
            self.ResetResultSummary(board_selected)
            Mkdir(self.base_dir)
            self._PrepareWorkingSpace(min(self.num_threads, len(board_selected)))
            self._PrepareOutputSpace()
            self.SetupBuild(board_selected, commits)
            self.ProcessResult(None)
    
            # Create jobs to build all commits for each board
            for brd in board_selected.itervalues():
                job = BuilderJob()
                job.board = brd
                job.commits = commits
                job.keep_outputs = keep_outputs
                job.step = self._step
                self.queue.put(job)
    
            # Wait until all jobs are started
            self.queue.join()
    
            # Wait until we have processed all output
            self.out_queue.join()
            print
            self.ClearLine(0)