Debian Codegraph @

infra/bots/gen_tasks_logic/task_builder.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 import (
7 "fmt"
8 "log"
9 "reflect"
10 "strings"
11 "time"
12
13 "go.skia.org/infra/go/cipd"
14 "go.skia.org/infra/task_scheduler/go/specs"
15 "go.skia.org/skia/infra/bots/deps"
16 )
17
18 // TaskBuilder is a helper for creating a task.
19 type TaskBuilder struct {
20 *jobBuilder
21 Parts
22 Name string
23 Spec *specs.TaskSpec
24 recipeProperties map[string]string
25 }
26
27 // newTaskBuilder returns a taskBuilder instance.
28 func newTaskBuilder(b *jobBuilder, name string) *TaskBuilder {
29 parts, err := b.jobNameSchema.ParseJobName(name)
30 if err != nil {
31 log.Fatal(err)
32 }
33 return &TaskBuilder{
34 jobBuilder: b,
35 Parts: parts,
36 Name: name,
37 Spec: &specs.TaskSpec{},
38 recipeProperties: map[string]string{},
39 }
40 }
41
42 // attempts sets the desired MaxAttempts for this task.
43 func (b *TaskBuilder) attempts(a int) {
44 b.Spec.MaxAttempts = a
45 }
46
47 // cache adds the given caches to the task.
48 func (b *TaskBuilder) cache(caches ...*specs.Cache) {
49 for _, c := range caches {
50 alreadyHave := false
51 for _, exist := range b.Spec.Caches {
52 if c.Name == exist.Name {
53 if !reflect.DeepEqual(c, exist) {
54 log.Fatalf("Already have cache %s with a different definition!", c.Name)
55 }
56 alreadyHave = true
57 break
58 }
59 }
60 if !alreadyHave {
61 b.Spec.Caches = append(b.Spec.Caches, c)
62 }
63 }
64 }
65
66 // cmd sets the command for the task.
67 func (b *TaskBuilder) cmd(c ...string) {
68 b.Spec.Command = c
69 }
70
71 // dimension adds the given dimensions to the task.
72 func (b *TaskBuilder) dimension(dims ...string) {
73 for _, dim := range dims {
74 if !In(dim, b.Spec.Dimensions) {
75 b.Spec.Dimensions = append(b.Spec.Dimensions, dim)
76 }
77 }
78 }
79
80 // expiration sets the expiration of the task.
81 func (b *TaskBuilder) expiration(e time.Duration) {
82 b.Spec.Expiration = e
83 }
84
85 // idempotent marks the task as idempotent.
86 func (b *TaskBuilder) idempotent() {
87 b.Spec.Idempotent = true
88 }
89
90 // cas sets the CasSpec used by the task.
91 func (b *TaskBuilder) cas(casSpec string) {
92 b.Spec.CasSpec = casSpec
93 }
94
95 // env sets the value for the given environment variable for the task.
96 func (b *TaskBuilder) env(key, value string) {
97 if b.Spec.Environment == nil {
98 b.Spec.Environment = map[string]string{}
99 }
100 b.Spec.Environment[key] = value
101 }
102
103 // envPrefixes appends the given values to the given environment variable for
104 // the task.
105 func (b *TaskBuilder) envPrefixes(key string, values ...string) {
106 if b.Spec.EnvPrefixes == nil {
107 b.Spec.EnvPrefixes = map[string][]string{}
108 }
109 for _, value := range values {
110 if !In(value, b.Spec.EnvPrefixes[key]) {
111 b.Spec.EnvPrefixes[key] = append(b.Spec.EnvPrefixes[key], value)
112 }
113 }
114 }
115
116 // addToPATH adds the given locations to PATH for the task.
117 func (b *TaskBuilder) addToPATH(loc ...string) {
118 b.envPrefixes("PATH", loc...)
119 }
120
121 // output adds the given paths as outputs to the task, which results in their
122 // contents being uploaded to the isolate server.
123 func (b *TaskBuilder) output(paths ...string) {
124 for _, path := range paths {
125 if !In(path, b.Spec.Outputs) {
126 b.Spec.Outputs = append(b.Spec.Outputs, path)
127 }
128 }
129 }
130
131 // serviceAccount sets the service account for this task.
132 func (b *TaskBuilder) serviceAccount(sa string) {
133 b.Spec.ServiceAccount = sa
134 }
135
136 // timeout sets the timeout(s) for this task.
137 func (b *TaskBuilder) timeout(timeout time.Duration) {
138 b.Spec.ExecutionTimeout = timeout
139 b.Spec.IoTimeout = timeout // With kitchen, step logs don't count toward IoTimeout.
140 }
141
142 // dep adds the given tasks as dependencies of this task.
143 func (b *TaskBuilder) dep(tasks ...string) {
144 for _, task := range tasks {
145 if !In(task, b.Spec.Dependencies) {
146 b.Spec.Dependencies = append(b.Spec.Dependencies, task)
147 }
148 }
149 }
150
151 // cipd adds the given CIPD packages to the task.
152 func (b *TaskBuilder) cipd(pkgs ...*specs.CipdPackage) {
153 for _, pkg := range pkgs {
154 alreadyHave := false
155 for _, exist := range b.Spec.CipdPackages {
156 if pkg.Name == exist.Name {
157 if !reflect.DeepEqual(pkg, exist) {
158 log.Fatalf("Already have package %s with a different definition!", pkg.Name)
159 }
160 alreadyHave = true
161 break
162 }
163 }
164 if !alreadyHave {
165 b.Spec.CipdPackages = append(b.Spec.CipdPackages, pkg)
166 }
167 }
168 }
169
170 // cipdFromDEPS adds a CIPD package, which is pinned in DEPS, to the task.
171 func (b *TaskBuilder) cipdFromDEPS(pkgName string) {
172 dep, err := deps.Get(pkgName)
173 if err != nil {
174 panic(err)
175 }
176 taskDriverPkg := &cipd.Package{
177 // Note: the DEPS parser normalizes dependency IDs, which includes
178 // stripping suffixes like "/${platform}" or ".git". When specifying a
179 // package to a Swarming task, those suffixes are necessary, so we use
180 // the passed-in package name, which we assume is correct and complete.
181 Name: pkgName,
182 Path: dep.Path,
183 Version: dep.Version,
184 }
185 b.cipd(taskDriverPkg)
186 }
187
188 // useIsolatedAssets returns true if this task should use assets which are
189 // isolated rather than downloading directly from CIPD.
190 func (b *TaskBuilder) useIsolatedAssets() bool {
191 // Only do this on the RPIs for now. Other, faster machines shouldn't
192 // see much benefit and we don't need the extra complexity, for now.
193 if b.Os("ChromeOS", "iOS") || b.MatchOs("Android") {
194 return true
195 }
196 return false
197 }
198
199 // uploadAssetCASCfg represents a task which copies a CIPD package into
200 // isolate.
201 type uploadAssetCASCfg struct {
202 alwaysIsolate bool
203 uploadTaskName string
204 path string
205 }
206
207 // assetWithVersion adds the given asset with the given version number to the
208 // task as a CIPD package.
209 func (b *TaskBuilder) assetWithVersion(assetName string, version int) {
210 pkg := &specs.CipdPackage{
211 Name: fmt.Sprintf("skia/bots/%s", assetName),
212 Path: assetName,
213 Version: fmt.Sprintf("version:%d", version),
214 }
215 b.cipd(pkg)
216 }
217
218 // asset adds the given assets to the task as CIPD packages.
219 func (b *TaskBuilder) asset(assets ...string) {
220 shouldIsolate := b.useIsolatedAssets()
221 pkgs := make([]*specs.CipdPackage, 0, len(assets))
222 for _, asset := range assets {
223 if cfg, ok := ISOLATE_ASSET_MAPPING[asset]; ok && (cfg.alwaysIsolate || shouldIsolate) {
224 b.dep(b.uploadCIPDAssetToCAS(asset))
225 } else {
226 pkgs = append(pkgs, b.MustGetCipdPackageFromAsset(asset))
227 }
228 }
229 b.cipd(pkgs...)
230 }
231
232 // usesCCache adds attributes to tasks which need bazel (via bazelisk).
233 func (b *TaskBuilder) usesBazel(hostOSArch string) {
234 archToPkg := map[string]string{
235 "linux_x64": "bazelisk_linux_amd64",
236 "mac_arm64": "bazelisk_mac_arm64",
237 "mac_x64": "bazelisk_mac_amd64",
238 "windows_x64": "bazelisk_win_amd64",
239 }
240 pkg, ok := archToPkg[hostOSArch]
241 if !ok {
242 panic("Unsupported osAndArch for bazelisk: " + hostOSArch)
243 }
244 b.cipd(b.MustGetCipdPackageFromAsset(pkg))
245 b.addToPATH(pkg)
246 b.env("USE_BAZEL_FALLBACK_VERSION", "error")
247 }
248
249 // usesCCache adds attributes to tasks which use ccache.
250 func (b *TaskBuilder) usesCCache() {
251 b.cache(CACHES_CCACHE...)
252 }
253
254 // shellsOutToBazel returns true if this task normally uses GN but some step
255 // shells out to Bazel to build stuff, e.g. rust code.
256 func (b *TaskBuilder) shellsOutToBazel() bool {
257 return b.ExtraConfig("Fontations", "RustPNG", "ICU4X")
258 }
259
260 func (b *TaskBuilder) usesCMake() {
261 archToPkg := map[string]string{
262 "Ubuntu24.04": "cmake_linux",
263 "Mac": "cmake_mac",
264 "Win": "cmake_win",
265 }
266 pkg, ok := archToPkg[b.Parts["os"]]
267 if !ok {
268 panic("Unsupported OS for cmake: " + b.Parts["os"])
269 }
270 b.cipd(b.MustGetCipdPackageFromAsset(pkg))
271 b.addToPATH(pkg + "/bin")
272 }
273
274 // usesGit adds attributes to tasks which use git.
275 func (b *TaskBuilder) usesGit() {
276 b.cache(CACHES_GIT...)
277 b.cipd(specs.CIPD_PKGS_GIT...)
278 b.addToPATH("cipd_bin_packages", "cipd_bin_packages/bin")
279 }
280
281 // usesGo adds attributes to tasks which use go. Recipes should use
282 // "with api.context(env=api.infra.go_env)".
283 func (b *TaskBuilder) usesGo() {
284 b.usesGit() // Go requires Git.
285 b.cache(CACHES_GO...)
286 pkg := b.MustGetCipdPackageFromAsset("go")
287 if b.MatchOs("Win") || b.MatchExtraConfig("Win") {
288 pkg = b.MustGetCipdPackageFromAsset("go_win")
289 pkg.Path = "go"
290 }
291 b.cipd(pkg)
292 b.addToPATH(pkg.Path + "/go/bin")
293 b.envPrefixes("GOROOT", pkg.Path+"/go")
294 }
295
296 // usesDocker adds attributes to tasks which use docker.
297 func (b *TaskBuilder) usesDocker() {
298 // The "docker" binary reads its config from $HOME/.docker/config.json which, after running
299 // "gcloud auth configure-docker", typically looks like this:
300 //
301 // {
302 // "credHelpers": {
303 // "gcr.io": "gcloud",
304 // "us.gcr.io": "gcloud",
305 // "eu.gcr.io": "gcloud",
306 // "asia.gcr.io": "gcloud",
307 // "staging-k8s.gcr.io": "gcloud",
308 // "marketplace.gcr.io": "gcloud"
309 // }
310 // }
311 //
312 // This instructs "docker" to get its GCR credentials from a credential helper [1] program
313 // named "docker-credential-gcloud" [2], which is part of the Google Cloud SDK. This program is
314 // a shell script that invokes the "gcloud" command, which is itself a shell script that probes
315 // the environment to find a viable Python interpreter, and then invokes
316 // /usr/lib/google-cloud-sdk/lib/gcloud.py. For some unknown reason, sometimes "gcloud" decides
317 // to use "/b/s/w/ir/cache/vpython/875f1a/bin/python" as the Python interpreter (exact path may
318 // vary), which causes gcloud.py to fail with the following error:
319 //
320 // ModuleNotFoundError: No module named 'contextlib'
321 //
322 // Fortunately, "gcloud" supports specifying a Python interpreter via the GCLOUDSDK_PYTHON
323 // environment variable.
324 //
325 // [1] https://docs.docker.com/engine/reference/commandline/login/#credential-helpers
326 // [2] See /usr/bin/docker-credential-gcloud on your gLinux system, which is provided by the
327 // google-cloud-sdk package.
328 b.envPrefixes("CLOUDSDK_PYTHON", "cipd_bin_packages/cpython3/bin/python3")
329
330 // As mentioned, Docker uses gcloud for authentication against GCR, and gcloud requires Python.
331 b.usesPython()
332 }
333
334 // usesGSUtil adds the gsutil dependency from CIPD and puts it on PATH.
335 func (b *TaskBuilder) usesGSUtil() {
336 b.asset("gsutil")
337 b.addToPATH("gsutil/gsutil")
338 }
339
340 // needsFontsForParagraphTests downloads the skparagraph CIPD package to
341 // a subdirectory of the Skia checkout: resources/extra_fonts
342 func (b *TaskBuilder) needsFontsForParagraphTests() {
343 pkg := b.MustGetCipdPackageFromAsset("skparagraph")
344 pkg.Path = "skia/resources/extra_fonts"
345 b.cipd(pkg)
346 }
347
348 // recipeProp adds the given recipe property key/value pair. Panics if
349 // getRecipeProps() was already called.
350 func (b *TaskBuilder) recipeProp(key, value string) {
351 if b.recipeProperties == nil {
352 log.Fatal("taskBuilder.recipeProp() cannot be called after taskBuilder.getRecipeProps()!")
353 }
354 b.recipeProperties[key] = value
355 }
356
357 // recipeProps calls recipeProp for every key/value pair in the given map.
358 // Panics if getRecipeProps() was already called.
359 func (b *TaskBuilder) recipeProps(props map[string]string) {
360 for k, v := range props {
361 b.recipeProp(k, v)
362 }
363 }
364
365 // getRecipeProps returns JSON-encoded recipe properties. Subsequent calls to
366 // recipeProp[s] will panic, to prevent accidentally adding recipe properties
367 // after they have been added to the task.
368 func (b *TaskBuilder) getRecipeProps() string {
369 props := make(map[string]interface{}, len(b.recipeProperties)+2)
370 // TODO(borenet): I'm not sure why we supply the original task name
371 // and not the upload task name. We should investigate whether this is
372 // needed.
373 buildername := b.Name
374 if b.Role("Upload") {
375 buildername = strings.TrimPrefix(buildername, "Upload-")
376 }
377 props["buildername"] = buildername
378 props["$kitchen"] = struct {
379 DevShell bool `json:"devshell"`
380 GitAuth bool `json:"git_auth"`
381 }{
382 DevShell: true,
383 GitAuth: true,
384 }
385 for k, v := range b.recipeProperties {
386 props[k] = v
387 }
388 b.recipeProperties = nil
389 return marshalJson(props)
390 }
391
392 // usesPython adds attributes to tasks which use python.
393 func (b *TaskBuilder) usesPython() {
394 b.cipd(cipd.PkgsPython...)
395 b.addToPATH(
396 "cipd_bin_packages/cpython3",
397 "cipd_bin_packages/cpython3/bin",
398 )
399 b.cache(&specs.Cache{
400 Name: "vpython3",
401 Path: "cache/vpython3",
402 })
403 b.envPrefixes("VPYTHON_VIRTUALENV_ROOT", "cache/vpython3")
404 b.env("VPYTHON_LOG_TRACE", "1")
405 }
406
407 func (b *TaskBuilder) usesXCode() {
408 b.cipd(&specs.CipdPackage{
409 Name: "infra/tools/mac_toolchain/${platform}",
410 Path: "mac_toolchain",
411 // When this is updated, also update
412 // https://skia.googlesource.com/skcms.git/+/f1e2b45d18facbae2dece3aca673fe1603077846/infra/bots/gen_tasks.go#56
413 // and
414 // https://skia.googlesource.com/skia.git/+/main/infra/bots/recipe_modules/xcode/api.py#38
415 Version: "git_revision:0cb1e51344de158f72524c384f324465aebbcef2",
416 })
417 b.Spec.Caches = append(b.Spec.Caches, &specs.Cache{
418 Name: "xcode",
419 Path: "cache/Xcode.app",
420 })
421 }
422
423 func (b *TaskBuilder) usesLUCIAuth() {
424 b.cipd(CIPD_PKG_LUCI_AUTH)
425 b.addToPATH("cipd_bin_packages", "cipd_bin_packages/bin")
426 }
427
428 func (b *TaskBuilder) usesNode() {
429 // It is very important when including node via CIPD to also add it to the PATH of the
430 // taskdriver or mysterious things can happen when subprocesses try to resolve node/npm.
431 b.asset("node")
432 b.addToPATH("node/node/bin")
433 }
434
435 func (b *TaskBuilder) needsLottiesWithAssets() {
436 // This CIPD package was made by hand with the following invocation:
437 // cipd create -name skia/internal/lotties_with_assets -in ./lotties/ -tag version:2
438 // cipd acl-edit skia/internal/lotties_with_assets -reader group:project-skia-external-task-accounts
439 // cipd acl-edit skia/internal/lotties_with_assets -reader user:[email protected]
440 // Where lotties is a hand-selected set of lottie animations and (optionally) assets used in
441 // them (e.g. fonts, images).
442 // Each test case is in its own folder, with a data.json file and an optional images/ subfolder
443 // with any images/fonts/etc loaded by the animation.
444 // Note: If you are downloading the existing package to update them, remove the CIPD-generated
445 // .cipdpkg subfolder before trying to re-upload it.
446 // Note: It is important that the folder names do not special characters like . (), &, as
447 // the Android filesystem does not support folders with those names well.
448 b.cipd(&specs.CipdPackage{
449 Name: "skia/internal/lotties_with_assets",
450 Path: "lotties_with_assets",
451 Version: "version:4",
452 })
453 }
454
455 // goPlatform derives the GOOS and GOARCH for this task.
456 func (b *TaskBuilder) goPlatform() (string, string) {
457 os := ""
458 if b.IsWindows() {
459 os = "windows"
460 } else if b.IsMac() {
461 os = "darwin"
462 } else if b.IsLinux() || b.MatchOs("Android", "ChromeOS", "iOS") {
463 // Tests on Android/ChromeOS/iOS are hosted on RPI.
464 os = "linux"
465 } else {
466 panic("unknown GOOS for " + b.Name)
467 }
468
469 arch := "amd64"
470 if b.Role("Upload") {
471 arch = "amd64"
472 } else if b.MatchArch("Arm64") || b.MatchBazelHost("on_rpi") || b.MatchOs("Android", "ChromeOS", "iOS") {
473 // Tests on Android/ChromeOS/iOS are hosted on RPI.
474 // WARNING: This assumption is not necessarily true with Android devices
475 // hosted in other environments.
476 arch = "arm64"
477 } else if b.IsLinux() || b.IsMac() || b.IsWindows() {
478 arch = "amd64"
479 } else {
480 panic("unknown GOARCH for " + b.Name)
481 }
482 return os, arch
483 }
484
485 // taskDriver sets the task up to use the given task driver, either by depending
486 // on the BuildTaskDrivers task to build the task driver immediately before use,
487 // or by pulling the pre-built task driver from CIPD. Returns the path to the
488 // task driver binary, which can be used directly as part of the task's command.
489 func (b *TaskBuilder) taskDriver(name string, preBuilt bool) string {
490 if preBuilt {
491 // We assume all task drivers are built under the "skia/tools" prefix
492 // and, being built per-platform, use the ${platform} suffix to
493 // automatically select the correct platform when the task runs.
494 b.cipdFromDEPS("skia/tools/" + name + "/${platform}")
495 // DEPS specifies that task drivers belong in the "task_drivers"
496 // directory.
497 return "task_drivers/" + name
498 } else {
499 os, arch := b.goPlatform()
500 b.dep(b.buildTaskDrivers(os, arch))
501 return "./" + name
502 }
503 }