| 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 collections |
| 7 |
import pprint |
| 8 |
import re |
| 9 |
|
| 10 |
import voluptuous |
| 11 |
|
| 12 |
import taskgraph |
| 13 |
from taskgraph.util.keyed_by import evaluate_keyed_by, iter_dot_path |
| 14 |
|
| 15 |
|
| 16 |
def validate_schema(schema, obj, msg_prefix): |
| 17 |
""" |
| 18 |
Validate that object satisfies schema. If not, generate a useful exception |
| 19 |
beginning with msg_prefix. |
| 20 |
""" |
| 21 |
if taskgraph.fast: |
| 22 |
return |
| 23 |
try: |
| 24 |
schema(obj) |
| 25 |
except voluptuous.MultipleInvalid as exc: |
| 26 |
msg = [msg_prefix] |
| 27 |
for error in exc.errors: |
| 28 |
msg.append(str(error)) |
| 29 |
raise Exception("\n".join(msg) + "\n" + pprint.pformat(obj)) |
| 30 |
|
| 31 |
|
| 32 |
def optionally_keyed_by(*arguments): |
| 33 |
""" |
| 34 |
Mark a schema value as optionally keyed by any of a number of fields. The |
| 35 |
schema is the last argument, and the remaining fields are taken to be the |
| 36 |
field names. For example: |
| 37 |
|
| 38 |
'some-value': optionally_keyed_by( |
| 39 |
'test-platform', 'build-platform', |
| 40 |
Any('a', 'b', 'c')) |
| 41 |
|
| 42 |
The resulting schema will allow nesting of `by-test-platform` and |
| 43 |
`by-build-platform` in either order. |
| 44 |
""" |
| 45 |
schema = arguments[-1] |
| 46 |
fields = arguments[:-1] |
| 47 |
|
| 48 |
def validator(obj): |
| 49 |
if isinstance(obj, dict) and len(obj) == 1: |
| 50 |
k, v = list(obj.items())[0] |
| 51 |
if k.startswith("by-") and k[len("by-") :] in fields: |
| 52 |
res = {} |
| 53 |
for kk, vv in v.items(): |
| 54 |
try: |
| 55 |
res[kk] = validator(vv) |
| 56 |
except voluptuous.Invalid as e: |
| 57 |
e.prepend([k, kk]) |
| 58 |
raise |
| 59 |
return res |
| 60 |
return Schema(schema)(obj) |
| 61 |
|
| 62 |
return validator |
| 63 |
|
| 64 |
|
| 65 |
def resolve_keyed_by( |
| 66 |
item, field, item_name, defer=None, enforce_single_match=True, **extra_values |
| 67 |
): |
| 68 |
""" |
| 69 |
For values which can either accept a literal value, or be keyed by some |
| 70 |
other attribute of the item, perform that lookup and replacement in-place |
| 71 |
(modifying `item` directly). The field is specified using dotted notation |
| 72 |
to traverse dictionaries. |
| 73 |
|
| 74 |
For example, given item:: |
| 75 |
|
| 76 |
task: |
| 77 |
test-platform: linux128 |
| 78 |
chunks: |
| 79 |
by-test-platform: |
| 80 |
macosx-10.11/debug: 13 |
| 81 |
win.*: 6 |
| 82 |
default: 12 |
| 83 |
|
| 84 |
a call to `resolve_keyed_by(item, 'task.chunks', item['thing-name'])` |
| 85 |
would mutate item in-place to:: |
| 86 |
|
| 87 |
task: |
| 88 |
test-platform: linux128 |
| 89 |
chunks: 12 |
| 90 |
|
| 91 |
The `item_name` parameter is used to generate useful error messages. |
| 92 |
|
| 93 |
If extra_values are supplied, they represent additional values available |
| 94 |
for reference from by-<field>. |
| 95 |
|
| 96 |
Items can be nested as deeply as the schema will allow:: |
| 97 |
|
| 98 |
chunks: |
| 99 |
by-test-platform: |
| 100 |
win.*: |
| 101 |
by-project: |
| 102 |
ash: .. |
| 103 |
cedar: .. |
| 104 |
linux: 13 |
| 105 |
default: 12 |
| 106 |
|
| 107 |
Args: |
| 108 |
item (dict): Object being evaluated. |
| 109 |
field (str): Name of the key to perform evaluation on. |
| 110 |
item_name (str): Used to generate useful error messages. |
| 111 |
defer (list): |
| 112 |
Allows evaluating a by-* entry at a later time. In the example |
| 113 |
above it's possible that the project attribute hasn't been set yet, |
| 114 |
in which case we'd want to stop before resolving that subkey and |
| 115 |
then call this function again later. This can be accomplished by |
| 116 |
setting `defer=["project"]` in this example. |
| 117 |
enforce_single_match (bool): |
| 118 |
If True (default), each task may only match a single arm of the |
| 119 |
evaluation. |
| 120 |
extra_values (kwargs): |
| 121 |
If supplied, represent additional values available |
| 122 |
for reference from by-<field>. |
| 123 |
|
| 124 |
Returns: |
| 125 |
dict: item which has also been modified in-place. |
| 126 |
""" |
| 127 |
for container, subfield in iter_dot_path(item, field): |
| 128 |
container[subfield] = evaluate_keyed_by( |
| 129 |
value=container[subfield], |
| 130 |
item_name=f"`{field}` in `{item_name}`", |
| 131 |
defer=defer, |
| 132 |
enforce_single_match=enforce_single_match, |
| 133 |
attributes=dict(item, **extra_values), |
| 134 |
) |
| 135 |
|
| 136 |
return item |
| 137 |
|
| 138 |
|
| 139 |
# Schemas for YAML files should use dashed identifiers by default. If there are |
| 140 |
# components of the schema for which there is a good reason to use another format, |
| 141 |
# they can be excepted here. |
| 142 |
EXCEPTED_SCHEMA_IDENTIFIERS = [ |
| 143 |
# upstream-artifacts and artifact-map are handed directly to scriptWorker, |
| 144 |
# which expects interCaps |
| 145 |
"upstream-artifacts", |
| 146 |
"artifact-map", |
| 147 |
] |
| 148 |
|
| 149 |
|
| 150 |
def check_schema(schema): |
| 151 |
identifier_re = re.compile(r"^\$?[a-z][a-z0-9-]*$") |
| 152 |
|
| 153 |
def excepted(item): |
| 154 |
for esi in EXCEPTED_SCHEMA_IDENTIFIERS: |
| 155 |
if isinstance(esi, str): |
| 156 |
if f"[{esi!r}]" in item: |
| 157 |
return True |
| 158 |
elif esi(item): |
| 159 |
return True |
| 160 |
return False |
| 161 |
|
| 162 |
def iter(path, sch): |
| 163 |
def check_identifier(path, k): |
| 164 |
if k in (str,) or k in (str, voluptuous.Extra): |
| 165 |
pass |
| 166 |
elif isinstance(k, voluptuous.NotIn): |
| 167 |
pass |
| 168 |
elif isinstance(k, str): |
| 169 |
if not identifier_re.match(k) and not excepted(path): |
| 170 |
raise RuntimeError( |
| 171 |
"YAML schemas should use dashed lower-case identifiers, " |
| 172 |
f"not {k!r} @ {path}" |
| 173 |
) |
| 174 |
elif isinstance(k, (voluptuous.Optional, voluptuous.Required)): |
| 175 |
check_identifier(path, k.schema) |
| 176 |
elif isinstance(k, (voluptuous.Any, voluptuous.All)): |
| 177 |
for v in k.validators: |
| 178 |
check_identifier(path, v) |
| 179 |
elif not excepted(path): |
| 180 |
raise RuntimeError( |
| 181 |
f"Unexpected type in YAML schema: {type(k).__name__} @ {path}" |
| 182 |
) |
| 183 |
|
| 184 |
if isinstance(sch, collections.abc.Mapping): # type: ignore |
| 185 |
for k, v in sch.items(): |
| 186 |
child = f"{path}[{k!r}]" |
| 187 |
check_identifier(child, k) |
| 188 |
iter(child, v) |
| 189 |
elif isinstance(sch, (list, tuple)): |
| 190 |
for i, v in enumerate(sch): |
| 191 |
iter(f"{path}[{i}]", v) |
| 192 |
elif isinstance(sch, voluptuous.Any): |
| 193 |
for v in sch.validators: |
| 194 |
iter(path, v) |
| 195 |
|
| 196 |
iter("schema", schema.schema) |
| 197 |
|
| 198 |
|
| 199 |
class Schema(voluptuous.Schema): |
| 200 |
""" |
| 201 |
Operates identically to voluptuous.Schema, but applying some taskgraph-specific checks |
| 202 |
in the process. |
| 203 |
""" |
| 204 |
|
| 205 |
def __init__(self, *args, check=True, **kwargs): |
| 206 |
super().__init__(*args, **kwargs) |
| 207 |
|
| 208 |
self.check = check |
| 209 |
if not taskgraph.fast and self.check: |
| 210 |
check_schema(self) |
| 211 |
|
| 212 |
def extend(self, *args, **kwargs): |
| 213 |
schema = super().extend(*args, **kwargs) |
| 214 |
|
| 215 |
if self.check: |
| 216 |
check_schema(schema) |
| 217 |
# We want twice extend schema to be checked too. |
| 218 |
schema.__class__ = Schema |
| 219 |
return schema |
| 220 |
|
| 221 |
def _compile(self, schema): |
| 222 |
if taskgraph.fast: |
| 223 |
return |
| 224 |
return super()._compile(schema) |
| 225 |
|
| 226 |
def __getitem__(self, item): |
| 227 |
return self.schema[item] # type: ignore |
| 228 |
|
| 229 |
|
| 230 |
OptimizationSchema = voluptuous.Any( |
| 231 |
# always run this task (default) |
| 232 |
None, |
| 233 |
# search the index for the given index namespaces, and replace this task if found |
| 234 |
# the search occurs in order, with the first match winning |
| 235 |
{"index-search": [str]}, |
| 236 |
# skip this task if none of the given file patterns match |
| 237 |
{"skip-unless-changed": [str]}, |
| 238 |
) |
| 239 |
|
| 240 |
# shortcut for a string where task references are allowed |
| 241 |
taskref_or_string = voluptuous.Any( |
| 242 |
str, |
| 243 |
{voluptuous.Required("task-reference"): str}, |
| 244 |
{voluptuous.Required("artifact-reference"): str}, |
| 245 |
) |