Debian Codegraph @

third_party/python/taskcluster_taskgraph/taskgraph/main.py

raw
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 argparse
6 import atexit
7 import logging
8 import os
9 import re
10 import shutil
11 import subprocess
12 import sys
13 import tempfile
14 import traceback
15 from collections import namedtuple
16 from concurrent.futures import ProcessPoolExecutor, as_completed
17 from pathlib import Path
18 from textwrap import dedent
19 from typing import Any, List
20 from urllib.parse import urlparse
21
22 import appdirs
23 import yaml
24
25 Command = namedtuple("Command", ["func", "args", "kwargs", "defaults"])
26 commands = {}
27
28
29 def command(*args, **kwargs):
30 defaults = kwargs.pop("defaults", {})
31
32 def decorator(func):
33 commands[args[0]] = Command(func, args, kwargs, defaults)
34 return func
35
36 return decorator
37
38
39 def argument(*args, **kwargs):
40 def decorator(func):
41 if not hasattr(func, "args"):
42 func.args = []
43 func.args.append((args, kwargs))
44 return func
45
46 return decorator
47
48
49 def format_taskgraph_labels(taskgraph):
50 return "\n".join(
51 sorted(
52 taskgraph.tasks[index].label for index in taskgraph.graph.visit_postorder()
53 )
54 )
55
56
57 def format_taskgraph_json(taskgraph):
58 from taskgraph.util import json
59
60 return json.dumps(taskgraph.to_json(), sort_keys=True, indent=2)
61
62
63 def format_taskgraph_yaml(taskgraph):
64 return yaml.safe_dump(taskgraph.to_json(), default_flow_style=False)
65
66
67 def get_filtered_taskgraph(taskgraph, tasksregex, exclude_keys):
68 """
69 Filter all the tasks on basis of a regular expression
70 and returns a new TaskGraph object
71 """
72 from taskgraph.graph import Graph
73 from taskgraph.task import Task
74 from taskgraph.taskgraph import TaskGraph
75
76 if tasksregex:
77 named_links_dict = taskgraph.graph.named_links_dict()
78 filteredtasks = {}
79 filterededges = set()
80 regexprogram = re.compile(tasksregex)
81
82 for key in taskgraph.graph.visit_postorder():
83 task = taskgraph.tasks[key]
84 if regexprogram.match(task.label):
85 filteredtasks[key] = task
86 for depname, dep in named_links_dict[key].items():
87 if regexprogram.match(dep):
88 filterededges.add((key, dep, depname))
89
90 taskgraph = TaskGraph(
91 filteredtasks, Graph(frozenset(filteredtasks), frozenset(filterededges))
92 )
93
94 if exclude_keys:
95 for label, task in taskgraph.tasks.items():
96 task = task.to_json()
97 for key in exclude_keys:
98 obj = task
99 attrs = key.split(".")
100 while obj and attrs[0] in obj:
101 if len(attrs) == 1:
102 del obj[attrs[0]]
103 break
104 obj = obj[attrs[0]]
105 attrs = attrs[1:]
106 taskgraph.tasks[label] = Task.from_json(task)
107
108 return taskgraph
109
110
111 FORMAT_METHODS = {
112 "labels": format_taskgraph_labels,
113 "json": format_taskgraph_json,
114 "yaml": format_taskgraph_yaml,
115 }
116
117
118 def get_taskgraph_generator(root, parameters):
119 """Helper function to make testing a little easier."""
120 from taskgraph.generator import TaskGraphGenerator
121
122 return TaskGraphGenerator(root_dir=root, parameters=parameters)
123
124
125 def format_taskgraph(options, parameters, overrides, logfile=None):
126 import taskgraph
127 from taskgraph.parameters import parameters_loader
128
129 if logfile:
130 handler = logging.FileHandler(logfile, mode="w")
131 if logging.root.handlers:
132 oldhandler = logging.root.handlers[-1]
133 logging.root.removeHandler(oldhandler)
134 handler.setFormatter(oldhandler.formatter)
135 logging.root.addHandler(handler)
136
137 if options["fast"]:
138 taskgraph.fast = True
139
140 if isinstance(parameters, str):
141 parameters = parameters_loader(
142 parameters,
143 overrides=overrides,
144 strict=False,
145 )
146
147 tgg = get_taskgraph_generator(options.get("root"), parameters)
148
149 tg = getattr(tgg, options["graph_attr"])
150 tg = get_filtered_taskgraph(tg, options["tasks_regex"], options["exclude_keys"])
151 format_method = FORMAT_METHODS[options["format"] or "labels"]
152 return format_method(tg)
153
154
155 def dump_output(out, path=None, params_spec=None):
156 from taskgraph.parameters import Parameters
157
158 params_name = Parameters.format_spec(params_spec)
159 fh = None
160 if path:
161 # Substitute params name into file path if necessary
162 if params_spec and "{params}" not in path:
163 name, ext = os.path.splitext(path)
164 name += "_{params}"
165 path = name + ext
166
167 path = path.format(params=params_name)
168 fh = open(path, "w")
169 else:
170 print(
171 f"Dumping result with parameters from {params_name}:",
172 file=sys.stderr,
173 )
174 print(out + "\n", file=fh)
175
176
177 def generate_taskgraph(options, parameters, overrides, logdir):
178 from taskgraph.parameters import Parameters
179
180 def logfile(spec):
181 """Determine logfile given a parameters specification."""
182 if logdir is None:
183 return None
184 return os.path.join(
185 logdir,
186 "{}_{}.log".format(options["graph_attr"], Parameters.format_spec(spec)),
187 )
188
189 # Don't bother using futures if there's only one parameter. This can make
190 # tracebacks a little more readable and avoids additional process overhead.
191 if len(parameters) == 1:
192 spec = parameters[0]
193 out = format_taskgraph(options, spec, overrides, logfile(spec))
194 dump_output(out, options["output_file"])
195 return 0
196
197 futures = {}
198 with ProcessPoolExecutor(max_workers=options["max_workers"]) as executor:
199 for spec in parameters:
200 f = executor.submit(
201 format_taskgraph, options, spec, overrides, logfile(spec)
202 )
203 futures[f] = spec
204
205 returncode = 0
206 for future in as_completed(futures):
207 output_file = options["output_file"]
208 spec = futures[future]
209 e = future.exception()
210 if e:
211 returncode = 1
212 out = "".join(traceback.format_exception(type(e), e, e.__traceback__))
213 if options["diff"]:
214 # Dump to console so we don't accidentally diff the tracebacks.
215 output_file = None
216 else:
217 out = future.result()
218
219 dump_output(
220 out,
221 path=output_file,
222 params_spec=spec if len(parameters) > 1 else None,
223 )
224
225 return returncode
226
227
228 @command(
229 "tasks",
230 help="Show the full task set in the task graph. The full task set includes all tasks defined by any kind, without edges (dependencies) between them.",
231 defaults={"graph_attr": "full_task_set"},
232 )
233 @command(
234 "full",
235 help="Show the full task graph. The full task graph consists of the full task set, with edges (dependencies) between tasks.",
236 defaults={"graph_attr": "full_task_graph"},
237 )
238 @command(
239 "target",
240 help="Show the target task set in the task graph. The target task set includes the tasks which have indicated they should be run, without edges (dependencies) between them.",
241 defaults={"graph_attr": "target_task_set"},
242 )
243 @command(
244 "target-graph",
245 help="Show the target task graph. The target task graph consists of the target task set, with edges (dependencies) between tasks.",
246 defaults={"graph_attr": "target_task_graph"},
247 )
248 @command(
249 "optimized",
250 help="Show the optimized task graph, which is the target task set with tasks optimized out (filtered, omitted, or replaced) and edges representing dependencies.",
251 defaults={"graph_attr": "optimized_task_graph"},
252 )
253 @command(
254 "morphed",
255 help="Show the morphed graph, which is the optimized task graph with additional morphs applied. It retains the same meaning as the optimized task graph but in a form more palatable to TaskCluster.",
256 defaults={"graph_attr": "morphed_task_graph"},
257 )
258 @argument("--root", "-r", help="root of the taskgraph definition relative to topsrcdir")
259 @argument("--quiet", "-q", action="store_true", help="suppress all logging output")
260 @argument(
261 "--verbose", "-v", action="store_true", help="include debug-level logging output"
262 )
263 @argument(
264 "--json",
265 "-J",
266 action="store_const",
267 dest="format",
268 const="json",
269 help="Output task graph as a JSON object",
270 )
271 @argument(
272 "--yaml",
273 "-Y",
274 action="store_const",
275 dest="format",
276 const="yaml",
277 help="Output task graph as a YAML object",
278 )
279 @argument(
280 "--labels",
281 "-L",
282 action="store_const",
283 dest="format",
284 const="labels",
285 help="Output the label for each task in the task graph (default)",
286 )
287 @argument(
288 "--parameters",
289 "-p",
290 default=None,
291 action="append",
292 help="Parameters to use for the generation. Can be a path to file (.yml or "
293 ".json; see `taskcluster/docs/parameters.rst`), a directory (containing "
294 "parameters files), a url, of the form `project=mozilla-central` to download "
295 "latest parameters file for the specified project from CI, or of the form "
296 "`task-id=<decision task id>` to download parameters from the specified "
297 "decision task. Can be specified multiple times, in which case multiple "
298 "generations will happen from the same invocation (one per parameters "
299 "specified).",
300 )
301 @argument(
302 "--force-local-files-changed",
303 default=False,
304 action="store_true",
305 help="Compute the 'files-changed' parameter from local version control, "
306 "even when explicitly using a parameter set that already has it defined. "
307 "Note that this is already the default behaviour when no parameters are "
308 "specified.",
309 )
310 @argument(
311 "--no-optimize",
312 dest="optimize",
313 action="store_false",
314 default="true",
315 help="do not remove tasks from the graph that are found in the "
316 "index (a.k.a. optimize the graph)",
317 )
318 @argument(
319 "-o",
320 "--output-file",
321 default=None,
322 help="file path to store generated output.",
323 )
324 @argument(
325 "--tasks-regex",
326 "--tasks",
327 default=None,
328 help="only return tasks with labels matching this regular expression.",
329 )
330 @argument(
331 "--exclude-key",
332 default=None,
333 dest="exclude_keys",
334 action="append",
335 help="Exclude the specified key (using dot notation) from the final result. "
336 "This is mainly useful with '--diff' to filter out expected differences. Can be "
337 "used multiple times.",
338 )
339 @argument(
340 "-k",
341 "--target-kind",
342 dest="target_kinds",
343 action="append",
344 default=[],
345 help="only return tasks that are of the given kind, or their dependencies.",
346 )
347 @argument(
348 "-F",
349 "--fast",
350 default=False,
351 action="store_true",
352 help="enable fast task generation for local debugging.",
353 )
354 @argument(
355 "--diff",
356 const="default",
357 nargs="?",
358 default=None,
359 help="Generate and diff the current taskgraph against another revision. "
360 "Without args the base revision will be used. A revision specifier such as "
361 "the hash or `.~1` (hg) or `HEAD~1` (git) can be used as well.",
362 )
363 @argument(
364 "-j",
365 "--max-workers",
366 dest="max_workers",
367 default=None,
368 type=int,
369 help="The maximum number of workers to use for parallel operations such as"
370 "when multiple parameters files are passed.",
371 )
372 def show_taskgraph(options):
373 from taskgraph.parameters import Parameters, parameters_loader
374 from taskgraph.util.vcs import get_repository
375
376 if options.pop("verbose", False):
377 logging.root.setLevel(logging.DEBUG)
378
379 repo = None
380 cur_rev = None
381 diffdir = None
382 output_file = options["output_file"]
383
384 if options["diff"] or options["force_local_files_changed"]:
385 repo = get_repository(os.getcwd())
386
387 if options["diff"]:
388 assert repo is not None
389 if not repo.working_directory_clean():
390 print(
391 "abort: can't diff taskgraph with dirty working directory",
392 file=sys.stderr,
393 )
394 return 1
395
396 # We want to return the working directory to the current state
397 # as best we can after we're done. In all known cases, using
398 # branch or bookmark (which are both available on the VCS object)
399 # as `branch` is preferable to a specific revision.
400 cur_rev = repo.branch or repo.head_rev[:12]
401 cur_rev_file = cur_rev.replace("/", "_")
402
403 diffdir = tempfile.mkdtemp()
404 atexit.register(
405 shutil.rmtree, diffdir
406 ) # make sure the directory gets cleaned up
407 options["output_file"] = os.path.join(
408 diffdir, f"{options['graph_attr']}_{cur_rev_file}"
409 )
410 print(f"Generating {options['graph_attr']} @ {cur_rev}", file=sys.stderr)
411
412 overrides = {
413 "target-kinds": options.get("target_kinds"),
414 }
415 parameters: List[Any[str, Parameters]] = options.pop("parameters")
416 if not parameters:
417 parameters = [
418 parameters_loader(None, strict=False, overrides=overrides)
419 ] # will use default values
420
421 # This is the default behaviour anyway, so no need to re-compute.
422 options["force_local_files_changed"] = False
423
424 elif options["force_local_files_changed"]:
425 assert repo is not None
426 overrides["files-changed"] = sorted(repo.get_changed_files("AM"))
427
428 for param in parameters[:]:
429 if isinstance(param, str) and os.path.isdir(param):
430 parameters.remove(param)
431 parameters.extend(
432 [
433 p.as_posix()
434 for p in Path(param).iterdir()
435 if p.suffix in (".yml", ".json")
436 ]
437 )
438
439 logdir = None
440 if len(parameters) > 1:
441 # Log to separate files for each process instead of stderr to
442 # avoid interleaving.
443 basename = os.path.basename(os.getcwd())
444 logdir = os.path.join(appdirs.user_log_dir("taskgraph"), basename)
445 if not os.path.isdir(logdir):
446 os.makedirs(logdir)
447 else:
448 # Only setup logging if we have a single parameter spec. Otherwise
449 # logging will go to files. This is also used as a hook for Gecko
450 # to setup its `mach` based logging.
451 setup_logging()
452
453 ret = generate_taskgraph(options, parameters, overrides, logdir)
454
455 if options["diff"]:
456 assert diffdir is not None
457 assert repo is not None
458
459 # Reload taskgraph modules to pick up changes and clear global state.
460 for mod in sys.modules.copy():
461 if mod != __name__ and mod.split(".", 1)[0].endswith("taskgraph"):
462 del sys.modules[mod]
463
464 if options["diff"] == "default":
465 base_rev = repo.base_rev
466 else:
467 base_rev = options["diff"]
468 base_rev_file = base_rev.replace("/", "_")
469
470 try:
471 repo.update(base_rev)
472 base_rev = repo.head_rev[:12]
473 options["output_file"] = os.path.join(
474 diffdir, f"{options['graph_attr']}_{base_rev_file}"
475 )
476 print(f"Generating {options['graph_attr']} @ {base_rev}", file=sys.stderr)
477 ret |= generate_taskgraph(options, parameters, overrides, logdir)
478 finally:
479 assert cur_rev
480 repo.update(cur_rev)
481
482 # Generate diff(s)
483 diffcmd = [
484 "diff",
485 "-U20",
486 "--report-identical-files",
487 f"--label={options['graph_attr']}@{base_rev}",
488 f"--label={options['graph_attr']}@{cur_rev}",
489 ]
490
491 non_fatal_failures = []
492
493 for spec in parameters:
494 base_path = os.path.join(
495 diffdir, f"{options['graph_attr']}_{base_rev_file}"
496 )
497 cur_path = os.path.join(diffdir, f"{options['graph_attr']}_{cur_rev_file}") # type: ignore
498
499 params_name = None
500 if len(parameters) > 1:
501 params_name = Parameters.format_spec(spec)
502 base_path += f"_{params_name}"
503 cur_path += f"_{params_name}"
504
505 # If the base or cur files are missing it means that generation
506 # failed. If one of them failed but not the other, the failure is
507 # likely due to the patch making changes to taskgraph in modules
508 # that don't get reloaded (safe to ignore). If both generations
509 # failed, there's likely a real issue.
510 base_missing = not os.path.isfile(base_path)
511 cur_missing = not os.path.isfile(cur_path)
512 if base_missing != cur_missing: # != is equivalent to XOR for booleans
513 non_fatal_failures.append(os.path.basename(base_path))
514 continue
515
516 try:
517 # If the output file(s) are missing, this command will raise
518 # CalledProcessError with a returncode > 1.
519 proc = subprocess.run(
520 diffcmd + [base_path, cur_path],
521 capture_output=True,
522 text=True,
523 check=True,
524 )
525 diff_output = proc.stdout
526 returncode = 0
527 except subprocess.CalledProcessError as e:
528 # returncode 1 simply means diffs were found
529 if e.returncode != 1:
530 print(e.stderr, file=sys.stderr)
531 raise
532 diff_output = e.output
533 returncode = e.returncode
534
535 dump_output(
536 diff_output,
537 # Don't bother saving file if no diffs were found. Log to
538 # console in this case instead.
539 path=None if returncode == 0 else output_file,
540 params_spec=spec if len(parameters) > 1 else None,
541 )
542
543 if non_fatal_failures:
544 failstr = "\n ".join(sorted(non_fatal_failures))
545 print(
546 "WARNING: Diff skipped for the following generation{s} "
547 "due to failures:\n {failstr}".format(
548 s="s" if len(non_fatal_failures) > 1 else "", failstr=failstr
549 ),
550 file=sys.stderr,
551 )
552
553 if options["format"] != "json":
554 print(
555 "If you were expecting differences in task bodies "
556 'you should pass "-J"\n',
557 file=sys.stderr,
558 )
559
560 if len(parameters) > 1:
561 print(f"See '{logdir}' for logs", file=sys.stderr)
562
563 return ret
564
565
566 @command("build-image", help="Build a Docker image")
567 @argument("image_name", help="Name of the image to build")
568 @argument(
569 "-t", "--tag", help="tag that the image should be built as.", metavar="name:tag"
570 )
571 @argument(
572 "--context-only",
573 help="File name the context tarball should be written to."
574 "with this option it will only build the context.tar.",
575 metavar="context.tar",
576 )
577 def build_image(args):
578 from taskgraph.docker import build_context, build_image
579
580 validate_docker()
581 if args["context_only"] is None:
582 build_image(args["image_name"], args["tag"], os.environ)
583 else:
584 build_context(args["image_name"], args["context_only"], os.environ)
585
586
587 @command(
588 "load-image",
589 help="Load a pre-built Docker image. Note that you need to "
590 "have docker installed and running for this to work.",
591 )
592 @argument(
593 "--task-id",
594 help="Load the image at public/image.tar.zst in this task, "
595 "rather than searching the index",
596 )
597 @argument(
598 "-t",
599 "--tag",
600 help="tag that the image should be loaded as. If not "
601 "image will be loaded with tag from the tarball",
602 metavar="name:tag",
603 )
604 @argument(
605 "image_name",
606 nargs="?",
607 help="Load the image of this name based on the current "
608 "contents of the tree (as built for mozilla-central "
609 "or mozilla-inbound)",
610 )
611 def load_image(args):
612 from taskgraph.docker import load_image_by_name, load_image_by_task_id
613
614 if not args.get("image_name") and not args.get("task_id"):
615 print("Specify either IMAGE-NAME or TASK-ID")
616 sys.exit(1)
617 validate_docker()
618 try:
619 if args["task_id"]:
620 tag = load_image_by_task_id(args["task_id"], args.get("tag"))
621 else:
622 tag = load_image_by_name(args["image_name"], args.get("tag"))
623 if not tag:
624 sys.exit(1)
625 except Exception:
626 traceback.print_exc()
627 sys.exit(1)
628
629
630 def validate_docker():
631 p = subprocess.run(["docker", "ps"], capture_output=True)
632 if p.returncode != 0:
633 print("Error connecting to Docker:", p.stderr)
634 sys.exit(1)
635
636
637 @command("image-digest", help="Print the digest of a docker image.")
638 @argument(
639 "image_name",
640 help="Print the digest of the image of this name based on the current "
641 "contents of the tree.",
642 )
643 def image_digest(args):
644 from taskgraph.docker import get_image_digest
645
646 try:
647 digest = get_image_digest(args["image_name"])
648 print(digest)
649 except Exception:
650 traceback.print_exc()
651 sys.exit(1)
652
653
654 @command(
655 "load-task",
656 help="Loads a pre-built Docker image and drops you into a container with "
657 "the same environment variables and run-task setup as the specified task. "
658 "The task's payload.command will be replaced with 'bash'. You need to have "
659 "docker installed and running for this to work.",
660 )
661 @argument("task_id", help="The task id to load into a docker container.")
662 @argument(
663 "--keep",
664 dest="remove",
665 action="store_false",
666 default=True,
667 help="Keep the docker container after exiting.",
668 )
669 @argument("--user", default=None, help="Container user to start shell with.")
670 def load_task(args):
671 from taskgraph.docker import load_task
672
673 validate_docker()
674 return load_task(args["task_id"], remove=args["remove"], user=args["user"])
675
676
677 @command("decision", help="Run the decision task")
678 @argument("--root", "-r", help="root of the taskgraph definition relative to topsrcdir")
679 @argument(
680 "--message",
681 required=False,
682 help=argparse.SUPPRESS,
683 )
684 @argument(
685 "--project",
686 required=True,
687 help="Project to use for creating task graph. Example: --project=try",
688 )
689 @argument("--pushlog-id", dest="pushlog_id", required=True, default="0")
690 @argument("--pushdate", dest="pushdate", required=True, type=int, default=0)
691 @argument("--owner", required=True, help="email address of who owns this graph")
692 @argument("--level", required=True, help="SCM level of this repository")
693 @argument(
694 "--target-tasks-method", help="method for selecting the target tasks to generate"
695 )
696 @argument(
697 "--repository-type",
698 required=True,
699 help='Type of repository, either "hg" or "git"',
700 )
701 @argument("--base-repository", required=True, help='URL for "base" repository to clone')
702 @argument(
703 "--base-ref", default="", help='Reference of the revision in the "base" repository'
704 )
705 @argument(
706 "--base-rev",
707 default="",
708 help="Taskgraph decides what to do based on the revision range between "
709 "`--base-rev` and `--head-rev`. Value is determined automatically if not provided",
710 )
711 @argument(
712 "--head-repository",
713 required=True,
714 help='URL for "head" repository to fetch revision from',
715 )
716 @argument(
717 "--head-ref", required=True, help="Reference (this is same as rev usually for hg)"
718 )
719 @argument(
720 "--head-rev", required=True, help="Commit revision to use from head repository"
721 )
722 @argument("--head-tag", help="Tag attached to the revision", default="")
723 @argument(
724 "--tasks-for", required=True, help="the tasks_for value used to generate this task"
725 )
726 @argument("--try-task-config-file", help="path to try task configuration file")
727 @argument(
728 "--verbose", "-v", action="store_true", help="include debug-level logging output"
729 )
730 def decision(options):
731 from taskgraph.decision import taskgraph_decision
732
733 taskgraph_decision(options)
734
735
736 @command("actions", help="Print the rendered actions.json")
737 @argument(
738 "--root",
739 "-r",
740 help="root of the taskgraph definition relative to topsrcdir",
741 default="taskcluster",
742 )
743 @argument(
744 "--verbose",
745 "-v",
746 action="store_true",
747 help="include debug-level logging output",
748 )
749 @argument(
750 "--parameters",
751 "-p",
752 default="",
753 help="parameters file (.yml or .json; see `taskcluster/docs/parameters.rst`)`",
754 )
755 def actions(args):
756 from taskgraph.actions import render_actions_json
757 from taskgraph.generator import TaskGraphGenerator
758 from taskgraph.parameters import parameters_loader
759 from taskgraph.util import json
760
761 if args.pop("verbose", False):
762 logging.root.setLevel(logging.DEBUG)
763
764 try:
765 parameters = parameters_loader(args["parameters"], strict=False)
766 tgg = TaskGraphGenerator(root_dir=args.get("root"), parameters=parameters)
767
768 actions = render_actions_json(tgg.parameters, tgg.graph_config, "DECISION-TASK")
769 print(json.dumps(actions, sort_keys=True, indent=2))
770 except Exception:
771 traceback.print_exc()
772 sys.exit(1)
773
774 return 0
775
776
777 @command("action-callback", description="Run action callback used by action tasks")
778 @argument(
779 "--root",
780 "-r",
781 default="taskcluster",
782 help="root of the taskgraph definition relative to topsrcdir",
783 )
784 def action_callback(options):
785 from taskgraph.actions import trigger_action_callback
786 from taskgraph.actions.util import get_parameters
787 from taskgraph.util import json
788
789 try:
790 # the target task for this action (or null if it's a group action)
791 task_id = json.loads(os.environ.get("ACTION_TASK_ID", "null"))
792 # the target task group for this action
793 task_group_id = os.environ.get("ACTION_TASK_GROUP_ID", None)
794 input = json.loads(os.environ.get("ACTION_INPUT", "null"))
795 callback = os.environ.get("ACTION_CALLBACK", None)
796 root = options["root"]
797
798 parameters = get_parameters(task_group_id)
799
800 return trigger_action_callback(
801 task_group_id=task_group_id,
802 task_id=task_id,
803 input=input,
804 callback=callback,
805 parameters=parameters,
806 root=root,
807 test=False,
808 )
809 except Exception:
810 traceback.print_exc()
811 sys.exit(1)
812
813
814 @command("test-action-callback", description="Run an action callback in a testing mode")
815 @argument(
816 "--root",
817 "-r",
818 default="taskcluster",
819 help="root of the taskgraph definition relative to topsrcdir",
820 )
821 @argument(
822 "--parameters",
823 "-p",
824 default="",
825 help="parameters file (.yml or .json; see `taskcluster/docs/parameters.rst`)`",
826 )
827 @argument("--task-id", default=None, help="TaskId to which the action applies")
828 @argument(
829 "--task-group-id", default=None, help="TaskGroupId to which the action applies"
830 )
831 @argument("--input", default=None, help="Action input (.yml or .json)")
832 @argument("callback", default=None, help="Action callback name (Python function name)")
833 def test_action_callback(options):
834 import taskgraph.actions
835 import taskgraph.parameters
836 from taskgraph.config import load_graph_config
837 from taskgraph.util import json, yaml
838
839 def load_data(filename):
840 with open(filename) as f:
841 if filename.endswith(".yml"):
842 return yaml.load_stream(f)
843 elif filename.endswith(".json"):
844 return json.load(f)
845 else:
846 raise Exception(f"unknown filename {filename}")
847
848 try:
849 task_id = options["task_id"]
850
851 if options["input"]:
852 input = load_data(options["input"])
853 else:
854 input = None
855
856 root = options["root"]
857 graph_config = load_graph_config(root)
858 trust_domain = graph_config["trust-domain"]
859 graph_config.register()
860
861 parameters = taskgraph.parameters.load_parameters_file(
862 options["parameters"], strict=False, trust_domain=trust_domain
863 )
864 parameters.check()
865
866 return taskgraph.actions.trigger_action_callback(
867 task_group_id=options["task_group_id"],
868 task_id=task_id,
869 input=input,
870 callback=options["callback"],
871 parameters=parameters,
872 root=root,
873 test=True,
874 )
875 except Exception:
876 traceback.print_exc()
877 sys.exit(1)
878
879
880 @command(
881 "init", description="Initialize a new Taskgraph setup in a new or existing project."
882 )
883 @argument(
884 "-f",
885 "--force",
886 action="store_true",
887 default=False,
888 help="Bypass safety checks.",
889 )
890 @argument(
891 "--prompt",
892 dest="no_input",
893 action="store_false",
894 default=True,
895 help="Prompt for input rather than using default values (advanced).",
896 )
897 @argument(
898 "--template",
899 default="gh:taskcluster/taskgraph",
900 help=argparse.SUPPRESS, # used for testing
901 )
902 def init_taskgraph(options):
903 from cookiecutter.main import cookiecutter
904
905 import taskgraph
906 from taskgraph.util.vcs import get_repository
907
908 repo = get_repository(os.getcwd())
909 root = Path(repo.path)
910
911 # Clean up existing installations if necessary.
912 tc_yml = root.joinpath(".taskcluster.yml")
913 if tc_yml.is_file():
914 if not options["force"]:
915 proceed = input(
916 "A Taskcluster setup already exists in this repository, "
917 "would you like to overwrite it? [y/N]: "
918 ).lower()
919 while proceed not in ("y", "yes", "n", "no"):
920 proceed = input(f"Invalid option '{proceed}'! Try again: ")
921
922 if proceed[0] == "n":
923 sys.exit(1)
924
925 tc_yml.unlink()
926 tg_dir = root.joinpath("taskcluster")
927 if tg_dir.is_dir():
928 shutil.rmtree(tg_dir)
929
930 # Populate some defaults from the current repository.
931 context = {"project_name": root.name, "taskgraph_version": taskgraph.__version__}
932
933 try:
934 repo_url = repo.get_url(remote=repo.remote_name)
935 except RuntimeError:
936 repo_url = ""
937
938 if repo.tool == "git" and "github.com" in repo_url:
939 context["repo_host"] = "github"
940 else:
941 print(
942 dedent(
943 """\
944 Repository not supported!
945
946 The `taskgraph init` command only supports repositories hosted on
947 Github. Ensure you use a remote that points to a Github repository.
948 """
949 ),
950 file=sys.stderr,
951 )
952 return 1
953
954 context["repo_name"] = urlparse(repo_url).path.rsplit("/", 1)[-1]
955 if context["repo_name"].endswith(".git"):
956 context["repo_name"] = context["repo_name"][: -len(".git")]
957
958 # Generate the project.
959 cookiecutter(
960 options["template"],
961 checkout=taskgraph.__version__,
962 directory="template",
963 extra_context=context,
964 no_input=options["no_input"],
965 output_dir=str(root.parent),
966 overwrite_if_exists=True,
967 )
968
969
970 def create_parser():
971 parser = argparse.ArgumentParser(description="Interact with taskgraph")
972 subparsers = parser.add_subparsers()
973 for _, (func, args, kwargs, defaults) in commands.items():
974 subparser = subparsers.add_parser(*args, **kwargs)
975 for arg in func.args:
976 subparser.add_argument(*arg[0], **arg[1])
977 subparser.set_defaults(command=func, **defaults)
978 return parser
979
980
981 def setup_logging():
982 logging.basicConfig(
983 format="%(asctime)s - %(levelname)s - %(message)s", level=logging.INFO
984 )
985
986
987 def main(args=sys.argv[1:]):
988 setup_logging()
989 parser = create_parser()
990
991 if not args:
992 parser.print_help()
993 sys.exit(1)
994
995 args = parser.parse_args(args)
996 try:
997 return args.command(vars(args))
998 except Exception:
999 traceback.print_exc()
1000 sys.exit(1)