Debian Codegraph @

third_party/python/taskcluster_taskgraph/taskgraph/config.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
6 import logging
7 import os
8 import sys
9 from dataclasses import dataclass
10 from typing import Dict
11
12 from voluptuous import All, Any, Extra, Length, Optional, Required
13
14 from .util import path
15 from .util.caches import CACHES
16 from .util.python_path import find_object
17 from .util.schema import Schema, optionally_keyed_by, validate_schema
18 from .util.yaml import load_yaml
19
20 logger = logging.getLogger(__name__)
21
22 graph_config_schema = Schema(
23 {
24 # The trust-domain for this graph.
25 # (See https://firefox-source-docs.mozilla.org/taskcluster/taskcluster/taskgraph.html#taskgraph-trust-domain) # noqa
26 Required("trust-domain"): str,
27 Required("task-priority"): optionally_keyed_by(
28 "project",
29 "level",
30 Any(
31 "highest",
32 "very-high",
33 "high",
34 "medium",
35 "low",
36 "very-low",
37 "lowest",
38 ),
39 ),
40 Optional(
41 "task-deadline-after",
42 description="Default 'deadline' for tasks, in relative date format. "
43 "Eg: '1 week'",
44 ): optionally_keyed_by("project", str),
45 Optional(
46 "task-expires-after",
47 description="Default 'expires-after' for level 1 tasks, in relative date format. "
48 "Eg: '90 days'",
49 ): str,
50 Required("workers"): {
51 Required("aliases"): {
52 str: {
53 Required("provisioner"): optionally_keyed_by("level", str),
54 Required("implementation"): str,
55 Required("os"): str,
56 Required("worker-type"): optionally_keyed_by("level", str),
57 }
58 },
59 },
60 Required("taskgraph"): {
61 Optional(
62 "register",
63 description="Python function to call to register extensions.",
64 ): str,
65 Optional("decision-parameters"): str,
66 Optional(
67 "cached-task-prefix",
68 description="The taskcluster index prefix to use for caching tasks. "
69 "Defaults to `trust-domain`.",
70 ): str,
71 Optional(
72 "cache-pull-requests",
73 description="Should tasks from pull requests populate the cache",
74 ): bool,
75 Optional(
76 "index-path-regexes",
77 description="Regular expressions matching index paths to be summarized.",
78 ): [str],
79 Optional(
80 "run",
81 description="Configuration related to the 'run' transforms.",
82 ): {
83 Optional(
84 "use-caches",
85 description="List of caches to enable, or a boolean to "
86 "enable/disable all of them.",
87 ): Any(bool, list(CACHES.keys())),
88 },
89 Required("repositories"): All(
90 {
91 str: {
92 Required("name"): str,
93 Optional("project-regex"): str,
94 Optional("ssh-secret-name"): str,
95 # FIXME
96 Extra: str,
97 }
98 },
99 Length(min=1),
100 ),
101 },
102 Extra: object,
103 }
104 )
105 """Schema for GraphConfig"""
106
107
108 @dataclass(frozen=True, eq=False)
109 class GraphConfig:
110 _config: Dict
111 root_dir: str
112
113 _PATH_MODIFIED = False
114
115 def __post_init__(self):
116 # ensure we have an absolute path; this is required for assumptions
117 # made later, such as the `vcs_root` being a directory above `root_dir`
118 object.__setattr__(self, "root_dir", os.path.abspath(self.root_dir))
119
120 def __getitem__(self, name):
121 return self._config[name]
122
123 def __contains__(self, name):
124 return name in self._config
125
126 def get(self, name, default=None):
127 return self._config.get(name, default)
128
129 def register(self):
130 """
131 Add the project's taskgraph directory to the python path, and register
132 any extensions present.
133 """
134 if GraphConfig._PATH_MODIFIED:
135 if GraphConfig._PATH_MODIFIED == self.root_dir:
136 # Already modified path with the same root_dir.
137 # We currently need to do this to enable actions to call
138 # taskgraph_decision, e.g. relpro.
139 return
140 raise Exception("Can't register multiple directories on python path.")
141 GraphConfig._PATH_MODIFIED = self.root_dir
142 sys.path.insert(0, self.root_dir)
143 register_path = self["taskgraph"].get("register")
144 if register_path:
145 find_object(register_path)(self)
146
147 @property
148 def vcs_root(self):
149 if path.split(self.root_dir)[-1:] != ["taskcluster"]:
150 raise Exception(
151 "Not guessing path to vcs root. Graph config in non-standard location."
152 )
153 return os.path.dirname(self.root_dir)
154
155 @property
156 def taskcluster_yml(self):
157 return os.path.join(self.vcs_root, ".taskcluster.yml")
158
159
160 def validate_graph_config(config):
161 validate_schema(graph_config_schema, config, "Invalid graph configuration:")
162
163
164 def load_graph_config(root_dir):
165 config_yml = os.path.join(root_dir, "config.yml")
166 if not os.path.exists(config_yml):
167 raise Exception(f"Couldn't find taskgraph configuration: {config_yml}")
168
169 logger.debug(f"loading config from `{config_yml}`")
170 config = load_yaml(config_yml)
171
172 validate_graph_config(config)
173 return GraphConfig(config, root_dir=root_dir)