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/execute/execute.go +348

@@ -0,0 +1,348 @@
1 // Package execute is the boundary between the runner and the thing that runs a
2 // job's steps.
3 //
4 // Everything around a job — the lease, the saved checkout, the job cache, the log
5 // stream, the artifact publish, the record — belongs to ci/agent and is the same
6 // whatever the steps run in. This package is the part that is not: taking a pinned
7 // image, creating an environment for one job, running a shell step in it while the
8 // lease stays alive, and removing it afterwards.
9 //
10 // An Executor is one way to do that. ci/container is the OCI implementation: one
11 // container per job, started by docker, podman, or nerdctl. A second implementation
12 // is the reason this package exists — a job whose steps run in a virtual machine
13 // (Tart for macOS, or a Linux microVM), where the "image" is a VM disk rather than
14 // a layer stack and there is no container runtime on the host at all. That backend
15 // implements the same interface, so the lease, the log, the cache, the secrets, and
16 // the record do not learn that anything changed.
17 //
18 // The interface is deliberately smaller than ci/container's API. It has to be,
19 // because the two kinds of backend agree about far less than they disagree about:
20 // there is no `--userns`, no `--pids-limit`, no `--tmpfs`, and no `--cap-drop` for
21 // a virtual machine, and a VM can be reached only through a guest channel rather
22 // than a runtime's exec. So the contract here is stated in terms of what a job
23 // needs, and a backend that cannot honour part of it says so through Capabilities
24 // instead of quietly dropping the flag. The caller checks that before the job
25 // starts, which is the difference between a workflow that fails with a sentence and
26 // one that fails halfway through a build.
27 //
28 // Two rules keep a second backend honest:
29 //
30 // - Nothing outside an environment is reachable from inside it. A step can see
31 // its job tree, its cache, and its event directory, and nothing else of the
32 // runner's: not the SSH key, not the saved checkout, not another job.
33 // - The caller owns the clock and the lease. Anything long — pulling a 60 GB VM
34 // image, building a definition, booting a guest — goes through Runner so it
35 // keeps its lease alive and stops when the run is cancelled.
36 package execute
37
38 import (
39 "context"
40 "errors"
41 "fmt"
42 "io"
43 "os/exec"
44 "sort"
45 "strings"
46 "time"
47 )
48
49 // Executor is one implementation of job execution.
50 //
51 // An Executor is safe for concurrent use: a runner with --jobs 4 leases four jobs
52 // at once and calls Start on all of them.
53 type Executor interface {
54 // Capabilities describes what this executor can honour and what it is called.
55 // It is fixed for the life of the process and is read before a job is accepted.
56 Capabilities() Capabilities
57
58 // Probe proves the executor can start a job on this host, and is run before the
59 // runner connects. Being installed is not being able to execute: a runtime whose
60 // daemon is down, a hypervisor without the entitlement, and an unenlightened
61 // `/dev/kvm` all pass a lookup and none of them can start a job. A machine that
62 // cannot execute is a startup failure, not a job that fails later and blames the
63 // commit.
64 Probe(ctx context.Context) error
65
66 // Prepare makes the job's image available and returns the reference Start takes.
67 //
68 // in.Ref is a registry reference, used as written. Otherwise in carries a pinned
69 // definition: the executor builds, pulls, or provisions that exact content and
70 // returns a handle that names it, so two jobs with the same definition share one
71 // preparation. The work can take an hour, so it goes through run and writes its
72 // progress to out.
73 //
74 // The release function marks the image no longer in flight and must be called
75 // once Start has the environment up. It is non-nil only on success: a failed
76 // Prepare has already released the image and returns a nil release.
77 Prepare(ctx context.Context, in Image, out io.Writer, run Runner) (ref string, release func(), err error)
78
79 // Start creates the environment for one job and returns the handle the steps run
80 // in. spec has already been validated against Capabilities by the caller.
81 Start(ctx context.Context, spec Spec) (Sandbox, error)
82
83 // Reconcile removes work an earlier process left behind: a container or a guest
84 // whose runner was killed before it could clean up. It runs at startup, before
85 // the first lease, and must not fail because there is nothing to remove.
86 Reconcile(ctx context.Context) error
87
88 // Prune bounds the executor's own storage, which is the one thing a runner cannot
89 // measure or quota itself because the backend owns it. age of zero keeps
90 // everything. A pass must give way to a job that is preparing or starting an
91 // image, and a backend that cannot prune reports it once rather than failing.
92 Prune(ctx context.Context, age time.Duration) (reclaimed int64, err error)
93 }
94
95 // Capabilities is what an executor can honour, and what it is.
96 //
97 // These are promises, not hints: the caller refuses a job whose workflow asks for
98 // something the executor reports false, before anything is started. A backend that
99 // silently degraded a job would produce a green run that did not test what the
100 // workflow said it tested, which is worse than a job that waits for the right
101 // machine.
102 type Capabilities struct {
103 // Backend names the implementation, for the run record and the log header:
104 // "podman" or "docker" for a container runtime, "tart" for a macOS guest.
105 Backend string
106 // Network reports whether a job that asks for network: bridge can be served. A
107 // job that asks for none is always servable.
108 Network bool
109 // Services reports whether service environments can be started beside a job and
110 // reached by their declared names.
111 Services bool
112 // Limits reports whether Memory and CPU are enforced per job. When false the
113 // caller must not present them as a bound.
114 Limits bool
115 // Root reports that steps run as a privileged user in their environment (uid 0,
116 // or Administrator in a Windows guest), so the environment's own files are
117 // writable by the job. It is a warning at startup, not a refusal.
118 Root bool
119 }
120
121 // Image is what a job asked to run in, before the executor has made it available.
122 //
123 // Exactly one of Ref and Definition is set: a workflow names a registry image or a
124 // pinned .vole/images definition, and the workflow validator refuses both or
125 // neither. How the rest is interpreted belongs to the backend — Definition is a
126 // build recipe for a container and the identity of a guest image for a VM — but the
127 // pinning rule is the same: the digest, not the name, is what runs.
128 type Image struct {
129 // Ref is a registry reference, used exactly as written.
130 Ref string
131 // File is the .vole/images name the definition came from, used to name what is
132 // built. Empty when Ref is set.
133 File string
134 // Definition is the pinned definition text. Empty when Ref is set.
135 Definition string
136 // Digest is the definition's pinned digest. It is the identity of the image, so a
137 // changed definition is a different image and an unchanged one is reused.
138 Digest string
139 }
140
141 // Runner runs one host-side command while keeping the job's lease alive.
142 //
143 // It exists so that a backend can perform an operation that outlives a lease
144 // interval without owning the lease. The agent's implementation heartbeats, watches
145 // the runner's free space, and turns a cancellation request into a killed process;
146 // a backend that ran the command itself would go quiet and be requeued mid-build.
147 //
148 // Run returns the command's exit code and reports a lease that went away (lost) or
149 // a run a maintainer cancelled (canceled). Both mean the backend must stop and must
150 // not start an environment: the queue no longer considers this job the runner's.
151 type Runner interface {
152 Run(ctx context.Context, cmd *exec.Cmd, out io.Writer) (code int, lost, canceled bool)
153 // Beat confirms the lease is still held, for a backend that has to wait for work
154 // it did not start: another slot is already pulling or building the same image,
155 // and a waiter that went quiet would be requeued and then go on to run a job the
156 // queue no longer considers its own. It blocks for one beat and reports held=false
157 // when the lease is gone; canceled reports a maintainer's stop, and out is where
158 // the reason goes.
159 Beat(out io.Writer) (held, canceled bool)
160 }
161
162 // A backend reports these two through its error, wrapping the cause of the stop, so
163 // the caller can tell "the machine could not do this" from "this job is no longer
164 // yours" without knowing which backend ran it.
165 var (
166 // ErrLeaseLost means the queue gave the job to another runner. Nothing is
167 // reported: that runner states the result now.
168 ErrLeaseLost = errors.New("the lease was lost")
169 // ErrCanceled means a maintainer asked the run to stop. What did happen is still
170 // reported, because a partial attempt is what a reader wants first.
171 ErrCanceled = errors.New("the run was canceled")
172 )
173
174 // Direct runs a command with no lease to keep, which is what a local
175 // `vole workflow run` and a test need. It is the same behaviour a backend would
176 // have if it ran the command itself: no heartbeat, no disk check, and a context
177 // that kills the process.
178 type Direct struct{}
179
180 // Run implements Runner.
181 func (Direct) Run(ctx context.Context, cmd *exec.Cmd, out io.Writer) (int, bool, bool) {
182 cmd.Stdout, cmd.Stderr = out, out
183 err := cmd.Run()
184 if err == nil {
185 return 0, false, false
186 }
187 var code *exec.ExitError
188 if errors.As(err, &code) {
189 return code.ExitCode(), false, false
190 }
191 fmt.Fprintf(out, "\n%v\n", err)
192 return 1, false, false
193 }
194
195 // Beat implements Runner: a local run holds no lease, so it never loses one.
196 func (Direct) Beat(io.Writer) (bool, bool) { return true, false }
197
198 // Nothing is a sandbox that was never started. The caller holds one before Start so
199 // its failure paths can stop "the sandbox" without a nil check on every branch.
200 func Nothing() Sandbox { return nothing{} }
201
202 type nothing struct{}
203
204 func (nothing) Exec(context.Context, string) *exec.Cmd { return nil }
205 func (nothing) StopJob() {}
206 func (nothing) Stop() {}
207 func (nothing) ServiceLogs(context.Context, int64) []ServiceLog { return nil }
208
209 // Spec is one job's environment, in the terms a workflow uses rather than the terms
210 // a runtime uses.
211 type Spec struct {
212 // Name identifies this attempt's environment when a backend has to name things:
213 // containers, guests, and the network they share are all derived from it. It is
214 // unique to the attempt, so two attempts of the same run never meet.
215 Name string
216 // Image is what Prepare returned.
217 Image string
218 // Work is the job tree: a fresh checkout that the steps may write. The backend
219 // makes Work.Host visible at Work.Path and starts each step there.
220 Work Share
221 // Shares are extra directories the job may write: the cache, and the directory
222 // holding the pinned event and the secrets file. They are owned by the runner's
223 // user, so a job can fill one; bounding them is the caller's job.
224 Shares []Share
225 // Env is the job's environment on top of the fixed set the runner sets. Names
226 // here cannot collide with the reserves: the workflow validator refuses those.
227 Env map[string]string
228 // SecretsFile, when set, is the path of a file *inside* the environment holding
229 // `export NAME='value'` lines, which every step sources before its own script. A
230 // secret then reaches the step's shell and never its argv, which matters because
231 // a runtime's or a hypervisor's argument list is visible to every process on the
232 // host. The caller writes the file; the caller owns what is in it.
233 SecretsFile string
234 // Network is the network mode this job gets, already resolved against the
235 // executor's own default: ci.NetworkNone or ci.NetworkBridge. Services are reached
236 // over a private network created for the attempt, so requesting them requires
237 // NetworkBridge.
238 Network string
239 // Memory and CPUs are per-job resource limits. They are honoured only when
240 // Capabilities reports Limits.
241 Memory string
242 CPUs string
243 // Services are environments started beside the job, reachable by their declared
244 // names, and stopped with it. Empty when the workflow declared none.
245 Services []Service
246 // Labels are how the backend's own tooling finds what this attempt created,
247 // including after a killed runner. A backend that has no labels may ignore them.
248 Labels map[string]string
249 }
250
251 // Share is one directory the runner makes visible inside the environment. A
252 // container bind-mounts it; a virtual machine shares it (virtiofs) or, where a
253 // backend cannot share, copies it in and back out. The guarantee the interface
254 // makes is only this: the host directory is readable and writable by the job at
255 // Path for the length of the job.
256 type Share struct {
257 Host string
258 Path string
259 }
260
261 // Service is one server started beside a job: a database, a queue, or another
262 // process the steps reach by name. It gets no job tree, no cache, and no secrets,
263 // and it runs the image's own command rather than a keepalive shell.
264 type Service struct {
265 // ID is the name the workflow declared, and the name the job's steps resolve.
266 ID string
267 Image string
268 Env map[string]string
269 }
270
271 // ServiceLog is one service's last output, read before the service is removed so a
272 // job that failed after a database refused to start says why in one place.
273 type ServiceLog struct {
274 ID string
275 Data []byte
276 }
277
278 // MaxServiceLogBytes bounds one service's output in an attempt log. A database that
279 // fails to start says why at the end; the tail is what the reader needs, and the cap
280 // keeps three services from crowding out the steps.
281 const MaxServiceLogBytes = 256 << 10
282
283 // Sandbox is one job's running environment: the job itself, the services started
284 // beside it, and the network they share. Stop and StopJob are idempotent, because
285 // the failure paths stop early so the service logs can go into the attempt and the
286 // deferred call still runs.
287 type Sandbox interface {
288 // Exec prepares one step. Each step is a separate exec, which is what gives it
289 // its own log, timeout, and exit status while keeping the filesystem and any
290 // background process shared with the steps around it.
291 //
292 // The returned command runs on the host — a runtime's exec, or a client talking
293 // to a guest — and the caller starts it through Runner, which is what keeps the
294 // lease alive and kills the process group on a timeout. Its output is the step's
295 // log.
296 Exec(ctx context.Context, script string) *exec.Cmd
297 // StopJob ends the job and leaves the services and the network for Stop. It is
298 // called before artifacts and a site are read, so a background step cannot change
299 // the tree while it is being published.
300 StopJob()
301 // Stop ends everything: the job, the services, and the network. Logs are not read
302 // here, so an ordinary successful finish does not spend time collecting them.
303 Stop()
304 // ServiceLogs reads each service's last output, keeping the last max bytes of
305 // each. It is called on a path that is already failing, so it returns what it
306 // could read and skips a service whose runtime would not answer.
307 ServiceLogs(ctx context.Context, max int64) []ServiceLog
308 }
309
310 // StepScript is the shell text one step runs: the secrets file is sourced first, so
311 // every step's own shell exports the values and no value is ever an argument. A
312 // step that shadows one of its own is the step's business; the file is its
313 // environment.
314 func StepScript(script, secretsFile string) string {
315 if secretsFile == "" {
316 return script
317 }
318 return ". " + secretsFile + "\n" + script
319 }
320
321 // SecretsEnv renders the values a job runs with as the file every step sources.
322 // Each line exports one variable and the value is POSIX single-quoted, so a quote
323 // becomes '\” and a newline stays a newline; nothing is interpolated. Names are
324 // sorted so the same values produce the same bytes.
325 //
326 // It lives here rather than in a backend because every backend that runs shell
327 // steps reads the same file, and two renderings that disagreed about quoting would
328 // be a secret that leaks or a step that fails depending on which executor ran it.
329 func SecretsEnv(values map[string]string) ([]byte, error) {
330 names := make([]string, 0, len(values))
331 for name := range values {
332 names = append(names, name)
333 }
334 sort.Strings(names)
335 var b strings.Builder
336 for _, name := range names {
337 value := values[name]
338 if strings.ContainsRune(value, 0) {
339 // A NUL would end the string the shell reads and turn the rest into a
340 // command, so it cannot be written even though the store refuses it.
341 return nil, fmt.Errorf("secret %s contains a NUL byte", name)
342 }
343 b.WriteString("export " + name + "='")
344 b.WriteString(strings.ReplaceAll(value, "'", `'\''`))
345 b.WriteString("'\n")
346 }
347 return []byte(b.String()), nil
348 }