Sign in

Search issue titles and bodies, change requests and comments. Private repositories you cannot read are not included.

vole
Site
Clone

Read only, no credentials:

https://rodent.software/vole.git

Write over SSH with a registered key:

git clone ssh://git@rodent.software/vole.git

Self-hosted forge that lives in your Git repo.

Blame · ci/container/backend.go

Line attribution on main · 555 line(s)

de3eec16
Keenan Nemetz
2h ago
1 package container
2
3 // ci/container as an execute.Executor.
4 //
5 // The package below this file is a thin CLI wrapper: it turns a Config and a Spec
6 // into `docker run` arguments and runs them. This file is the part a caller talks
7 // to: it owns the per-attempt orchestration (services, the private network they
8 // share, and the job's container), the image build and its lease-keeping, and the
9 // cleanup of what a killed runner left behind. It is the OCI implementation of
10 // ci/execute, and the reason that interface exists is a second implementation whose
11 // "image" is a virtual machine disk rather than a layer stack.
12 //
13 // Keeping the orchestration here rather than in the caller is what makes a second
14 // backend possible at all. A job's services and network are created differently by
15 // a hypervisor — usually not at all — so a caller that created them itself would
16 // have to know which backend it was talking to.
17
18 import (
19 "context"
20 "errors"
21 "fmt"
22 "io"
23 "os"
24 "os/exec"
25 "path/filepath"
26 "strconv"
27 "strings"
28 "sync"
29 "time"
30
31 "rodent.software/vole/ci"
32 "rodent.software/vole/ci/execute"
33 )
34
35 // imageBuildTimeout bounds one image-file build. A definition that needs longer is
36 // a definition that will not finish on a runner at all, and the bound is what keeps
37 // a hung build from holding a lease until the job's own timeout.
38 const imageBuildTimeout = 30 * time.Minute
39
40 // Backend is the container runtime as an execute.Executor. It is created once per
41 // runner process: the build and prune coordination below is shared by every slot.
42 type Backend struct {
43 cfg Config
44 // id and pid label what this process creates, so a restarted runner can tell its
45 // own leftovers from another runner's work under the same --dir.
46 id string
47 pid int
48 // builds is shared by every slot, so two jobs that name the same image-file build
49 // it once. A nil value (a Backend built by hand in a test) builds alone.
50 builds *imageBuilds
51 // images keeps a prune pass away from an image a job is resolving or starting.
52 images *imageUse
53 }
54
55 // New returns the container backend for these settings. id must be stable for one
56 // cache directory and one instance, which is what lets Reconcile find this runner's
57 // leftovers after a restart.
58 func New(cfg Config, id string) *Backend {
59 return &Backend{
60 cfg: cfg,
61 id: id,
62 pid: os.Getpid(),
63 builds: &imageBuilds{},
64 images: &imageUse{},
65 }
66 }
67
68 // Config is the runtime settings this backend was built with. A caller that has to
69 // print one of them — the runner's startup line names the runtime — reads it here
70 // rather than keeping a second copy.
71 func (b *Backend) Config() Config { return b.cfg }
72
73 // Capabilities implements execute.Executor. A container always has a network and
74 // always enforces what it was given; whether it may offer a bridge is the operator's
75 // decision, taken at startup.
76 func (b *Backend) Capabilities() execute.Capabilities {
77 return execute.Capabilities{
78 Backend: b.cfg.Runtime,
79 Network: b.cfg.Network == "bridge",
80 Services: true,
81 Limits: true,
82 Root: RunsAsRoot(b.cfg),
83 }
84 }
85
86 // Probe implements execute.Executor.
87 func (b *Backend) Probe(ctx context.Context) error { return Probe(ctx, b.cfg) }
88
89 // Reconcile implements execute.Executor: containers first, then the networks they
90 // were attached to, because a network with a member cannot be removed.
91 func (b *Backend) Reconcile(context.Context) error {
92 b.cleanupStaleContainers()
93 b.cleanupStaleNetworks()
94 return nil
95 }
96
97 // Prune implements execute.Executor. A pass gives way to a job that is preparing or
98 // starting an image: the lease is the thing that must not lose, and a skipped pass
99 // costs nothing because the next beat tries again.
100 func (b *Backend) Prune(ctx context.Context, age time.Duration) (int64, error) {
101 release, ok := b.images.exclusive()
102 if !ok {
103 return 0, nil
104 }
105 defer release()
106 // --container-pull never means this runner may have no network to fetch an image
107 // again, so every tagged image is kept. Dangling layers are still unreachable by
108 // any tag or container and are safe to reclaim.
109 return PruneImages(ctx, b.cfg, age, b.cfg.Pull != "never")
110 }
111
112 // Prepare implements execute.Executor. A registry reference is used as written; an
113 // image-file definition is built locally and cached under a digest tag, so a second
114 // job with the same definition reuses the first build.
115 func (b *Backend) Prepare(ctx context.Context, in execute.Image, out io.Writer, run execute.Runner) (string, func(), error) {
116 // Hold the image in use until the job's container is up: a prune pass takes the
117 // same guard exclusively, so a tag this job is about to run cannot disappear
118 // between the two. A running container already protects its image from the
119 // runtime's own prune; this closes the gap before one exists.
120 release := b.images.hold()
121 if in.Ref != "" {
122 if err := ci.ValidImageRef(in.Ref); err != nil {
123 release()
124 return "", nil, fmt.Errorf("the job image: %w", err)
125 }
126 return in.Ref, release, nil
127 }
128 if in.Definition == "" {
129 release()
130 return "", nil, fmt.Errorf("image-file %q has no pinned definition", in.File)
131 }
132 if in.Digest == "" {
133 release()
134 return "", nil, fmt.Errorf("image-file %q has no definition digest", in.File)
135 }
136 tag := ImageTag(in.File, in.Digest)
137 // The pull policy is the operator's, not the job's: it is a setting of this
138 // machine ("this runner may have no network"), which is why it is not part of
139 // the image the workflow asked for.
140 if b.cfg.Pull != "always" && Exists(b.cfg.Runtime, tag) {
141 fmt.Fprintf(out, "image-file %s: using cached %s\n", in.File, tag)
142 return tag, release, nil
143 }
144 if b.builds == nil {
145 // A Backend built by hand (a test, or a caller that never validated) has no
146 // shared state to join; building alone is the behaviour before --jobs.
147 if err := b.buildImage(ctx, in, tag, out, run); err != nil {
148 release()
149 return "", nil, err
150 }
151 return tag, release, nil
152 }
153
154 build, mine := b.builds.join(tag)
155 if mine {
156 err := b.buildImage(ctx, in, tag, out, run)
157 build.err = err
158 // Leave before closing, so a job that arrives after this one has taken the
159 // finished entry starts a fresh build instead of reading an answer about a
160 // digest it did not ask for. Waiters already on done are unaffected.
161 b.builds.leave(tag)
162 close(build.done)
163 if err != nil {
164 release()
165 return "", nil, err
166 }
167 return tag, release, nil
168 }
169
170 // Another slot is building it. The line goes in this job's log so a reader knows
171 // why the steps have not started.
172 fmt.Fprintf(out, "image-file %s: %s is being built by another job; waiting\n", in.File, tag)
173 if err := waitForBuild(build, out, run); err != nil {
174 release()
175 return "", nil, err
176 }
177 if build.err != nil {
178 // A failed build is this job's failure too: the same definition would fail the
179 // same way, and a second attempt would only spend the time again. A lease that
180 // went away belongs to the builder, though, and means only that nobody may run
181 // this image on this runner's word.
182 release()
183 if errors.Is(build.err, execute.ErrLeaseLost) || errors.Is(build.err, execute.ErrCanceled) {
184 return "", nil, build.err
185 }
186 return "", nil, fmt.Errorf("image-file %q: %w", in.File, build.err)
187 }
188 return tag, release, nil
189 }
190
191 // buildImage renders the pinned definition, builds it, and tags the result by its
192 // digest. The build goes through run so a half-hour build keeps its lease.
193 func (b *Backend) buildImage(ctx context.Context, in execute.Image, tag string, out io.Writer, run execute.Runner) error {
194 dockerfile, err := ci.RenderImage(in.Definition)
195 if err != nil {
196 return fmt.Errorf("image-file %q: %w", in.File, err)
197 }
198 dir, err := os.MkdirTemp("", "vole-image-*")
199 if err != nil {
200 return err
201 }
202 defer os.RemoveAll(dir)
203 if err := os.WriteFile(filepath.Join(dir, "Dockerfile"), []byte(dockerfile), 0o600); err != nil {
204 return err
205 }
206
207 args := []string{"build", "-t", tag, "-f", filepath.Join(dir, "Dockerfile"), dir}
208 switch {
209 case b.cfg.Pull == "always" && b.cfg.Runtime == "podman":
210 args = append(args, "--pull=always")
211 case b.cfg.Pull == "always":
212 args = append(args, "--pull")
213 }
214 ctx, cancel := context.WithTimeout(ctx, imageBuildTimeout)
215 defer cancel()
216 code, lost, canceled := run.Run(ctx, exec.CommandContext(ctx, b.cfg.Runtime, args...), out)
217 if lost {
218 return execute.ErrLeaseLost
219 }
220 if canceled {
221 return execute.ErrCanceled
222 }
223 if ctx.Err() == context.DeadlineExceeded {
224 return fmt.Errorf("building image-file %q timed out after %s", in.File, imageBuildTimeout)
225 }
226 if code != 0 {
227 return fmt.Errorf("building image-file %q exited %d", in.File, code)
228 }
229 if !Exists(b.cfg.Runtime, tag) {
230 return fmt.Errorf("building image-file %q produced no image tagged %s", in.File, tag)
231 }
232 fmt.Fprintf(out, "\nimage-file %s: built %s\n", in.File, tag)
233 return nil
234 }
235
236 // Start implements execute.Executor. The returned sandbox is never nil: when Start
237 // fails partway, it holds whatever was created before the failure so the caller can
238 // collect the services' output and stop them. A caller that gets an error must
239 // still call Stop.
240 func (b *Backend) Start(ctx context.Context, spec execute.Spec) (execute.Sandbox, error) {
241 sb := &sandbox{cfg: b.cfg, name: spec.Name, secrets: spec.SecretsFile}
242 if spec.Work.Host != "" {
243 sb.work, sb.workPath = spec.Work.Host, spec.Work.Path
244 }
245 if err := validateSpec(spec); err != nil {
246 return sb, err
247 }
248 // The caller resolves the job's `network:` against this executor's own offering,
249 // so what arrives here is what the job gets; only a job that declared services
250 // gets something else, because they need a network of their own.
251 cfg := b.cfg
252 cfg.Network = spec.Network
253 if spec.Memory != "" {
254 cfg.Memory = spec.Memory
255 }
256 if spec.CPUs != "" {
257 cfg.CPUs = spec.CPUs
258 }
259 // The attempt's labels carry this process's identity, not the caller's: they are
260 // what Reconcile matches on, and a caller that forgot the pid would make a live
261 // sibling's containers look abandoned.
262 labels := make(map[string]string, len(spec.Labels)+3)
263 for k, v := range spec.Labels {
264 labels[k] = v
265 }
266 labels["vole.runner"] = "1"
267 labels["vole.runner.id"] = b.id
268 labels["vole.runner.pid"] = strconv.Itoa(b.pid)
269 // Services need a network of their own so their declared names resolve inside
270 // the attempt and nowhere else. The job joins that network instead of the runtime
271 // default, which is what the per-attempt name is for.
272 if len(spec.Services) > 0 {
273 net, err := CreateNetwork(ctx, cfg, spec.Name+"-net", labels)
274 if err != nil {
275 return sb, err
276 }
277 sb.network = net
278 cfg.Network = net.Name()
279 for _, svc := range spec.Services {
280 c, err := StartService(cfg, ServiceSpec{
281 Name: spec.Name + "-svc-" + svc.ID,
282 Alias: svc.ID,
283 Image: svc.Image,
284 Env: svc.Env,
285 Labels: labels,
286 })
287 if err != nil {
288 return sb, err
289 }
290 sb.services = append(sb.services, c)
291 sb.serviceIDs = append(sb.serviceIDs, svc.ID)
292 }
293 // A service that exited before the steps begin is a failed job, not a
294 // connection error in the first step that talks to it.
295 for i, c := range sb.services {
296 running, err := c.Running(ctx)
297 if err != nil {
298 return sb, fmt.Errorf("service %s: %w", spec.Services[i].ID, err)
299 }
300 if !running {
301 return sb, fmt.Errorf("service %s exited before the steps started", spec.Services[i].ID)
302 }
303 }
304 }
305 mounts := make([]Mount, 0, len(spec.Shares))
306 for _, m := range spec.Shares {
307 mounts = append(mounts, Mount{Host: m.Host, Path: m.Path})
308 }
309 job, err := Start(cfg, Spec{
310 Image: spec.Image,
311 Name: spec.Name,
312 Work: spec.Work.Host,
313 Labels: labels,
314 Mounts: mounts,
315 Env: spec.Env,
316 SecretsFile: spec.SecretsFile,
317 })
318 if err != nil {
319 return sb, err
320 }
321 sb.job = job
322 return sb, nil
323 }
324
325 // validateSpec refuses a spec whose paths cannot be passed as `--volume` arguments.
326 // The separator is a colon, so a path containing one would be read as an extra
327 // field; a NUL or a newline would end or split the argument the runtime sees. The
328 // caller builds these paths itself, so this is the check that keeps that assumption
329 // true rather than the check that discovers it.
330 func validateSpec(spec execute.Spec) error {
331 if spec.Network != ci.NetworkNone && spec.Network != ci.NetworkBridge {
332 return fmt.Errorf("network %q is not a network mode", spec.Network)
333 }
334 paths := []string{spec.Work.Host, spec.Work.Path}
335 for _, m := range spec.Shares {
336 paths = append(paths, m.Host, m.Path)
337 }
338 if spec.SecretsFile != "" {
339 if !strings.HasPrefix(spec.SecretsFile, "/") {
340 return fmt.Errorf("the secrets file %q is not a path in the environment", spec.SecretsFile)
341 }
342 paths = append(paths, spec.SecretsFile)
343 }
344 for _, p := range paths {
345 if p == "" {
346 return fmt.Errorf("container path is empty")
347 }
348 if strings.ContainsAny(p, ":\x00\r\n") {
349 return fmt.Errorf("container path %q contains a character a volume argument cannot carry", p)
350 }
351 }
352 return nil
353 }
354
355 // sandbox is one job's container, the services started beside it, and the network
356 // they share.
357 type sandbox struct {
358 cfg Config
359 // name is the attempt's environment name, used for derived names and messages.
360 name string
361 // work is the job tree on the host and workPath is where the job sees it. The
362 // host path is also the client's working directory, which lets a test runtime
363 // execute a step in the same place without pretending to be a container.
364 work string
365 workPath string
366 secrets string
367 job *Container
368 services []*Container
369 // serviceIDs are the workflow's names for the services, parallel to services.
370 serviceIDs []string
371 network *Network
372 }
373
374 // Exec implements execute.Sandbox.
375 func (s *sandbox) Exec(ctx context.Context, script string) *exec.Cmd {
376 script = execute.StepScript(script, s.secrets)
377 work := s.workPath
378 if work == "" {
379 work = "/workspace"
380 }
381 cmd := exec.CommandContext(ctx, s.cfg.Runtime, "exec",
382 "-w", work, s.name, "/bin/sh", "-c", script)
383 cmd.Dir = s.work
384 return cmd
385 }
386
387 // Stop implements execute.Sandbox.
388 func (s *sandbox) Stop() { s.StopJob(); s.StopServices(); s.removeNetwork() }
389
390 // StopJob implements execute.Sandbox.
391 func (s *sandbox) StopJob() {
392 if s.job != nil {
393 s.job.Stop()
394 s.job = nil
395 }
396 }
397
398 // StopServices ends the services and leaves the network for Stop.
399 func (s *sandbox) StopServices() {
400 for _, svc := range s.services {
401 svc.Stop()
402 }
403 s.services, s.serviceIDs = nil, nil
404 }
405
406 func (s *sandbox) removeNetwork() {
407 if s.network != nil {
408 ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
409 _ = s.network.Remove(ctx)
410 cancel()
411 s.network = nil
412 }
413 }
414
415 // ServiceLogs implements execute.Sandbox. A service whose runtime will not answer is
416 // skipped: this runs on a path that is already failing.
417 func (s *sandbox) ServiceLogs(ctx context.Context, max int64) []execute.ServiceLog {
418 if max <= 0 {
419 max = execute.MaxServiceLogBytes
420 }
421 out := make([]execute.ServiceLog, 0, len(s.services))
422 for i, svc := range s.services {
423 ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
424 data, err := svc.Logs(ctx, max)
425 cancel()
426 if err != nil || len(data) == 0 {
427 continue
428 }
429 out = append(out, execute.ServiceLog{ID: s.serviceIDs[i], Data: data})
430 }
431 return out
432 }
433
434 // cleanupStaleContainers removes containers from an earlier process that used this
435 // runner's cache. Normally the executor removes its own container, but a killed
436 // runner leaves the keepalive process behind.
437 func (b *Backend) cleanupStaleContainers() {
438 out, err := exec.Command(b.cfg.Runtime, "ps", "-a",
439 "--filter", "label=vole.runner.id="+b.id,
440 "--format", `{{.ID}} {{.Label "vole.runner.pid"}}`).Output()
441 if err != nil {
442 return // the first job will report a runtime problem with more context
443 }
444 var stale []string
445 for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
446 fields := strings.Fields(line)
447 if len(fields) == 0 {
448 continue
449 }
450 pid, _ := strconv.Atoi(fields[len(fields)-1])
451 if pid > 0 && processAlive(pid) {
452 continue // another runner using the same cache is still working
453 }
454 stale = append(stale, fields[0])
455 }
456 if len(stale) == 0 {
457 return
458 }
459 args := append([]string{"rm", "-f"}, stale...)
460 _ = exec.Command(b.cfg.Runtime, args...).Run()
461 }
462
463 // cleanupStaleNetworks removes networks a killed runner left behind. It runs after
464 // cleanupStaleContainers, because a network with a member cannot be removed.
465 func (b *Backend) cleanupStaleNetworks() {
466 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
467 defer cancel()
468 names, err := ListNetworks(ctx, b.cfg, "vole.runner.id="+b.id)
469 if err != nil {
470 return // the first job will report a runtime problem with more context
471 }
472 for _, name := range names {
473 labels, err := NetworkLabels(ctx, b.cfg, name)
474 if err != nil {
475 continue
476 }
477 pid, _ := strconv.Atoi(labels["vole.runner.pid"])
478 if pid > 0 && processAlive(pid) {
479 continue // another runner using the same cache is still working
480 }
481 _ = RemoveNetwork(ctx, b.cfg, name)
482 }
483 }
484
485 // One build per digest, per process.
486 //
487 // With --jobs, two slots can lease jobs that name the same image-file: same bytes,
488 // same tag, twice the CPU and twice the disk, and two processes racing to tag the
489 // result. The first slot builds; the others wait on the same answer.
490 //
491 // Waiting is not free. A build can run for half an hour, and a runner that stops
492 // hearing from the queue loses the run it is holding, so a waiter keeps its lease
493 // alive exactly as a build of its own would have, and stops when the lease or the
494 // run goes away.
495 //
496 // Two runners sharing a --dir can still both build the digest. That is waste, not
497 // damage: the definition is pinned by digest, so both builds produce the same image
498 // under the same tag. Serialising that too would need a lock file per digest beside
499 // the caches, which is more machinery than the case is worth.
500
501 // imageBuild is one in-flight build of a digest. done closes when the attempt has an
502 // answer, success or failure; err is that answer.
503 type imageBuild struct {
504 done chan struct{}
505 err error
506 }
507
508 // imageBuilds is the set of builds this process has in flight, shared by its slots.
509 type imageBuilds struct {
510 mu sync.Mutex
511 running map[string]*imageBuild
512 }
513
514 // join makes this caller the builder of tag, or hands it the build already running.
515 func (b *imageBuilds) join(tag string) (build *imageBuild, mine bool) {
516 b.mu.Lock()
517 defer b.mu.Unlock()
518 if cur, ok := b.running[tag]; ok {
519 return cur, false
520 }
521 if b.running == nil {
522 b.running = make(map[string]*imageBuild)
523 }
524 build = &imageBuild{done: make(chan struct{})}
525 b.running[tag] = build
526 return build, true
527 }
528
529 // leave forgets a finished build, so the next job that wants the digest asks the
530 // runtime again — which is also how an image somebody deleted gets rebuilt.
531 func (b *imageBuilds) leave(tag string) {
532 b.mu.Lock()
533 defer b.mu.Unlock()
534 delete(b.running, tag)
535 }
536
537 // waitForBuild waits for another slot's build, keeping this job's lease alive for as
538 // long as a build of its own would have. Beat blocks for one lease interval, so the
539 // published result is noticed within one beat of the builder finishing.
540 func waitForBuild(build *imageBuild, out io.Writer, run execute.Runner) error {
541 for {
542 select {
543 case <-build.done:
544 return nil
545 default:
546 }
547 held, canceled := run.Beat(out)
548 if canceled {
549 return execute.ErrCanceled
550 }
551 if !held {
552 return execute.ErrLeaseLost
553 }
554 }
555 }