xref: /aosp_15_r20/external/grpc-grpc/tools/run_tests/task_runner.py (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1#!/usr/bin/env python3
2# Copyright 2016 gRPC authors.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#     http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15"""Runs selected gRPC test/build tasks."""
16
17from __future__ import print_function
18
19import argparse
20import multiprocessing
21import sys
22
23import artifacts.artifact_targets as artifact_targets
24import artifacts.distribtest_targets as distribtest_targets
25import artifacts.package_targets as package_targets
26import python_utils.jobset as jobset
27import python_utils.report_utils as report_utils
28
29_TARGETS = []
30_TARGETS += artifact_targets.targets()
31_TARGETS += distribtest_targets.targets()
32_TARGETS += package_targets.targets()
33
34
35def _create_build_map():
36    """Maps task names and labels to list of tasks to be built."""
37    target_build_map = dict([(target.name, [target]) for target in _TARGETS])
38    if len(_TARGETS) > len(list(target_build_map.keys())):
39        raise Exception("Target names need to be unique")
40
41    label_build_map = {}
42    label_build_map["all"] = [t for t in _TARGETS]  # to build all targets
43    for target in _TARGETS:
44        for label in target.labels:
45            if label in label_build_map:
46                label_build_map[label].append(target)
47            else:
48                label_build_map[label] = [target]
49
50    if set(target_build_map.keys()).intersection(list(label_build_map.keys())):
51        raise Exception("Target names need to be distinct from label names")
52    return dict(list(target_build_map.items()) + list(label_build_map.items()))
53
54
55_BUILD_MAP = _create_build_map()
56
57argp = argparse.ArgumentParser(description="Runs build/test targets.")
58argp.add_argument(
59    "-b",
60    "--build",
61    choices=sorted(_BUILD_MAP.keys()),
62    nargs="+",
63    default=["all"],
64    help="Target name or target label to build.",
65)
66argp.add_argument(
67    "-f",
68    "--filter",
69    choices=sorted(_BUILD_MAP.keys()),
70    nargs="+",
71    default=[],
72    help="Filter targets to build with AND semantics.",
73)
74argp.add_argument("-j", "--jobs", default=multiprocessing.cpu_count(), type=int)
75argp.add_argument(
76    "-x",
77    "--xml_report",
78    default="report_taskrunner_sponge_log.xml",
79    type=str,
80    help="Filename for the JUnit-compatible XML report",
81)
82argp.add_argument(
83    "--dry_run",
84    default=False,
85    action="store_const",
86    const=True,
87    help="Only print what would be run.",
88)
89argp.add_argument(
90    "--inner_jobs",
91    default=None,
92    type=int,
93    help=(
94        "Number of parallel jobs to use by each target. Passed as"
95        " build_jobspec(inner_jobs=N) to each target."
96    ),
97)
98
99args = argp.parse_args()
100
101# Figure out which targets to build
102targets = []
103for label in args.build:
104    targets += _BUILD_MAP[label]
105
106# Among targets selected by -b, filter out those that don't match the filter
107targets = [t for t in targets if all(f in t.labels for f in args.filter)]
108
109print("Will build %d targets:" % len(targets))
110for target in targets:
111    print("  %s, labels %s" % (target.name, target.labels))
112print()
113
114if args.dry_run:
115    print("--dry_run was used, exiting")
116    sys.exit(1)
117
118# Execute pre-build phase
119prebuild_jobs = []
120for target in targets:
121    prebuild_jobs += target.pre_build_jobspecs()
122if prebuild_jobs:
123    num_failures, _ = jobset.run(
124        prebuild_jobs, newline_on_success=True, maxjobs=args.jobs
125    )
126    if num_failures != 0:
127        jobset.message("FAILED", "Pre-build phase failed.", do_newline=True)
128        sys.exit(1)
129
130build_jobs = []
131for target in targets:
132    build_jobs.append(target.build_jobspec(inner_jobs=args.inner_jobs))
133if not build_jobs:
134    print("Nothing to build.")
135    sys.exit(1)
136
137jobset.message("START", "Building targets.", do_newline=True)
138num_failures, resultset = jobset.run(
139    build_jobs, newline_on_success=True, maxjobs=args.jobs
140)
141report_utils.render_junit_xml_report(
142    resultset, args.xml_report, suite_name="tasks"
143)
144if num_failures == 0:
145    jobset.message(
146        "SUCCESS", "All targets built successfully.", do_newline=True
147    )
148else:
149    jobset.message("FAILED", "Failed to build targets.", do_newline=True)
150    sys.exit(1)
151