Debian Codegraph @

third_party/python/taskcluster_taskgraph/taskgraph/transforms/chunking.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 import copy
5 from textwrap import dedent
6
7 from voluptuous import ALLOW_EXTRA, Optional, Required
8
9 from taskgraph.transforms.base import TransformSequence
10 from taskgraph.util.schema import Schema
11 from taskgraph.util.templates import substitute
12
13 CHUNK_SCHEMA = Schema(
14 {
15 # Optional, so it can be used for a subset of tasks in a kind
16 Optional(
17 "chunk",
18 description=dedent(
19 """
20 `chunk` can be used to split one task into `total-chunks`
21 tasks, substituting `this_chunk` and `total_chunks` into any
22 fields in `substitution-fields`.
23 """.lstrip()
24 ),
25 ): {
26 Required(
27 "total-chunks",
28 description=dedent(
29 """
30 The total number of chunks to split the task into.
31 """.lstrip()
32 ),
33 ): int,
34 Optional(
35 "substitution-fields",
36 description=dedent(
37 """
38 A list of fields that need to have `{this_chunk}` and/or
39 `{total_chunks}` replaced in them.
40 """.lstrip()
41 ),
42 ): [str],
43 }
44 },
45 extra=ALLOW_EXTRA,
46 )
47
48 transforms = TransformSequence()
49 transforms.add_validate(CHUNK_SCHEMA)
50
51
52 @transforms.add
53 def chunk_tasks(config, tasks):
54 for task in tasks:
55 chunk_config = task.pop("chunk", None)
56 if not chunk_config:
57 yield task
58 continue
59
60 total_chunks = chunk_config["total-chunks"]
61
62 for this_chunk in range(1, total_chunks + 1):
63 subtask = copy.deepcopy(task)
64
65 subs = {
66 "this_chunk": this_chunk,
67 "total_chunks": total_chunks,
68 }
69 subtask.setdefault("attributes", {})
70 subtask["attributes"].update(subs)
71
72 for field in chunk_config["substitution-fields"]:
73 container, subfield = subtask, field
74 while "." in subfield:
75 f, subfield = subfield.split(".", 1)
76 container = container[f]
77
78 subcontainer = copy.deepcopy(container[subfield])
79 subfield = substitute(subfield, **subs)
80 container[subfield] = substitute(subcontainer, **subs)
81
82 yield subtask