1 # -*- coding: utf-8 -*-
3 # This Source Code Form is subject to the terms of the Mozilla Public
4 # License, v. 2.0. If a copy of the MPL was not distributed with this
5 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 from __future__
import absolute_import
, print_function
, unicode_literals
14 from six
import text_type
21 from mach
.decorators
import (
28 from mozbuild
.base
import MachCommandBase
32 """Convert string to boolean.
34 Wraps "distutils.util.strtobool", deferring the import of the package
35 in case it's not installed. Otherwise, we have a "chicken and egg problem" where
36 |mach bootstrap| would install the required package to enable "distutils.util", but
37 it can't because mach fails to interpret this file.
39 from distutils
.util
import strtobool
41 return bool(strtobool(value
))
44 class ShowTaskGraphSubCommand(SubCommand
):
45 """A SubCommand with TaskGraph-specific arguments"""
47 def __call__(self
, func
):
48 after
= SubCommand
.__call
__(self
, func
)
53 help="root of the taskgraph definition relative to topsrcdir",
56 "--quiet", "-q", action
="store_true", help="suppress all logging output"
62 help="include debug-level logging output",
70 help="Output task graph as a JSON object",
78 help="Output the label for each task in the task graph (default)",
83 default
="project=mozilla-central",
84 help="parameters file (.yml or .json; see "
85 "`taskcluster/docs/parameters.rst`)`",
92 help="do not remove tasks from the graph that are found in the "
93 "index (a.k.a. optimize the graph)",
99 help="only return tasks with labels matching this regular "
105 help="only return tasks that are of the given kind, "
106 "or their dependencies.",
114 help="enable fast task generation for local debugging.",
120 help="file path to store generated output.",
129 class MachCommands(MachCommandBase
):
133 description
="Manipulate TaskCluster task graphs defined in-tree",
136 """The taskgraph subcommands all relate to the generation of task graphs
137 for Gecko continuous integration. A task graph is a set of tasks linked
138 by dependencies: for example, a binary must be built before it is tested,
139 and that build may further depend on various toolchains, libraries, etc.
142 @ShowTaskGraphSubCommand(
143 "taskgraph", "tasks", description
="Show all tasks in the taskgraph"
145 def taskgraph_tasks(self
, **options
):
146 return self
.show_taskgraph("full_task_set", options
)
148 @ShowTaskGraphSubCommand("taskgraph", "full", description
="Show the full taskgraph")
149 def taskgraph_full(self
, **options
):
150 return self
.show_taskgraph("full_task_graph", options
)
152 @ShowTaskGraphSubCommand(
153 "taskgraph", "target", description
="Show the target task set"
155 def taskgraph_target(self
, **options
):
156 return self
.show_taskgraph("target_task_set", options
)
158 @ShowTaskGraphSubCommand(
159 "taskgraph", "target-graph", description
="Show the target taskgraph"
161 def taskgraph_target_taskgraph(self
, **options
):
162 return self
.show_taskgraph("target_task_graph", options
)
164 @ShowTaskGraphSubCommand(
165 "taskgraph", "optimized", description
="Show the optimized taskgraph"
167 def taskgraph_optimized(self
, **options
):
168 return self
.show_taskgraph("optimized_task_graph", options
)
170 @ShowTaskGraphSubCommand(
171 "taskgraph", "morphed", description
="Show the morphed taskgraph"
173 def taskgraph_morphed(self
, **options
):
174 return self
.show_taskgraph("morphed_task_graph", options
)
176 @SubCommand("taskgraph", "actions", description
="Write actions.json to stdout")
178 "--root", "-r", help="root of the taskgraph definition relative to topsrcdir"
181 "--quiet", "-q", action
="store_true", help="suppress all logging output"
187 help="include debug-level logging output",
192 default
="project=mozilla-central",
193 help="parameters file (.yml or .json; see "
194 "`taskcluster/docs/parameters.rst`)`",
196 def taskgraph_actions(self
, **options
):
197 return self
.show_actions(options
)
199 @SubCommand("taskgraph", "decision", description
="Run the decision task")
204 help="root of the taskgraph definition relative to topsrcdir",
210 help='URL for "base" repository to clone',
216 help='URL for "head" repository to fetch revision from',
222 help="Reference (this is same as rev usually for hg)",
228 help="Commit revision to use from head repository",
231 "--comm-base-repository",
234 help='URL for "base" comm-* repository to clone',
237 "--comm-head-repository",
240 help='URL for "head" comm-* repository to fetch revision from',
246 help="comm-* Reference (this is same as rev usually for hg)",
252 help="Commit revision to use from head comm-* repository",
258 help="Project to use for creating task graph. Example: --project=try",
261 "--pushlog-id", type=text_type
, dest
="pushlog_id", required
=True, default
="0"
263 @CommandArgument("--pushdate", dest
="pushdate", required
=True, type=int, default
=0)
268 help="email address of who owns this graph",
271 "--level", type=text_type
, required
=True, help="SCM level of this repository"
274 "--target-tasks-method",
276 help="method for selecting the target tasks to generate",
279 "--optimize-target-tasks",
280 type=lambda flag
: strtobool(flag
),
283 help="If specified, this indicates whether the target "
284 "tasks are eligible for optimization. Otherwise, "
285 "the default for the project is used.",
288 "--try-task-config-file",
290 help="path to try task configuration file",
296 help="the tasks_for value used to generate this task",
299 "--include-push-tasks",
301 help="Whether tasks from the on-push graph should be re-used "
302 "in this graph. This allows cron graphs to avoid rebuilding "
303 "jobs that were built on-push.",
307 dest
="rebuild_kinds",
309 default
=argparse
.SUPPRESS
,
310 help="Kinds that should not be re-used from the on-push graph.",
312 def taskgraph_decision(self
, **options
):
313 """Run the decision task: generate a task graph and submit to
314 TaskCluster. This is only meant to be called within decision tasks,
315 and requires a great many arguments. Commands like `mach taskgraph
316 optimized` are better suited to use on the command line, and can take
317 the parameters file generated by a decision task."""
319 import taskgraph
.decision
323 start
= time
.monotonic()
324 ret
= taskgraph
.decision
.taskgraph_decision(options
)
325 end
= time
.monotonic()
326 if os
.environ
.get("MOZ_AUTOMATION") == "1":
328 "framework": {"name": "build_metrics"},
332 "value": end
- start
,
333 "lowerIsBetter": True,
340 "PERFHERDER_DATA: {}".format(json
.dumps(perfherder_data
)),
345 traceback
.print_exc()
351 description
="Provide a pointer to the new `.cron.yml` handler.",
353 def taskgraph_cron(self
, **options
):
355 'Handling of ".cron.yml" files has move to '
356 "https://hg.mozilla.org/ci/ci-admin/file/default/build-decision."
363 description
="Run action callback used by action tasks",
368 default
="taskcluster/ci",
369 help="root of the taskgraph definition relative to topsrcdir",
371 def action_callback(self
, **options
):
372 from taskgraph
.actions
import trigger_action_callback
373 from taskgraph
.actions
.util
import get_parameters
378 # the target task for this action (or null if it's a group action)
379 task_id
= json
.loads(os
.environ
.get("ACTION_TASK_ID", "null"))
380 # the target task group for this action
381 task_group_id
= os
.environ
.get("ACTION_TASK_GROUP_ID", None)
382 input = json
.loads(os
.environ
.get("ACTION_INPUT", "null"))
383 callback
= os
.environ
.get("ACTION_CALLBACK", None)
384 root
= options
["root"]
386 parameters
= get_parameters(task_group_id
)
388 return trigger_action_callback(
389 task_group_id
=task_group_id
,
393 parameters
=parameters
,
398 traceback
.print_exc()
403 "test-action-callback",
404 description
="Run an action callback in a testing mode",
409 default
="taskcluster/ci",
410 help="root of the taskgraph definition relative to topsrcdir",
415 default
="project=mozilla-central",
416 help="parameters file (.yml or .json; see "
417 "`taskcluster/docs/parameters.rst`)`",
420 "--task-id", default
=None, help="TaskId to which the action applies"
423 "--task-group-id", default
=None, help="TaskGroupId to which the action applies"
425 @CommandArgument("--input", default
=None, help="Action input (.yml or .json)")
427 "callback", default
=None, help="Action callback name (Python function name)"
429 def test_action_callback(self
, **options
):
430 import taskgraph
.parameters
431 import taskgraph
.actions
432 from taskgraph
.util
import yaml
434 def load_data(filename
):
435 with
open(filename
) as f
:
436 if filename
.endswith(".yml"):
437 return yaml
.load_stream(f
)
438 elif filename
.endswith(".json"):
441 raise Exception("unknown filename {}".format(filename
))
445 task_id
= options
["task_id"]
448 input = load_data(options
["input"])
452 parameters
= taskgraph
.parameters
.load_parameters_file(
453 options
["parameters"],
455 # FIXME: There should be a way to parameterize this.
456 trust_domain
="gecko",
460 root
= options
["root"]
462 return taskgraph
.actions
.trigger_action_callback(
463 task_group_id
=options
["task_group_id"],
466 callback
=options
["callback"],
467 parameters
=parameters
,
472 traceback
.print_exc()
475 def setup_logging(self
, quiet
=False, verbose
=True):
477 Set up Python logging for all loggers, sending results to stderr (so
478 that command output can be redirected easily) and adding the typical
481 # remove the old terminal handler
482 old
= self
.log_manager
.replace_terminal_handler(None)
484 # re-add it, with level and fh set appropriately
486 level
= logging
.DEBUG
if verbose
else logging
.INFO
487 self
.log_manager
.add_terminal_logging(
490 write_interval
=old
.formatter
.write_interval
,
491 write_times
=old
.formatter
.write_times
,
494 # all of the taskgraph logging is unstructured logging
495 self
.log_manager
.enable_unstructured()
497 def show_taskgraph(self
, graph_attr
, options
):
498 import taskgraph
.parameters
499 import taskgraph
.generator
503 taskgraph
.fast
= True
506 self
.setup_logging(quiet
=options
["quiet"], verbose
=options
["verbose"])
507 parameters
= taskgraph
.parameters
.parameters_loader(
508 options
["parameters"],
509 overrides
={"target-kind": options
.get("target_kind")},
513 tgg
= taskgraph
.generator
.TaskGraphGenerator(
514 root_dir
=options
.get("root"),
515 parameters
=parameters
,
518 tg
= getattr(tgg
, graph_attr
)
520 show_method
= getattr(
521 self
, "show_taskgraph_" + (options
["format"] or "labels")
523 tg
= self
.get_filtered_taskgraph(tg
, options
["tasks_regex"])
525 fh
= options
["output_file"]
528 show_method(tg
, file=fh
)
530 traceback
.print_exc()
533 def show_taskgraph_labels(self
, taskgraph
, file=None):
534 for index
in taskgraph
.graph
.visit_postorder():
535 print(taskgraph
.tasks
[index
].label
, file=file)
537 def show_taskgraph_json(self
, taskgraph
, file=None):
540 taskgraph
.to_json(), sort_keys
=True, indent
=2, separators
=(",", ": ")
545 def get_filtered_taskgraph(self
, taskgraph
, tasksregex
):
546 from taskgraph
.graph
import Graph
547 from taskgraph
.taskgraph
import TaskGraph
550 This class method filters all the tasks on basis of a regular expression
551 and returns a new TaskGraph object
553 # return original taskgraph if no regular expression is passed
556 named_links_dict
= taskgraph
.graph
.named_links_dict()
558 filterededges
= set()
559 regexprogram
= re
.compile(tasksregex
)
561 for key
in taskgraph
.graph
.visit_postorder():
562 task
= taskgraph
.tasks
[key
]
563 if regexprogram
.match(task
.label
):
564 filteredtasks
[key
] = task
565 for depname
, dep
in six
.iteritems(named_links_dict
[key
]):
566 if regexprogram
.match(dep
):
567 filterededges
.add((key
, dep
, depname
))
568 filtered_taskgraph
= TaskGraph(
569 filteredtasks
, Graph(set(filteredtasks
), filterededges
)
571 return filtered_taskgraph
573 def show_actions(self
, options
):
574 import taskgraph
.parameters
575 import taskgraph
.generator
577 import taskgraph
.actions
580 self
.setup_logging(quiet
=options
["quiet"], verbose
=options
["verbose"])
581 parameters
= taskgraph
.parameters
.parameters_loader(options
["parameters"])
583 tgg
= taskgraph
.generator
.TaskGraphGenerator(
584 root_dir
=options
.get("root"),
585 parameters
=parameters
,
588 actions
= taskgraph
.actions
.render_actions_json(
591 decision_task_id
="DECISION-TASK",
593 print(json
.dumps(actions
, sort_keys
=True, indent
=2, separators
=(",", ": ")))
595 traceback
.print_exc()
600 class TaskClusterImagesProvider(MachCommandBase
):
602 "taskcluster-load-image",
604 description
="Load a pre-built Docker image. Note that you need to "
605 "have docker installed and running for this to work.",
609 help="Load the image at public/image.tar.zst in this task, "
610 "rather than searching the index",
615 help="tag that the image should be loaded as. If not "
616 "image will be loaded with tag from the tarball",
622 help="Load the image of this name based on the current "
623 "contents of the tree (as built for mozilla-central "
624 "or mozilla-inbound)",
626 def load_image(self
, image_name
, task_id
, tag
):
627 from taskgraph
.docker
import load_image_by_name
, load_image_by_task_id
629 if not image_name
and not task_id
:
630 print("Specify either IMAGE-NAME or TASK-ID")
634 ok
= load_image_by_task_id(task_id
, tag
)
636 ok
= load_image_by_name(image_name
, tag
)
640 traceback
.print_exc()
644 "taskcluster-build-image", category
="ci", description
="Build a Docker image"
646 @CommandArgument("image_name", help="Name of the image to build")
648 "-t", "--tag", help="tag that the image should be built as.", metavar
="name:tag"
652 help="File name the context tarball should be written to."
653 "with this option it will only build the context.tar.",
654 metavar
="context.tar",
656 def build_image(self
, image_name
, tag
, context_only
):
657 from taskgraph
.docker
import build_image
, build_context
660 if context_only
is None:
661 build_image(image_name
, tag
, os
.environ
)
663 build_context(image_name
, context_only
, os
.environ
)
665 traceback
.print_exc()
670 class TaskClusterPartialsData(MachCommandBase
):
674 description
="Query balrog for release history used by enable partials generation",
679 help="The gecko project branch used in balrog, such as "
680 "mozilla-central, release, maple",
683 "--product", default
="Firefox", help="The product identifier, such as 'Firefox'"
685 def generate_partials_builds(self
, product
, branch
):
686 from taskgraph
.util
.partials
import populate_release_history
692 "release_history": populate_release_history(product
, branch
)
696 release_history
, allow_unicode
=True, default_flow_style
=False
700 traceback
.print_exc()