Debian Codegraph @

infra/bots/gen_tasks_logic/schema.go

raw
1 // Copyright 2020 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 package gen_tasks_logic
5
6 /*
7 This file contains logic related to task/job name schemas.
8 */
9
10 import (
11 "encoding/json"
12 "fmt"
13 "log"
14 "os"
15 "regexp"
16 "strings"
17 )
18
19 // Parts represents the key/value pairs which make up task and job names.
20 type Parts map[string]string
21
22 // Equal returns true if the given part of this job's name equals any of the
23 // given values. Panics if no values are provided.
24 func (p Parts) Equal(part string, eq ...string) bool {
25 if len(eq) == 0 {
26 log.Fatal("No values provided for equal!")
27 }
28 v := p[part]
29 for _, e := range eq {
30 if v == e {
31 return true
32 }
33 }
34 return false
35 }
36
37 // Role returns true if the Role for this job equals any of the given values.
38 func (p Parts) Role(eq ...string) bool {
39 return p.Equal("role", eq...)
40 }
41
42 // Os returns true if the OS for this job equals any of the given values.
43 func (p Parts) Os(eq ...string) bool {
44 return p.Equal("os", eq...)
45 }
46
47 // Compiler returns true if the Compiler for this job equals any of the given
48 // values.
49 func (p Parts) Compiler(eq ...string) bool {
50 return p.Equal("compiler", eq...)
51 }
52
53 // Model returns true if the Model for this job equals any of the given values.
54 func (p Parts) Model(eq ...string) bool {
55 return p.Equal("model", eq...)
56 }
57
58 // Frequency returns true if the Frequency for this job equals any of the given
59 // values.
60 func (p Parts) Frequency(eq ...string) bool {
61 return p.Equal("frequency", eq...)
62 }
63
64 // CPU returns true if the task's cpu_or_gpu is "CPU" and the CPU for this
65 // task equals any of the given values. If no values are provided, CPU returns
66 // true if this task runs on CPU.
67 func (p Parts) CPU(eq ...string) bool {
68 if p["cpu_or_gpu"] == "CPU" {
69 if len(eq) == 0 {
70 return true
71 }
72 return p.Equal("cpu_or_gpu_value", eq...)
73 }
74 return false
75 }
76
77 // GPU returns true if the task's cpu_or_gpu is "GPU" and the GPU for this task
78 // equals any of the given values. If no values are provided, GPU returns true
79 // if this task runs on GPU.
80 func (p Parts) GPU(eq ...string) bool {
81 if p["cpu_or_gpu"] == "GPU" {
82 if len(eq) == 0 {
83 return true
84 }
85 return p.Equal("cpu_or_gpu_value", eq...)
86 }
87 return false
88 }
89
90 // Arch returns true if the architecture for this job equals any of the
91 // given values.
92 func (p Parts) Arch(eq ...string) bool {
93 return p.Equal("arch", eq...) || p.Equal("target_arch", eq...)
94 }
95
96 // ExtraConfig returns true if any of the extra_configs for this job equals
97 // any of the given values. If the extra_config starts with "SK_",
98 // it is considered to be a single config.
99 func (p Parts) ExtraConfig(eq ...string) bool {
100 if len(eq) == 0 {
101 log.Fatal("No values provided for extraConfig()!")
102 }
103 ec := p["extra_config"]
104 if ec == "" {
105 return false
106 }
107 splitCfgs := strings.Split(ec, "_")
108 cfgs := make([]string, 0, len(splitCfgs))
109 for idx, c := range splitCfgs {
110 if c == "SK" {
111 cfgs = append(cfgs, strings.Join(cfgs[idx:], "_"))
112 break
113 }
114 cfgs = append(cfgs, c)
115 }
116 for _, c := range cfgs {
117 for _, e := range eq {
118 if c == e {
119 return true
120 }
121 }
122 }
123 return false
124 }
125
126 // NoExtraConfig returns true if there are no extra_configs for this job.
127 func (p Parts) NoExtraConfig(eq ...string) bool {
128 ec := p["extra_config"]
129 return ec == ""
130 }
131
132 // MatchPart returns true if the given part of this job's name matches any of
133 // the given regular expressions. Note that a regular expression might match any
134 // substring, so if you need an exact match on the entire string you'll need to
135 // use `^` and `$`. Panics if no regular expressions are provided.
136 func (p Parts) MatchPart(part string, re ...string) bool {
137 if len(re) == 0 {
138 log.Fatal("No regular expressions provided for matchPart()!")
139 }
140 v := p[part]
141 for _, r := range re {
142 if regexp.MustCompile(r).MatchString(v) {
143 return true
144 }
145 }
146 return false
147 }
148
149 // MatchRole returns true if the role for this job matches any of the given
150 // regular expressions.
151 func (p Parts) MatchRole(re ...string) bool {
152 return p.MatchPart("role", re...)
153 }
154
155 func (p Parts) Project(re ...string) bool {
156 return p.MatchPart("project", re...)
157 }
158
159 // MatchOs returns true if the OS for this job matches any of the given regular
160 // expressions.
161 func (p Parts) MatchOs(re ...string) bool {
162 return p.MatchPart("os", re...)
163 }
164
165 // MatchCompiler returns true if the compiler for this job matches any of the
166 // given regular expressions.
167 func (p Parts) MatchCompiler(re ...string) bool {
168 return p.MatchPart("compiler", re...)
169 }
170
171 // MatchModel returns true if the model for this job matches any of the given
172 // regular expressions.
173 func (p Parts) MatchModel(re ...string) bool {
174 return p.MatchPart("model", re...)
175 }
176
177 // MatchCpu returns true if the task's cpu_or_gpu is "CPU" and the CPU for this
178 // task matches any of the given regular expressions. If no regular expressions
179 // are provided, cpu returns true if this task runs on CPU.
180 func (p Parts) MatchCpu(re ...string) bool {
181 if p["cpu_or_gpu"] == "CPU" {
182 if len(re) == 0 {
183 return true
184 }
185 return p.MatchPart("cpu_or_gpu_value", re...)
186 }
187 return false
188 }
189
190 // MatchGpu returns true if the task's cpu_or_gpu is "GPU" and the GPU for this task
191 // matches any of the given regular expressions. If no regular expressions are
192 // provided, gpu returns true if this task runs on GPU.
193 func (p Parts) MatchGpu(re ...string) bool {
194 if p["cpu_or_gpu"] == "GPU" {
195 if len(re) == 0 {
196 return true
197 }
198 return p.MatchPart("cpu_or_gpu_value", re...)
199 }
200 return false
201 }
202
203 // MatchArch returns true if the architecture for this job matches any of the
204 // given regular expressions.
205 func (p Parts) MatchArch(re ...string) bool {
206 return p.MatchPart("arch", re...) || p.MatchPart("target_arch", re...)
207 }
208
209 // MatchBazelHost returns true if the Bazel host for this job matches any of the
210 // given regular expressions.
211 func (p Parts) MatchBazelHost(re ...string) bool {
212 return p.MatchPart("host", re...)
213 }
214
215 // MatchExtraConfig returns true if any of the extra_configs for this job matches
216 // any of the given regular expressions. If the extra_config starts with "SK_",
217 // it is considered to be a single config.
218 func (p Parts) MatchExtraConfig(re ...string) bool {
219 if len(re) == 0 {
220 log.Fatal("No regular expressions provided for matchExtraConfig()!")
221 }
222 ec := p["extra_config"]
223 if ec == "" {
224 return false
225 }
226 var cfgs []string
227 if strings.HasPrefix(ec, "SK_") {
228 cfgs = []string{ec}
229 } else {
230 cfgs = strings.Split(ec, "_")
231 }
232 compiled := make([]*regexp.Regexp, 0, len(re))
233 for _, r := range re {
234 compiled = append(compiled, regexp.MustCompile(r))
235 }
236 for _, c := range cfgs {
237 for _, r := range compiled {
238 if r.MatchString(c) {
239 return true
240 }
241 }
242 }
243 return false
244 }
245
246 // Debug returns true if this task runs in Debug mode.
247 func (p Parts) Debug() bool {
248 return p["configuration"] == "Debug"
249 }
250
251 // Release returns true if this task runs in Release mode.
252 func (p Parts) Release() bool {
253 return p["configuration"] == "Release"
254 }
255
256 // IsLinux returns true if the task runs on Linux.
257 func (p Parts) IsLinux() bool {
258 return p.MatchOs("Debian", "Ubuntu") ||
259 p.MatchExtraConfig("Debian", "Ubuntu") ||
260 p.MatchBazelHost("linux", "on_rpi") ||
261 p.Role("Housekeeper", "Canary", "Upload")
262
263 }
264
265 // IsWindows returns true if the task runs on Windows.
266 func (p Parts) IsWindows() bool {
267 return !p.Role("Upload") && (p.MatchOs("Win") || p.MatchExtraConfig("Win") || p.MatchBazelHost("windows"))
268 }
269
270 // IsMac returns true if the task runs on Mac.
271 func (p Parts) IsMac() bool {
272 return !p.Role("Upload") && (p.MatchOs("Mac") || p.MatchExtraConfig("Mac") || p.MatchBazelHost("darwin"))
273 }
274
275 // BazelBuildParts returns all parts from the BazelBuild schema. All parts are required.
276 func (p Parts) BazelBuildParts() (label string, config string, host string) {
277 return p["label"], p["config"], p["host"]
278 }
279
280 // BazelTestParts returns all parts from the BazelTest schema. task_driver, label, build_config,
281 // and host are required; test_config is optional.
282 func (p Parts) BazelTestParts() (taskDriver string, label string, buildConfig string, host string, testConfig string) {
283 return p["task_driver"], p["label"], p["build_config"], p["host"], p["test_config"]
284 }
285
286 // TODO(borenet): The below really belongs in its own file, probably next to the
287 // builder_name_schema.json file.
288
289 // schema is a sub-struct of JobNameSchema.
290 type schema struct {
291 Keys []string `json:"keys"`
292 OptionalKeys []string `json:"optional_keys"`
293 RecurseRoles []string `json:"recurse_roles"`
294 }
295
296 // JobNameSchema is a struct used for (de)constructing Job names in a
297 // predictable format.
298 type JobNameSchema struct {
299 Schema map[string]*schema `json:"builder_name_schema"`
300 Sep string `json:"builder_name_sep"`
301 }
302
303 // NewJobNameSchema returns a JobNameSchema instance based on the given JSON
304 // file.
305 func NewJobNameSchema(jsonFile string) (*JobNameSchema, error) {
306 var rv JobNameSchema
307 f, err := os.Open(jsonFile)
308 if err != nil {
309 return nil, err
310 }
311 defer func() {
312 if err := f.Close(); err != nil {
313 log.Println(fmt.Sprintf("Failed to close %s: %s", jsonFile, err))
314 }
315 }()
316 if err := json.NewDecoder(f).Decode(&rv); err != nil {
317 return nil, err
318 }
319 return &rv, nil
320 }
321
322 // ParseJobName splits the given Job name into its component parts, according
323 // to the schema.
324 func (s *JobNameSchema) ParseJobName(n string) (map[string]string, error) {
325 popFront := func(items []string) (string, []string, error) {
326 if len(items) == 0 {
327 return "", nil, fmt.Errorf("Invalid job name: %s (not enough parts)", n)
328 }
329 return items[0], items[1:], nil
330 }
331
332 result := map[string]string{}
333
334 var parse func(int, string, []string) ([]string, error)
335 parse = func(depth int, role string, parts []string) ([]string, error) {
336 s, ok := s.Schema[role]
337 if !ok {
338 return nil, fmt.Errorf("Invalid job name; %q is not a valid role.", role)
339 }
340 if depth == 0 {
341 result["role"] = role
342 } else {
343 result[fmt.Sprintf("sub-role-%d", depth)] = role
344 }
345 var err error
346 for _, key := range s.Keys {
347 var value string
348 value, parts, err = popFront(parts)
349 if err != nil {
350 return nil, err
351 }
352 result[key] = value
353 }
354 for _, subRole := range s.RecurseRoles {
355 if len(parts) > 0 && parts[0] == subRole {
356 parts, err = parse(depth+1, parts[0], parts[1:])
357 if err != nil {
358 return nil, err
359 }
360 }
361 }
362 for _, key := range s.OptionalKeys {
363 if len(parts) > 0 {
364 var value string
365 value, parts, err = popFront(parts)
366 if err != nil {
367 return nil, err
368 }
369 result[key] = value
370 }
371 }
372 if len(parts) > 0 {
373 return nil, fmt.Errorf("Invalid job name: %s (too many parts)", n)
374 }
375 return parts, nil
376 }
377
378 split := strings.Split(n, s.Sep)
379 if len(split) < 2 {
380 return nil, fmt.Errorf("Invalid job name: %s (not enough parts)", n)
381 }
382 role := split[0]
383 split = split[1:]
384 _, err := parse(0, role, split)
385 return result, err
386 }
387
388 // MakeJobName assembles the given parts of a Job name, according to the schema.
389 func (s *JobNameSchema) MakeJobName(parts map[string]string) (string, error) {
390 rvParts := make([]string, 0, len(parts))
391
392 var process func(int, map[string]string) (map[string]string, error)
393 process = func(depth int, parts map[string]string) (map[string]string, error) {
394 roleKey := "role"
395 if depth != 0 {
396 roleKey = fmt.Sprintf("sub-role-%d", depth)
397 }
398 role, ok := parts[roleKey]
399 if !ok {
400 return nil, fmt.Errorf("Invalid job parts; missing key %q", roleKey)
401 }
402
403 s, ok := s.Schema[role]
404 if !ok {
405 return nil, fmt.Errorf("Invalid job parts; unknown role %q", role)
406 }
407 rvParts = append(rvParts, role)
408 delete(parts, roleKey)
409
410 for _, key := range s.Keys {
411 value, ok := parts[key]
412 if !ok {
413 return nil, fmt.Errorf("Invalid job parts; missing %q", key)
414 }
415 rvParts = append(rvParts, value)
416 delete(parts, key)
417 }
418
419 if len(s.RecurseRoles) > 0 {
420 subRoleKey := fmt.Sprintf("sub-role-%d", depth+1)
421 subRole, ok := parts[subRoleKey]
422 if !ok {
423 return nil, fmt.Errorf("Invalid job parts; missing %q", subRoleKey)
424 }
425 rvParts = append(rvParts, subRole)
426 delete(parts, subRoleKey)
427 found := false
428 for _, recurseRole := range s.RecurseRoles {
429 if recurseRole == subRole {
430 found = true
431 var err error
432 parts, err = process(depth+1, parts)
433 if err != nil {
434 return nil, err
435 }
436 break
437 }
438 }
439 if !found {
440 return nil, fmt.Errorf("Invalid job parts; unknown sub-role %q", subRole)
441 }
442 }
443 for _, key := range s.OptionalKeys {
444 if value, ok := parts[key]; ok {
445 rvParts = append(rvParts, value)
446 delete(parts, key)
447 }
448 }
449 if len(parts) > 0 {
450 return nil, fmt.Errorf("Invalid job parts: too many parts: %v", parts)
451 }
452 return parts, nil
453 }
454
455 // Copy the parts map, so that we can modify at will.
456 partsCpy := make(map[string]string, len(parts))
457 for k, v := range parts {
458 partsCpy[k] = v
459 }
460 if _, err := process(0, partsCpy); err != nil {
461 return "", err
462 }
463 return strings.Join(rvParts, s.Sep), nil
464 }