| 1 |
# This Source Code Form is subject to the terms of the Mozilla Public |
| 2 |
# License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 |
# file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 4 |
|
| 5 |
|
| 6 |
import logging |
| 7 |
import os |
| 8 |
import pathlib |
| 9 |
import shutil |
| 10 |
import time |
| 11 |
from pathlib import Path |
| 12 |
|
| 13 |
import yaml |
| 14 |
from voluptuous import Optional |
| 15 |
|
| 16 |
from taskgraph.actions import render_actions_json |
| 17 |
from taskgraph.create import create_tasks |
| 18 |
from taskgraph.generator import TaskGraphGenerator |
| 19 |
from taskgraph.parameters import Parameters, get_version |
| 20 |
from taskgraph.taskgraph import TaskGraph |
| 21 |
from taskgraph.util import json |
| 22 |
from taskgraph.util.python_path import find_object |
| 23 |
from taskgraph.util.schema import Schema, validate_schema |
| 24 |
from taskgraph.util.vcs import Repository, get_repository |
| 25 |
from taskgraph.util.yaml import load_yaml |
| 26 |
|
| 27 |
logger = logging.getLogger(__name__) |
| 28 |
|
| 29 |
ARTIFACTS_DIR = Path("artifacts") |
| 30 |
|
| 31 |
|
| 32 |
# For each project, this gives a set of parameters specific to the project. |
| 33 |
# See `taskcluster/docs/parameters.rst` for information on parameters. |
| 34 |
PER_PROJECT_PARAMETERS = { |
| 35 |
# the default parameters are used for projects that do not match above. |
| 36 |
"default": { |
| 37 |
"target_tasks_method": "default", |
| 38 |
} |
| 39 |
} |
| 40 |
|
| 41 |
|
| 42 |
try_task_config_schema_v2 = Schema( |
| 43 |
{ |
| 44 |
Optional("parameters"): {str: object}, |
| 45 |
} |
| 46 |
) |
| 47 |
|
| 48 |
|
| 49 |
def full_task_graph_to_runnable_tasks(full_task_json): |
| 50 |
runnable_tasks = {} |
| 51 |
for label, node in full_task_json.items(): |
| 52 |
if not ("extra" in node["task"] and "treeherder" in node["task"]["extra"]): |
| 53 |
continue |
| 54 |
|
| 55 |
th = node["task"]["extra"]["treeherder"] |
| 56 |
runnable_tasks[label] = {"symbol": th["symbol"]} |
| 57 |
|
| 58 |
for i in ("groupName", "groupSymbol", "collection"): |
| 59 |
if i in th: |
| 60 |
runnable_tasks[label][i] = th[i] |
| 61 |
if th.get("machine", {}).get("platform"): |
| 62 |
runnable_tasks[label]["platform"] = th["machine"]["platform"] |
| 63 |
return runnable_tasks |
| 64 |
|
| 65 |
|
| 66 |
def taskgraph_decision(options, parameters=None): |
| 67 |
""" |
| 68 |
Run the decision task. This function implements `mach taskgraph decision`, |
| 69 |
and is responsible for |
| 70 |
|
| 71 |
* processing decision task command-line options into parameters |
| 72 |
* running task-graph generation exactly the same way the other `mach |
| 73 |
taskgraph` commands do |
| 74 |
* generating a set of artifacts to memorialize the graph |
| 75 |
* calling TaskCluster APIs to create the graph |
| 76 |
""" |
| 77 |
level = logging.INFO |
| 78 |
if options.get("verbose"): |
| 79 |
level = logging.DEBUG |
| 80 |
|
| 81 |
logging.root.setLevel(level) |
| 82 |
# Handlers must have an explicit level set for them to properly filter |
| 83 |
# messages from child loggers (such as the optimization log a few lines |
| 84 |
# down). |
| 85 |
for h in logging.root.handlers: |
| 86 |
h.setLevel(level) |
| 87 |
|
| 88 |
if not os.path.isdir(ARTIFACTS_DIR): |
| 89 |
os.mkdir(ARTIFACTS_DIR) |
| 90 |
|
| 91 |
# optimizations are difficult to debug after the fact, so we always |
| 92 |
# log them at DEBUG level, and write the log as a separate artifact |
| 93 |
opt_log = logging.getLogger("optimization") |
| 94 |
opt_log.setLevel(logging.DEBUG) |
| 95 |
opt_handler = logging.FileHandler(ARTIFACTS_DIR / "optimizations.log", mode="w") |
| 96 |
if logging.root.handlers: |
| 97 |
opt_handler.setFormatter(logging.root.handlers[0].formatter) |
| 98 |
opt_log.addHandler(opt_handler) |
| 99 |
|
| 100 |
parameters = parameters or ( |
| 101 |
lambda graph_config: get_decision_parameters(graph_config, options) |
| 102 |
) |
| 103 |
|
| 104 |
decision_task_id = os.environ["TASK_ID"] |
| 105 |
|
| 106 |
# create a TaskGraphGenerator instance |
| 107 |
tgg = TaskGraphGenerator( |
| 108 |
root_dir=options.get("root"), |
| 109 |
parameters=parameters, |
| 110 |
decision_task_id=decision_task_id, |
| 111 |
write_artifacts=True, |
| 112 |
) |
| 113 |
|
| 114 |
# write out the parameters used to generate this graph |
| 115 |
write_artifact("parameters.yml", dict(**tgg.parameters)) |
| 116 |
|
| 117 |
# write out the public/actions.json file |
| 118 |
write_artifact( |
| 119 |
"actions.json", |
| 120 |
render_actions_json(tgg.parameters, tgg.graph_config, decision_task_id), |
| 121 |
) |
| 122 |
|
| 123 |
# write out the full graph for reference |
| 124 |
full_task_json = tgg.full_task_graph.to_json() |
| 125 |
write_artifact("full-task-graph.json", full_task_json) |
| 126 |
|
| 127 |
# write out the public/runnable-jobs.json file |
| 128 |
write_artifact( |
| 129 |
"runnable-jobs.json", full_task_graph_to_runnable_tasks(full_task_json) |
| 130 |
) |
| 131 |
|
| 132 |
# this is just a test to check whether the from_json() function is working |
| 133 |
_, _ = TaskGraph.from_json(full_task_json) |
| 134 |
|
| 135 |
# write out the target task set to allow reproducing this as input |
| 136 |
write_artifact("target-tasks.json", list(tgg.target_task_set.tasks.keys())) |
| 137 |
|
| 138 |
# write out the optimized task graph to describe what will actually happen, |
| 139 |
# and the map of labels to taskids |
| 140 |
write_artifact("task-graph.json", tgg.morphed_task_graph.to_json()) |
| 141 |
write_artifact("label-to-taskid.json", tgg.label_to_taskid) |
| 142 |
|
| 143 |
# write out current run-task and fetch-content scripts |
| 144 |
RUN_TASK_DIR = pathlib.Path(__file__).parent / "run-task" |
| 145 |
shutil.copy2(RUN_TASK_DIR / "run-task", ARTIFACTS_DIR) |
| 146 |
shutil.copy2(RUN_TASK_DIR / "fetch-content", ARTIFACTS_DIR) |
| 147 |
|
| 148 |
# actually create the graph |
| 149 |
create_tasks( |
| 150 |
tgg.graph_config, |
| 151 |
tgg.morphed_task_graph, |
| 152 |
tgg.label_to_taskid, |
| 153 |
tgg.parameters, |
| 154 |
decision_task_id=decision_task_id, |
| 155 |
) |
| 156 |
|
| 157 |
|
| 158 |
def get_decision_parameters(graph_config, options): |
| 159 |
""" |
| 160 |
Load parameters from the command-line options for 'taskgraph decision'. |
| 161 |
This also applies per-project parameters, based on the given project. |
| 162 |
|
| 163 |
""" |
| 164 |
parameters = { |
| 165 |
n: options[n] |
| 166 |
for n in [ |
| 167 |
"base_repository", |
| 168 |
"base_ref", |
| 169 |
"base_rev", |
| 170 |
"head_repository", |
| 171 |
"head_rev", |
| 172 |
"head_ref", |
| 173 |
"head_tag", |
| 174 |
"project", |
| 175 |
"pushlog_id", |
| 176 |
"pushdate", |
| 177 |
"repository_type", |
| 178 |
"owner", |
| 179 |
"level", |
| 180 |
"target_tasks_method", |
| 181 |
"tasks_for", |
| 182 |
] |
| 183 |
if n in options |
| 184 |
} |
| 185 |
|
| 186 |
repo_path = os.getcwd() |
| 187 |
repo = get_repository(repo_path) |
| 188 |
try: |
| 189 |
commit_message = repo.get_commit_message() |
| 190 |
except UnicodeDecodeError: |
| 191 |
commit_message = "" |
| 192 |
|
| 193 |
parameters["base_ref"] = _determine_more_accurate_base_ref( |
| 194 |
repo, |
| 195 |
candidate_base_ref=options.get("base_ref"), |
| 196 |
head_ref=options.get("head_ref"), |
| 197 |
base_rev=options.get("base_rev"), |
| 198 |
) |
| 199 |
|
| 200 |
parameters["base_rev"] = _determine_more_accurate_base_rev( |
| 201 |
repo, |
| 202 |
base_ref=parameters["base_ref"], |
| 203 |
candidate_base_rev=options.get("base_rev"), |
| 204 |
head_rev=options.get("head_rev"), |
| 205 |
env_prefix=_get_env_prefix(graph_config), |
| 206 |
) |
| 207 |
|
| 208 |
# Define default filter list, as most configurations shouldn't need |
| 209 |
# custom filters. |
| 210 |
parameters["files_changed"] = repo.get_changed_files( |
| 211 |
rev=parameters["head_rev"], base_rev=parameters["base_rev"] |
| 212 |
) |
| 213 |
parameters["filters"] = [ |
| 214 |
"target_tasks_method", |
| 215 |
] |
| 216 |
parameters["optimize_strategies"] = None |
| 217 |
parameters["optimize_target_tasks"] = True |
| 218 |
parameters["existing_tasks"] = {} |
| 219 |
parameters["do_not_optimize"] = [] |
| 220 |
parameters["enable_always_target"] = True |
| 221 |
parameters["build_number"] = 1 |
| 222 |
parameters["version"] = get_version(repo_path) |
| 223 |
parameters["next_version"] = None |
| 224 |
|
| 225 |
# owner must be an email, but sometimes (e.g., for ffxbld) it is not, in which |
| 226 |
# case, fake it |
| 227 |
if "@" not in parameters["owner"]: |
| 228 |
parameters["owner"] += "@noreply.mozilla.org" |
| 229 |
|
| 230 |
# use the pushdate as build_date if given, else use current time |
| 231 |
parameters["build_date"] = parameters["pushdate"] or int(time.time()) |
| 232 |
# moz_build_date is the build identifier based on build_date |
| 233 |
parameters["moz_build_date"] = time.strftime( |
| 234 |
"%Y%m%d%H%M%S", time.gmtime(parameters["build_date"]) |
| 235 |
) |
| 236 |
|
| 237 |
project = parameters["project"] |
| 238 |
try: |
| 239 |
parameters.update(PER_PROJECT_PARAMETERS[project]) |
| 240 |
except KeyError: |
| 241 |
logger.warning( |
| 242 |
f"using default project parameters; add {project} to " |
| 243 |
f"PER_PROJECT_PARAMETERS in {__file__} to customize behavior " |
| 244 |
"for this project" |
| 245 |
) |
| 246 |
parameters.update(PER_PROJECT_PARAMETERS["default"]) |
| 247 |
|
| 248 |
# `target_tasks_method` has higher precedence than `project` parameters |
| 249 |
if options.get("target_tasks_method"): |
| 250 |
parameters["target_tasks_method"] = options["target_tasks_method"] |
| 251 |
|
| 252 |
# ..but can be overridden by the commit message: if it contains the special |
| 253 |
# string "DONTBUILD" and this is an on-push decision task, then use the |
| 254 |
# special 'nothing' target task method. |
| 255 |
if "DONTBUILD" in commit_message and ( |
| 256 |
options["tasks_for"] in ("hg-push", "github-push") |
| 257 |
): |
| 258 |
parameters["target_tasks_method"] = "nothing" |
| 259 |
|
| 260 |
if options.get("optimize_target_tasks") is not None: |
| 261 |
parameters["optimize_target_tasks"] = options["optimize_target_tasks"] |
| 262 |
|
| 263 |
if "decision-parameters" in graph_config["taskgraph"]: |
| 264 |
find_object(graph_config["taskgraph"]["decision-parameters"])( |
| 265 |
graph_config, parameters |
| 266 |
) |
| 267 |
|
| 268 |
if options.get("try_task_config_file"): |
| 269 |
task_config_file = os.path.abspath(options.get("try_task_config_file")) |
| 270 |
else: |
| 271 |
# if try_task_config.json is present, load it |
| 272 |
task_config_file = os.path.join(os.getcwd(), "try_task_config.json") |
| 273 |
|
| 274 |
# load try settings |
| 275 |
if ("try" in project and options["tasks_for"] == "hg-push") or options[ |
| 276 |
"tasks_for" |
| 277 |
] == "github-pull-request": |
| 278 |
set_try_config(parameters, task_config_file) |
| 279 |
|
| 280 |
result = Parameters(**parameters) |
| 281 |
result.check() |
| 282 |
return result |
| 283 |
|
| 284 |
|
| 285 |
def _determine_more_accurate_base_ref(repo, candidate_base_ref, head_ref, base_rev): |
| 286 |
base_ref = candidate_base_ref |
| 287 |
|
| 288 |
if not candidate_base_ref: |
| 289 |
base_ref = repo.default_branch |
| 290 |
elif candidate_base_ref == head_ref and base_rev == Repository.NULL_REVISION: |
| 291 |
logger.info( |
| 292 |
"base_ref and head_ref are identical but base_rev equals the null revision. " |
| 293 |
"This is a new branch but Github didn't identify its actual base." |
| 294 |
) |
| 295 |
base_ref = repo.default_branch |
| 296 |
|
| 297 |
if base_ref != candidate_base_ref: |
| 298 |
logger.info( |
| 299 |
f'base_ref has been reset from "{candidate_base_ref}" to "{base_ref}".' |
| 300 |
) |
| 301 |
|
| 302 |
return base_ref |
| 303 |
|
| 304 |
|
| 305 |
def _determine_more_accurate_base_rev( |
| 306 |
repo, base_ref, candidate_base_rev, head_rev, env_prefix |
| 307 |
): |
| 308 |
if not candidate_base_rev: |
| 309 |
logger.info("base_rev is not set.") |
| 310 |
base_ref_or_rev = base_ref |
| 311 |
elif candidate_base_rev == Repository.NULL_REVISION: |
| 312 |
logger.info("base_rev equals the null revision. This branch is a new one.") |
| 313 |
base_ref_or_rev = base_ref |
| 314 |
elif not repo.does_revision_exist_locally(candidate_base_rev): |
| 315 |
logger.warning( |
| 316 |
"base_rev does not exist locally. It is likely because the branch was force-pushed. " |
| 317 |
"taskgraph is not able to assess how many commits were changed and assumes it is only " |
| 318 |
f"the last one. Please set the {env_prefix.upper()}_BASE_REV environment variable " |
| 319 |
"in the decision task and provide `--base-rev` to taskgraph." |
| 320 |
) |
| 321 |
base_ref_or_rev = base_ref |
| 322 |
else: |
| 323 |
base_ref_or_rev = candidate_base_rev |
| 324 |
|
| 325 |
if base_ref_or_rev == base_ref: |
| 326 |
logger.info( |
| 327 |
f'Using base_ref "{base_ref}" to determine latest common revision...' |
| 328 |
) |
| 329 |
|
| 330 |
base_rev = repo.find_latest_common_revision(base_ref_or_rev, head_rev) |
| 331 |
if base_rev != candidate_base_rev: |
| 332 |
if base_ref_or_rev == candidate_base_rev: |
| 333 |
logger.info("base_rev is not an ancestor of head_rev.") |
| 334 |
|
| 335 |
logger.info( |
| 336 |
f'base_rev has been reset from "{candidate_base_rev}" to "{base_rev}".' |
| 337 |
) |
| 338 |
|
| 339 |
return base_rev |
| 340 |
|
| 341 |
|
| 342 |
def _get_env_prefix(graph_config): |
| 343 |
repo_keys = list(graph_config["taskgraph"].get("repositories", {}).keys()) |
| 344 |
return repo_keys[0] if repo_keys else "" |
| 345 |
|
| 346 |
|
| 347 |
def set_try_config(parameters, task_config_file): |
| 348 |
if os.path.isfile(task_config_file): |
| 349 |
logger.info(f"using try tasks from {task_config_file}") |
| 350 |
with open(task_config_file) as fh: |
| 351 |
task_config = json.load(fh) |
| 352 |
task_config_version = task_config.pop("version") |
| 353 |
if task_config_version == 2: |
| 354 |
validate_schema( |
| 355 |
try_task_config_schema_v2, |
| 356 |
task_config, |
| 357 |
"Invalid v2 `try_task_config.json`.", |
| 358 |
) |
| 359 |
parameters.update(task_config["parameters"]) |
| 360 |
return |
| 361 |
else: |
| 362 |
raise Exception( |
| 363 |
f"Unknown `try_task_config.json` version: {task_config_version}" |
| 364 |
) |
| 365 |
|
| 366 |
|
| 367 |
def write_artifact(filename, data): |
| 368 |
logger.info(f"writing artifact file `{filename}`") |
| 369 |
if not os.path.isdir(ARTIFACTS_DIR): |
| 370 |
os.mkdir(ARTIFACTS_DIR) |
| 371 |
path = ARTIFACTS_DIR / filename |
| 372 |
if filename.endswith(".yml"): |
| 373 |
with open(path, "w") as f: |
| 374 |
yaml.safe_dump(data, f, allow_unicode=True, default_flow_style=False) |
| 375 |
elif filename.endswith(".json"): |
| 376 |
with open(path, "w") as f: |
| 377 |
json.dump(data, f, sort_keys=True, indent=2) |
| 378 |
elif filename.endswith(".gz"): |
| 379 |
import gzip |
| 380 |
|
| 381 |
with gzip.open(path, "wb") as f: |
| 382 |
f.write(json.dumps(data)) # type: ignore |
| 383 |
else: |
| 384 |
raise TypeError(f"Don't know how to write to {filename}") |
| 385 |
|
| 386 |
|
| 387 |
def read_artifact(filename): |
| 388 |
path = ARTIFACTS_DIR / filename |
| 389 |
if filename.endswith(".yml"): |
| 390 |
return load_yaml(path, filename) |
| 391 |
elif filename.endswith(".json"): |
| 392 |
with open(path) as f: |
| 393 |
return json.load(f) |
| 394 |
elif filename.endswith(".gz"): |
| 395 |
import gzip |
| 396 |
|
| 397 |
with gzip.open(path, "rb") as f: |
| 398 |
return json.load(f) |
| 399 |
else: |
| 400 |
raise TypeError(f"Don't know how to read {filename}") |
| 401 |
|
| 402 |
|
| 403 |
def rename_artifact(src, dest): |
| 404 |
os.rename(ARTIFACTS_DIR / src, ARTIFACTS_DIR / dest) |