| 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 |
import copy |
| 6 |
import logging |
| 7 |
import os |
| 8 |
from dataclasses import dataclass |
| 9 |
from typing import Callable, Dict, Optional, Union |
| 10 |
|
| 11 |
from . import filter_tasks |
| 12 |
from .config import GraphConfig, load_graph_config |
| 13 |
from .graph import Graph |
| 14 |
from .morph import morph |
| 15 |
from .optimize.base import optimize_task_graph |
| 16 |
from .parameters import Parameters, parameters_loader |
| 17 |
from .task import Task |
| 18 |
from .taskgraph import TaskGraph |
| 19 |
from .transforms.base import TransformConfig, TransformSequence |
| 20 |
from .util.python_path import find_object |
| 21 |
from .util.verify import verifications |
| 22 |
from .util.yaml import load_yaml |
| 23 |
|
| 24 |
logger = logging.getLogger(__name__) |
| 25 |
|
| 26 |
|
| 27 |
class KindNotFound(Exception): |
| 28 |
""" |
| 29 |
Raised when trying to load kind from a directory without a kind.yml. |
| 30 |
""" |
| 31 |
|
| 32 |
|
| 33 |
@dataclass(frozen=True) |
| 34 |
class Kind: |
| 35 |
name: str |
| 36 |
path: str |
| 37 |
config: Dict |
| 38 |
graph_config: GraphConfig |
| 39 |
|
| 40 |
def _get_loader(self): |
| 41 |
try: |
| 42 |
loader = self.config["loader"] |
| 43 |
except KeyError: |
| 44 |
loader = "taskgraph.loader.default:loader" |
| 45 |
return find_object(loader) |
| 46 |
|
| 47 |
def load_tasks(self, parameters, loaded_tasks, write_artifacts): |
| 48 |
loader = self._get_loader() |
| 49 |
config = copy.deepcopy(self.config) |
| 50 |
|
| 51 |
kind_dependencies = config.get("kind-dependencies", []) |
| 52 |
kind_dependencies_tasks = { |
| 53 |
task.label: task for task in loaded_tasks if task.kind in kind_dependencies |
| 54 |
} |
| 55 |
|
| 56 |
inputs = loader(self.name, self.path, config, parameters, loaded_tasks) |
| 57 |
|
| 58 |
transforms = TransformSequence() |
| 59 |
for xform_path in config["transforms"]: |
| 60 |
if ":" not in xform_path: |
| 61 |
xform_path = f"{xform_path}:transforms" |
| 62 |
|
| 63 |
transform = find_object(xform_path) |
| 64 |
transforms.add(transform) |
| 65 |
|
| 66 |
# perform the transformations on the loaded inputs |
| 67 |
trans_config = TransformConfig( |
| 68 |
self.name, |
| 69 |
self.path, |
| 70 |
config, |
| 71 |
parameters, |
| 72 |
kind_dependencies_tasks, |
| 73 |
self.graph_config, |
| 74 |
write_artifacts=write_artifacts, |
| 75 |
) |
| 76 |
tasks = [ |
| 77 |
Task( |
| 78 |
self.name, |
| 79 |
label=task_dict["label"], |
| 80 |
description=task_dict["description"], |
| 81 |
attributes=task_dict["attributes"], |
| 82 |
task=task_dict["task"], |
| 83 |
optimization=task_dict.get("optimization"), |
| 84 |
dependencies=task_dict.get("dependencies"), |
| 85 |
soft_dependencies=task_dict.get("soft-dependencies"), |
| 86 |
if_dependencies=task_dict.get("if-dependencies"), |
| 87 |
) |
| 88 |
for task_dict in transforms(trans_config, inputs) |
| 89 |
] |
| 90 |
return tasks |
| 91 |
|
| 92 |
@classmethod |
| 93 |
def load(cls, root_dir, graph_config, kind_name): |
| 94 |
path = os.path.join(root_dir, "kinds", kind_name) |
| 95 |
kind_yml = os.path.join(path, "kind.yml") |
| 96 |
if not os.path.exists(kind_yml): |
| 97 |
raise KindNotFound(kind_yml) |
| 98 |
|
| 99 |
logger.debug(f"loading kind `{kind_name}` from `{path}`") |
| 100 |
config = load_yaml(kind_yml) |
| 101 |
|
| 102 |
return cls(kind_name, path, config, graph_config) |
| 103 |
|
| 104 |
|
| 105 |
class TaskGraphGenerator: |
| 106 |
""" |
| 107 |
The central controller for taskgraph. This handles all phases of graph |
| 108 |
generation. The task is generated from all of the kinds defined in |
| 109 |
subdirectories of the generator's root directory. |
| 110 |
|
| 111 |
Access to the results of this generation, as well as intermediate values at |
| 112 |
various phases of generation, is available via properties. This encourages |
| 113 |
the provision of all generation inputs at instance construction time. |
| 114 |
""" |
| 115 |
|
| 116 |
# Task-graph generation is implemented as a Python generator that yields |
| 117 |
# each "phase" of generation. This allows some mach subcommands to short- |
| 118 |
# circuit generation of the entire graph by never completing the generator. |
| 119 |
|
| 120 |
def __init__( |
| 121 |
self, |
| 122 |
root_dir: Optional[str], |
| 123 |
parameters: Union[Parameters, Callable[[GraphConfig], Parameters]], |
| 124 |
decision_task_id: str = "DECISION-TASK", |
| 125 |
write_artifacts: bool = False, |
| 126 |
): |
| 127 |
""" |
| 128 |
@param root_dir: root directory containing the Taskgraph config.yml file |
| 129 |
@param parameters: parameters for this task-graph generation, or callable |
| 130 |
taking a `GraphConfig` and returning parameters |
| 131 |
@type parameters: Union[Parameters, Callable[[GraphConfig], Parameters]] |
| 132 |
""" |
| 133 |
if root_dir is None: |
| 134 |
root_dir = "taskcluster" |
| 135 |
self.root_dir = root_dir |
| 136 |
self._parameters = parameters |
| 137 |
self._decision_task_id = decision_task_id |
| 138 |
self._write_artifacts = write_artifacts |
| 139 |
|
| 140 |
# start the generator |
| 141 |
self._run = self._run() # type: ignore |
| 142 |
self._run_results = {} |
| 143 |
|
| 144 |
@property |
| 145 |
def parameters(self): |
| 146 |
""" |
| 147 |
The properties used for this graph. |
| 148 |
|
| 149 |
@type: Properties |
| 150 |
""" |
| 151 |
return self._run_until("parameters") |
| 152 |
|
| 153 |
@property |
| 154 |
def full_task_set(self): |
| 155 |
""" |
| 156 |
The full task set: all tasks defined by any kind (a graph without edges) |
| 157 |
|
| 158 |
@type: TaskGraph |
| 159 |
""" |
| 160 |
return self._run_until("full_task_set") |
| 161 |
|
| 162 |
@property |
| 163 |
def full_task_graph(self): |
| 164 |
""" |
| 165 |
The full task graph: the full task set, with edges representing |
| 166 |
dependencies. |
| 167 |
|
| 168 |
@type: TaskGraph |
| 169 |
""" |
| 170 |
return self._run_until("full_task_graph") |
| 171 |
|
| 172 |
@property |
| 173 |
def target_task_set(self): |
| 174 |
""" |
| 175 |
The set of targeted tasks (a graph without edges) |
| 176 |
|
| 177 |
@type: TaskGraph |
| 178 |
""" |
| 179 |
return self._run_until("target_task_set") |
| 180 |
|
| 181 |
@property |
| 182 |
def target_task_graph(self): |
| 183 |
""" |
| 184 |
The set of targeted tasks and all of their dependencies |
| 185 |
|
| 186 |
@type: TaskGraph |
| 187 |
""" |
| 188 |
return self._run_until("target_task_graph") |
| 189 |
|
| 190 |
@property |
| 191 |
def optimized_task_graph(self): |
| 192 |
""" |
| 193 |
The set of targeted tasks and all of their dependencies; tasks that |
| 194 |
have been optimized out are either omitted or replaced with a Task |
| 195 |
instance containing only a task_id. |
| 196 |
|
| 197 |
@type: TaskGraph |
| 198 |
""" |
| 199 |
return self._run_until("optimized_task_graph") |
| 200 |
|
| 201 |
@property |
| 202 |
def label_to_taskid(self): |
| 203 |
""" |
| 204 |
A dictionary mapping task label to assigned taskId. This property helps |
| 205 |
in interpreting `optimized_task_graph`. |
| 206 |
|
| 207 |
@type: dictionary |
| 208 |
""" |
| 209 |
return self._run_until("label_to_taskid") |
| 210 |
|
| 211 |
@property |
| 212 |
def morphed_task_graph(self): |
| 213 |
""" |
| 214 |
The optimized task graph, with any subsequent morphs applied. This graph |
| 215 |
will have the same meaning as the optimized task graph, but be in a form |
| 216 |
more palatable to TaskCluster. |
| 217 |
|
| 218 |
@type: TaskGraph |
| 219 |
""" |
| 220 |
return self._run_until("morphed_task_graph") |
| 221 |
|
| 222 |
@property |
| 223 |
def graph_config(self): |
| 224 |
""" |
| 225 |
The configuration for this graph. |
| 226 |
|
| 227 |
@type: TaskGraph |
| 228 |
""" |
| 229 |
return self._run_until("graph_config") |
| 230 |
|
| 231 |
def _load_kinds(self, graph_config, target_kinds=None): |
| 232 |
if target_kinds: |
| 233 |
# docker-image is an implicit dependency that never appears in |
| 234 |
# kind-dependencies. |
| 235 |
queue = target_kinds + ["docker-image"] |
| 236 |
seen_kinds = set() |
| 237 |
while queue: |
| 238 |
kind_name = queue.pop() |
| 239 |
if kind_name in seen_kinds: |
| 240 |
continue |
| 241 |
seen_kinds.add(kind_name) |
| 242 |
kind = Kind.load(self.root_dir, graph_config, kind_name) |
| 243 |
yield kind |
| 244 |
queue.extend(kind.config.get("kind-dependencies", [])) |
| 245 |
else: |
| 246 |
for kind_name in os.listdir(os.path.join(self.root_dir, "kinds")): |
| 247 |
try: |
| 248 |
yield Kind.load(self.root_dir, graph_config, kind_name) |
| 249 |
except KindNotFound: |
| 250 |
continue |
| 251 |
|
| 252 |
def _run(self): |
| 253 |
logger.info("Loading graph configuration.") |
| 254 |
graph_config = load_graph_config(self.root_dir) |
| 255 |
|
| 256 |
yield ("graph_config", graph_config) |
| 257 |
|
| 258 |
graph_config.register() |
| 259 |
|
| 260 |
# Initial verifications that don't depend on any generation state. |
| 261 |
verifications("initial") |
| 262 |
|
| 263 |
if callable(self._parameters): |
| 264 |
parameters = self._parameters(graph_config) |
| 265 |
else: |
| 266 |
parameters = self._parameters |
| 267 |
|
| 268 |
logger.info(f"Using {parameters}") |
| 269 |
logger.debug(f"Dumping parameters:\n{repr(parameters)}") |
| 270 |
|
| 271 |
filters = parameters.get("filters", []) |
| 272 |
if not filters: |
| 273 |
# Default to target_tasks_method if none specified. |
| 274 |
filters.append("target_tasks_method") |
| 275 |
filters = [filter_tasks.filter_task_functions[f] for f in filters] |
| 276 |
|
| 277 |
yield self.verify("parameters", parameters) |
| 278 |
|
| 279 |
logger.info("Loading kinds") |
| 280 |
# put the kinds into a graph and sort topologically so that kinds are loaded |
| 281 |
# in post-order |
| 282 |
target_kinds = sorted(parameters.get("target-kinds", [])) |
| 283 |
if target_kinds: |
| 284 |
logger.info( |
| 285 |
"Limiting kinds to following kinds and dependencies: {}".format( |
| 286 |
", ".join(target_kinds) |
| 287 |
) |
| 288 |
) |
| 289 |
kinds = { |
| 290 |
kind.name: kind for kind in self._load_kinds(graph_config, target_kinds) |
| 291 |
} |
| 292 |
verifications("kinds", kinds) |
| 293 |
|
| 294 |
edges = set() |
| 295 |
for kind in kinds.values(): |
| 296 |
for dep in kind.config.get("kind-dependencies", []): |
| 297 |
edges.add((kind.name, dep, "kind-dependency")) |
| 298 |
kind_graph = Graph(frozenset(kinds), frozenset(edges)) |
| 299 |
|
| 300 |
if target_kinds: |
| 301 |
kind_graph = kind_graph.transitive_closure( |
| 302 |
set(target_kinds) | {"docker-image"} |
| 303 |
) |
| 304 |
|
| 305 |
logger.info("Generating full task set") |
| 306 |
all_tasks = {} |
| 307 |
for kind_name in kind_graph.visit_postorder(): |
| 308 |
logger.debug(f"Loading tasks for kind {kind_name}") |
| 309 |
kind = kinds[kind_name] |
| 310 |
try: |
| 311 |
new_tasks = kind.load_tasks( |
| 312 |
parameters, |
| 313 |
list(all_tasks.values()), |
| 314 |
self._write_artifacts, |
| 315 |
) |
| 316 |
except Exception: |
| 317 |
logger.exception(f"Error loading tasks for kind {kind_name}:") |
| 318 |
raise |
| 319 |
for task in new_tasks: |
| 320 |
if task.label in all_tasks: |
| 321 |
raise Exception("duplicate tasks with label " + task.label) |
| 322 |
all_tasks[task.label] = task |
| 323 |
logger.info(f"Generated {len(new_tasks)} tasks for kind {kind_name}") |
| 324 |
full_task_set = TaskGraph(all_tasks, Graph(frozenset(all_tasks), frozenset())) |
| 325 |
yield self.verify("full_task_set", full_task_set, graph_config, parameters) |
| 326 |
|
| 327 |
logger.info("Generating full task graph") |
| 328 |
edges = set() |
| 329 |
for t in full_task_set: |
| 330 |
for depname, dep in t.dependencies.items(): |
| 331 |
if dep not in all_tasks.keys(): |
| 332 |
raise Exception( |
| 333 |
f"Task '{t.label}' lists a dependency that does not exist: '{dep}'" |
| 334 |
) |
| 335 |
edges.add((t.label, dep, depname)) |
| 336 |
|
| 337 |
full_task_graph = TaskGraph( |
| 338 |
all_tasks, Graph(frozenset(full_task_set.graph.nodes), frozenset(edges)) |
| 339 |
) |
| 340 |
logger.info( |
| 341 |
f"Full task graph contains {len(full_task_set.graph.nodes)} tasks and {len(edges)} dependencies" |
| 342 |
) |
| 343 |
yield self.verify("full_task_graph", full_task_graph, graph_config, parameters) |
| 344 |
|
| 345 |
logger.info("Generating target task set") |
| 346 |
target_task_set = TaskGraph( |
| 347 |
dict(all_tasks), |
| 348 |
Graph(frozenset(all_tasks.keys()), frozenset()), |
| 349 |
) |
| 350 |
for fltr in filters: |
| 351 |
old_len = len(target_task_set.graph.nodes) |
| 352 |
target_tasks = set(fltr(target_task_set, parameters, graph_config)) |
| 353 |
target_task_set = TaskGraph( |
| 354 |
{l: all_tasks[l] for l in target_tasks}, |
| 355 |
Graph(frozenset(target_tasks), frozenset()), |
| 356 |
) |
| 357 |
logger.info( |
| 358 |
f"Filter {fltr.__name__} pruned {old_len - len(target_tasks)} tasks ({len(target_tasks)} remain)" |
| 359 |
) |
| 360 |
|
| 361 |
yield self.verify("target_task_set", target_task_set, graph_config, parameters) |
| 362 |
|
| 363 |
logger.info("Generating target task graph") |
| 364 |
# include all tasks with `always_target` set |
| 365 |
if parameters["enable_always_target"]: |
| 366 |
always_target_tasks = { |
| 367 |
t.label |
| 368 |
for t in full_task_graph.tasks.values() # type: ignore |
| 369 |
if t.attributes.get("always_target") |
| 370 |
if parameters["enable_always_target"] is True |
| 371 |
or t.kind in parameters["enable_always_target"] |
| 372 |
} |
| 373 |
else: |
| 374 |
always_target_tasks = set() |
| 375 |
logger.info( |
| 376 |
f"Adding {len(always_target_tasks) - len(always_target_tasks & target_tasks)} tasks with `always_target` attribute" # type: ignore |
| 377 |
) |
| 378 |
requested_tasks = target_tasks | always_target_tasks # type: ignore |
| 379 |
target_graph = full_task_graph.graph.transitive_closure(requested_tasks) |
| 380 |
target_task_graph = TaskGraph( |
| 381 |
{l: all_tasks[l] for l in target_graph.nodes}, |
| 382 |
target_graph, # type: ignore |
| 383 |
) |
| 384 |
yield self.verify( |
| 385 |
"target_task_graph", target_task_graph, graph_config, parameters |
| 386 |
) |
| 387 |
|
| 388 |
logger.info("Generating optimized task graph") |
| 389 |
existing_tasks = parameters.get("existing_tasks") |
| 390 |
do_not_optimize = set(parameters.get("do_not_optimize", [])) |
| 391 |
if not parameters.get("optimize_target_tasks", True): |
| 392 |
do_not_optimize = set(target_task_set.graph.nodes).union(do_not_optimize) |
| 393 |
|
| 394 |
# this is used for testing experimental optimization strategies |
| 395 |
strategies = os.environ.get( |
| 396 |
"TASKGRAPH_OPTIMIZE_STRATEGIES", parameters.get("optimize_strategies") |
| 397 |
) |
| 398 |
if strategies: |
| 399 |
strategies = find_object(strategies) |
| 400 |
|
| 401 |
optimized_task_graph, label_to_taskid = optimize_task_graph( |
| 402 |
target_task_graph, |
| 403 |
requested_tasks, |
| 404 |
parameters, |
| 405 |
do_not_optimize, |
| 406 |
self._decision_task_id, |
| 407 |
existing_tasks=existing_tasks, |
| 408 |
strategy_override=strategies, |
| 409 |
) |
| 410 |
|
| 411 |
yield self.verify( |
| 412 |
"optimized_task_graph", optimized_task_graph, graph_config, parameters |
| 413 |
) |
| 414 |
|
| 415 |
morphed_task_graph, label_to_taskid = morph( |
| 416 |
optimized_task_graph, label_to_taskid, parameters, graph_config |
| 417 |
) |
| 418 |
|
| 419 |
yield "label_to_taskid", label_to_taskid |
| 420 |
yield self.verify( |
| 421 |
"morphed_task_graph", morphed_task_graph, graph_config, parameters |
| 422 |
) |
| 423 |
|
| 424 |
def _run_until(self, name): |
| 425 |
while name not in self._run_results: |
| 426 |
try: |
| 427 |
k, v = next(self._run) # type: ignore |
| 428 |
except StopIteration: |
| 429 |
raise AttributeError(f"No such run result {name}") |
| 430 |
self._run_results[k] = v |
| 431 |
return self._run_results[name] |
| 432 |
|
| 433 |
def verify(self, name, obj, *args, **kwargs): |
| 434 |
verifications(name, obj, *args, **kwargs) |
| 435 |
return name, obj |
| 436 |
|
| 437 |
|
| 438 |
def load_tasks_for_kind(parameters, kind, root_dir=None): |
| 439 |
""" |
| 440 |
Get all the tasks of a given kind. |
| 441 |
|
| 442 |
This function is designed to be called from outside of taskgraph. |
| 443 |
""" |
| 444 |
# make parameters read-write |
| 445 |
parameters = dict(parameters) |
| 446 |
parameters["target-kinds"] = [kind] |
| 447 |
parameters = parameters_loader(spec=None, strict=False, overrides=parameters) |
| 448 |
tgg = TaskGraphGenerator(root_dir=root_dir, parameters=parameters) |
| 449 |
return { |
| 450 |
task.task["metadata"]["name"]: task |
| 451 |
for task in tgg.full_task_set |
| 452 |
if task.kind == kind |
| 453 |
} |