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.

Put job execution behind an interface

de3eec162f93a697575c8bc756bd496fe4020376 · Keenan Nemetz · 2h ago · parent f784d769

Put job execution behind an interface

Job execution was container-shaped all the way into the runner: ci/agent
created the network, started the services and the job container, and held
*container.Container and *container.Network values directly, and
`vole workflow run` kept its own copy of the same orchestration. The only
abstraction was Config.Runtime, a string naming one of three flag-compatible
CLIs, which is enough for docker, podman and nerdctl and nothing else.

ci/execute is that seam. An Executor prepares the job's image, starts its
environment, runs one step while the caller keeps the lease alive, stops it,
reclaims what a killed runner left behind, and bounds its own storage. A
Sandbox is one job's environment: the job, the services beside it, and the
network they share. Capabilities is what a backend can honour, so a job that
asks for a network or for services is refused before it starts rather than
quietly given less.

ci/container implements it and takes over the orchestration that was in
ci/agent and cmd/vole: the per-attempt network, the service containers and
their log collection, the stale-container and stale-network reclamation, and
the image build and prune coordination. The isolation flags are unchanged.

This is the boundary a virtual-machine backend needs: a macOS guest behind
Tart (#356), a Windows guest, or a Linux microVM disagree with a container
about pids limits, user namespaces, tmpfs, capabilities and mounts, so they
cannot be expressed as another runtime string. Nothing about the image or
workflow schema changes here.

closes: 01M8Z2M9PVKPNH923S3VJ5FR5E

ci/agent/sandbox.go +48−186

@@ -1,57 +1,47 @@
1 1 package agent
2 2
3 // Container execution for one job.
3 // Execution for one job, as the runner sees it.
4 4 //
5 // The runner process stays on the host: it holds the SSH key and the trusted Git
6 // cache, leases work, publishes the record, and uploads artifacts. The workflow
7 // steps run in a container built from the image the job names. One container per
8 // job is the isolation boundary: a job cannot see the runner's key, and the next
9 // job starts with a clean container and a fresh job tree.
5 // The runner process stays on the host: it holds the SSH key, the trusted Git
6 // cache, the job cache, and the result channel. What runs the steps is an
7 // execute.Executor, and this file is the part of the runner that decides whether a
8 // job may be handed to it. Everything an executor does — the container, the guest,
9 // the network, the services — lives behind that interface, so adding a backend does
10 // not change the lease, the log, the cache, or the record.
10 11 //
11 // The image is part of the workflow, so a job carries the environment it needs.
12 // A custom .vole/images definition is built by the runner before the container
13 // starts; a registry reference is used as written.
14 //
15 // The container itself lives in ci/container, which `vole workflow run` shares, so
16 // a local run and a pushed run cannot disagree about how a step executes.
12 // A runner's own offering is what decides the answer here: a job that asks for a
13 // network or for services only goes to a machine whose executor can give one.
17 14
18 15 import (
19 "context"
20 16 "crypto/sha256"
21 17 "fmt"
22 "io"
23 "os"
24 "os/exec"
25 "strconv"
26 18 "strings"
27 "time"
28 19
29 20 "rodent.software/vole/ci"
30 21 "rodent.software/vole/ci/container"
22 "rodent.software/vole/ci/execute"
31 23 )
32 24
33 // runnerBox is the validated container settings plus the identity this runner
34 // process uses to find containers a killed predecessor left behind, and the builds
35 // it has in flight.
25 // runnerBox is the executor this runner leases for, the settings it was started
26 // with, and the identity this process uses to find the work a killed predecessor
27 // left behind.
36 28 type runnerBox struct {
37 container.Config
38 id string
39 pid int
40 // builds is shared by every slot in the process, so two jobs that name the same
41 // image-file build it once. Nil means the caller never validated these options,
42 // which only a test does.
43 builds *imageBuilds
44 // images keeps a prune pass away from an image a job is resolving or starting.
45 // It is shared with the trimmer, which lives in Run, for the length of the
46 // process.
47 images *imageUse
29 exec execute.Executor
30 caps execute.Capabilities
31 // cfg is the container settings as given: the runner's own flags, kept for the
32 // messages that name them. What executes a job is exec.
33 cfg container.Config
34 // id is one stable id per cache directory, derived from the cache and the
35 // instance, so a restarted runner recognises its own leftovers.
36 id string
48 37 }
49 38
50 // containerOptions validates the runner's container settings and fills in the
51 // defaults. It runs before the runner connects, so a missing runtime or an invalid
52 // option is a startup error rather than a job that fails mysteriously after it has
53 // been leased.
54 func containerOptions(opts Options, cache string) (runnerBox, error) {
39 // newRunnerBox builds the executor for these options.
40 //
41 // This function is the one place a second backend is added. A hypervisor is another
42 // execute.Executor; the flags that describe it, the capability check below, and
43 // nothing else in the runner has to change for it.
44 func newRunnerBox(opts Options, cache string) (runnerBox, error) {
55 45 cfg, err := container.Validate(container.Config{
56 46 Runtime: strings.TrimSpace(opts.ContainerRuntime),
57 47 Network: strings.TrimSpace(opts.ContainerNetwork),
@@ -67,175 +57,47 @@ func containerOptions(opts Options, cache string) (runnerBox, error) {
67 57 return runnerBox{}, err
68 58 }
69 59 // One stable id per cache directory: the cache belongs to a runner, and the id
70 // lets a restarted runner find containers a killed predecessor left behind.
60 // lets a restarted runner find what a killed predecessor left behind.
71 61 sum := sha256.Sum256([]byte(cache + "\x00" + opts.Remote))
72 return runnerBox{
73 Config: cfg,
74 id: fmt.Sprintf("%x", sum[:6]),
75 pid: os.Getpid(),
76 builds: &imageBuilds{},
77 images: &imageUse{},
78 }, nil
62 id := fmt.Sprintf("%x", sum[:6])
63 b := container.New(cfg, id)
64 return runnerBox{exec: b, caps: b.Capabilities(), cfg: cfg, id: id}, nil
79 65 }
80 66
81 // networkFor is the container settings for one job. A job that names a network gets
67 // networkFor is the network policy for one job. A job that names a network gets
82 68 // exactly that: `network: none` withholds the network even on a runner that could
83 69 // give one, and `network: bridge` is refused here on a runner that cannot, because
84 70 // running it without the network it asked for would fail later and less clearly than
85 71 // saying so at the start. A job that names nothing gets the runner's own default,
86 72 // which is what every workflow meant before the field existed.
87 func (b runnerBox) networkFor(job *runnerJob) (container.Config, error) {
88 cfg := b.Config
89 // A service is reached over the job's network. A job that declares one without
90 // asking for bridge would otherwise get a network its workflow never requested,
91 // or wait forever on a runner whose default is none, so it is refused here as
92 // well as at push time.
73 func (b runnerBox) networkFor(job *runnerJob) (string, error) {
93 74 if len(job.Services) > 0 && job.Network != ci.NetworkBridge {
94 return cfg, fmt.Errorf("job %s declares services but not network: bridge", job.ID)
75 return "", fmt.Errorf("job %s declares services but not network: bridge", job.ID)
76 }
77 if len(job.Services) > 0 && !b.caps.Services {
78 return "", fmt.Errorf("job %s declares services, which %s cannot start beside a job",
79 job.ID, b.caps.Backend)
95 80 }
96 81 if job.Network == "" {
97 return cfg, nil
82 return b.cfg.Network, nil
98 83 }
99 84 if err := ci.ValidNetwork(job.Network); err != nil {
100 return cfg, fmt.Errorf("job %s: %w", job.ID, err)
85 return "", fmt.Errorf("job %s: %w", job.ID, err)
101 86 }
102 if job.Network == ci.NetworkBridge && cfg.Network != ci.NetworkBridge {
103 return cfg, fmt.Errorf("job %s asks for network: bridge but this runner was started with "+
104 "--container-network %s, so it cannot provide one", job.ID, cfg.Network)
87 if job.Network == ci.NetworkBridge && !b.caps.Network {
88 return "", fmt.Errorf("job %s asks for network: bridge but this runner cannot provide one "+
89 "with %s", job.ID, b.caps.Backend)
105 90 }
106 cfg.Network = job.Network
107 return cfg, nil
91 return job.Network, nil
108 92 }
109 93
110 // labels are how a container says which runner and run it belongs to.
94 // labels say which run something belongs to. The executor adds its own machine and
95 // process identity, because those are what it reconciles on and a caller cannot know
96 // them; a backend with no such notion may ignore the set entirely.
111 97 func (b runnerBox) labels(job *runnerJob) map[string]string {
112 return map[string]string{
113 "vole.runner": "1",
114 "vole.runner.id": b.id,
115 "vole.runner.pid": strconv.Itoa(b.pid),
116 "vole.run": job.ID,
117 }
98 return map[string]string{"vole.run": job.ID}
118 99 }
119 100
120 101 func containerName(box runnerBox, job *runnerJob) string {
121 102 return fmt.Sprintf("vole-%s-%s-%d", box.id, strings.ToLower(job.ID), job.Attempt)
122 103 }
123
124 // cleanupStaleContainers removes containers from an earlier process that used this
125 // runner's cache. Normally the executor removes its own container, but a killed
126 // runner leaves the keepalive process behind.
127 func cleanupStaleContainers(cfg runnerBox) {
128 out, err := exec.Command(cfg.Runtime, "ps", "-a",
129 "--filter", "label=vole.runner.id="+cfg.id,
130 "--format", `{{.ID}} {{.Label "vole.runner.pid"}}`).Output()
131 if err != nil {
132 return // the first job will report a runtime problem with more context
133 }
134 var stale []string
135 for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
136 fields := strings.Fields(line)
137 if len(fields) == 0 {
138 continue
139 }
140 pid, _ := strconv.Atoi(fields[len(fields)-1])
141 if pid > 0 && processAlive(pid) {
142 continue // another runner using the same cache is still working
143 }
144 stale = append(stale, fields[0])
145 }
146 if len(stale) == 0 {
147 return
148 }
149 args := append([]string{"rm", "-f"}, stale...)
150 _ = exec.Command(cfg.Runtime, args...).Run()
151 }
152
153 // jobSandbox is the job container, the services started beside it, and the network
154 // they share. Stop is idempotent: the failure paths stop early so the service logs
155 // can go into the attempt, and the deferred call still runs.
156 type jobSandbox struct {
157 job *container.Container
158 services []*container.Container
159 serviceIDs []string
160 network *container.Network
161 }
162
163 func (s *jobSandbox) Stop() { s.StopWithLogs(nil) }
164
165 // StopJob stops the job container and leaves the services and network for the
166 // caller's final Stop. The job is stopped before artifacts and a site are read so a
167 // background step cannot change the tree while it is being published; a service
168 // does not touch that tree, and keeping it up means a publish failure can still
169 // attach its output.
170 func (s *jobSandbox) StopJob() {
171 if s.job != nil {
172 s.job.Stop()
173 s.job = nil
174 }
175 }
176
177 // StopWithLogs stops the job, then the services, then removes the network. When w
178 // is not nil, each service's last output is written under its own heading first:
179 // a job that failed after a database refused to start should not make the reader
180 // find the database's log in a second place.
181 func (s *jobSandbox) StopWithLogs(w io.Writer) {
182 s.StopJob()
183 if w != nil {
184 for i, svc := range s.services {
185 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
186 data, err := svc.Logs(ctx, container.MaxServiceLogBytes)
187 cancel()
188 if err != nil || len(data) == 0 {
189 continue
190 }
191 fmt.Fprintf(w, "\n=== service %s ===\n", s.serviceIDs[i])
192 _, _ = w.Write(data)
193 if data[len(data)-1] != '\n' {
194 fmt.Fprintln(w)
195 }
196 }
197 }
198 for _, svc := range s.services {
199 svc.Stop()
200 }
201 s.services, s.serviceIDs = nil, nil
202 if s.network != nil {
203 ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
204 _ = s.network.Remove(ctx)
205 cancel()
206 s.network = nil
207 }
208 }
209
210 // serviceNetworkName is the per-attempt network the job and its services join.
211 // The attempt is part of the name because two attempts of the same run must not
212 // share a network.
213 func serviceNetworkName(box runnerBox, job *runnerJob) string {
214 return fmt.Sprintf("vole-%s-%s-%d-net", box.id, strings.ToLower(job.ID), job.Attempt)
215 }
216
217 func serviceContainerName(box runnerBox, job *runnerJob, id string) string {
218 return fmt.Sprintf("vole-%s-%s-%d-svc-%s", box.id, strings.ToLower(job.ID), job.Attempt, id)
219 }
220
221 // cleanupStaleNetworks removes networks a killed runner left behind. It runs after
222 // cleanupStaleContainers, because a network with a member cannot be removed.
223 func cleanupStaleNetworks(cfg runnerBox) {
224 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
225 defer cancel()
226 names, err := container.ListNetworks(ctx, cfg.Config, "vole.runner.id="+cfg.id)
227 if err != nil {
228 return // the first job will report a runtime problem with more context
229 }
230 for _, name := range names {
231 labels, err := container.NetworkLabels(ctx, cfg.Config, name)
232 if err != nil {
233 continue
234 }
235 pid, _ := strconv.Atoi(labels["vole.runner.pid"])
236 if pid > 0 && processAlive(pid) {
237 continue // another runner using the same cache is still working
238 }
239 _ = container.RemoveNetwork(ctx, cfg.Config, name)
240 }
241 }