gunk-dev/the-valley

main.go

source6a7605f70901main's published tip history
13.0 KiB
1// Command onmain hands a host's own unit each new tip of a project's main.
2// It is the bridge behind a host's services.valley.onMain binding
3// (nix/valley-host.nix), one instance per binding, and the step that
4// writes the bound unit's environment.
5//
6// onmain watch converges on the latest tip. When main names a commit other
7// than the one it last requested, it replaces its commit file with that
8// commit and then creates its request file. That is all a bridge can do: it
9// starts nothing itself and holds no grant. The binding's path unit, with
10// PathExists= on the request file, starts the bound unit whenever the file
11// exists and the unit is not running, and checks the file again each time
12// the unit stops.
13//
14// onmain environment is the unit's first ExecStartPre=, run as root. It
15// removes the request, reads the commit file, and writes the environment
16// file the unit's command reads: VALLEY_REPOSITORY, from its own flag, and
17// VALLEY_COMMIT, the commit. systemd imports every assignment in an
18// environment file, so the bridge's user never writes one: a bridge that
19// could would choose the unit's loader and interpreter settings, and the
20// unit may run as root. The commit file is accepted only as one commit ID,
21// so all a bridge chooses is which commit runs.
22//
23// The order of the two steps on each side makes the handoff lose no tip
24// (see writeEnvironment). Moves made during a run leave one request and
25// the newest commit, so they become one run at the newest tip. The request
26// is removed before anything that can fail, so a failed run leaves nothing
27// that starts the unit again: the next run is for the next tip, or the
28// operator's.
29//
30// The tip last requested is kept in memory alone. So every start of the
31// bridge requests the current tip once, and a unit must tolerate running
32// again for a commit it has already run.
33//
34// main is read through git, and git's files ref storage is watched for its
35// moves (watch_linux.go). The watch is in place before main is first read,
36// and notifications are taken before each reading, so a move made at any
37// moment is followed by a reading that sees it. Losing the watch, or events
38// the kernel dropped, sets the watch up again and reads main again.
39package main
40
41import (
42 "errors"
43 "flag"
44 "fmt"
45 "io"
46 "io/fs"
47 "os"
48 "os/exec"
49 "path/filepath"
50 "regexp"
51 "strings"
52 "syscall"
53)
54
55// gitProgram is the git the repository is read with. The package fixes it
56// at build time to an absolute store path (nix/packages.nix), so no PATH
57// changes which git that is. Unset, as the tests run it, git is looked up
58// on PATH.
59var gitProgram = "git"
60
61// watcher is a watch on a repository's ref storage.
62type watcher interface {
63 // events is sent to, without blocking, when main's loose ref or
64 // packed-refs changed. Its capacity is one, so any number of changes
65 // wait as one.
66 events() <-chan struct{}
67 // failed is sent the reason once the watch must be set up again to see
68 // every change: a watched directory went or appeared, or the kernel
69 // dropped events. The bridge then sets up a new watch and reads main
70 // again.
71 failed() <-chan error
72 close()
73}
74
75type bridge struct {
76 repo string
77 commit string // the commit file
78 request string // the request file
79 log io.Writer
80
81 // watch sets up a watch on the ref storage at the git directory given
82 // (watch_linux.go). Tests may replace it.
83 watch func(gitDir string) (watcher, error)
84 // stop ends run when it is closed, for tests; nil never ends it.
85 stop <-chan struct{}
86 // waiting, when set, is called each time run waits for a change, and
87 // requested each time it has requested a run, for tests.
88 waiting func()
89 requested func(tip string)
90}
91
92const usage = `usage: onmain watch --repo DIR --commit-file FILE --request-file FILE
93 onmain environment --repo DIR --commit-file FILE --request-file FILE --out FILE
94`
95
96func main() {
97 if len(os.Args) < 2 {
98 fmt.Fprint(os.Stderr, usage)
99 os.Exit(2)
100 }
101 flags := flag.NewFlagSet("onmain "+os.Args[1], flag.ContinueOnError)
102 flags.Usage = func() { fmt.Fprint(os.Stderr, usage) }
103 repo := flags.String("repo", "", "the repository whose refs/heads/main is followed")
104 commit := flags.String("commit-file", "", "the file the bridge writes the commit to run to")
105 request := flags.String("request-file", "", "the file whose existence requests a run")
106 var out *string
107 switch os.Args[1] {
108 case "watch":
109 case "environment":
110 out = flags.String("out", "", "the environment file to write for the unit")
111 default:
112 fmt.Fprint(os.Stderr, usage)
113 os.Exit(2)
114 }
115 err := flags.Parse(os.Args[2:])
116 if err == nil && (*repo == "" || *commit == "" || *request == "" || flags.NArg() != 0 ||
117 out != nil && *out == "") {
118 flags.Usage()
119 err = flag.ErrHelp
120 }
121 if err != nil {
122 os.Exit(2)
123 }
124 if out != nil {
125 err = writeEnvironment(*repo, *commit, *request, *out)
126 } else {
127 b := &bridge{
128 repo: *repo,
129 commit: *commit,
130 request: *request,
131 log: os.Stdout,
132 watch: watchRefs,
133 }
134 err = b.run()
135 }
136 if err != nil {
137 fmt.Fprintf(os.Stderr, "onmain %s: %v\n", os.Args[1], err)
138 os.Exit(1)
139 }
140}
141
142// run follows main until the watch cannot be set up again, or until stop.
143func (b *bridge) run() error {
144 gitDir, err := refStorage(b.repo)
145 if err != nil {
146 return err
147 }
148 w, err := b.watch(gitDir)
149 if err != nil {
150 return fmt.Errorf("watching %s: %w", gitDir, err)
151 }
152 defer func() { w.close() }()
153
154 var last string
155 for {
156 // Taken before main is read, so a change after this reading is a
157 // notification waiting for the next.
158 select {
159 case <-w.events():
160 default:
161 }
162 tip, ok, err := readMain(b.repo)
163 switch {
164 case err != nil:
165 fmt.Fprintf(b.log, "reading main: %v; read again at its next change\n", err)
166 case ok && tip != last:
167 if err := requestRun(b.commit, b.request, tip); err != nil {
168 fmt.Fprintf(b.log, "requesting a run for %s: %v; requested again at the next change\n", tip, err)
169 break
170 }
171 last = tip
172 fmt.Fprintf(b.log, "requested a run for %s\n", tip)
173 if b.requested != nil {
174 b.requested(tip)
175 }
176 }
177 if b.waiting != nil {
178 b.waiting()
179 }
180 select {
181 case <-w.events():
182 case why := <-w.failed():
183 w.close()
184 fmt.Fprintf(b.log, "watching again and reading main: %v\n", why)
185 next, err := b.watch(gitDir)
186 if err != nil {
187 w = closed{}
188 return fmt.Errorf("watching %s again: %w", gitDir, err)
189 }
190 w = next
191 case <-b.stop:
192 return nil
193 }
194 }
195}
196
197// errDropped is what a watch fails with when the kernel dropped events.
198var errDropped = errors.New("the kernel dropped events")
199
200// closed is the watch left once one could not be set up again.
201type closed struct{}
202
203func (closed) events() <-chan struct{} { return nil }
204func (closed) failed() <-chan error { return nil }
205func (closed) close() {}
206
207// refStorage returns the directory git keeps the repository's refs in, and
208// refuses any ref storage but files, the loose refs and packed-refs the
209// watch understands.
210func refStorage(repo string) (string, error) {
211 out, err := git(repo, "rev-parse", "--show-ref-format", "--path-format=absolute", "--git-common-dir")
212 if err != nil {
213 return "", err
214 }
215 lines := strings.Split(strings.TrimSpace(out), "\n")
216 if len(lines) != 2 {
217 return "", fmt.Errorf("git rev-parse printed %q, not the ref format and the git directory", out)
218 }
219 if lines[0] != "files" {
220 return "", fmt.Errorf("%s keeps its refs in %s storage; onmain follows main only in files storage, as loose refs and packed-refs", repo, lines[0])
221 }
222 return lines[1], nil
223}
224
225var commitID = regexp.MustCompile(`^([0-9a-f]{40}|[0-9a-f]{64})$`)
226
227// readMain returns the commit refs/heads/main names, and false when there
228// is none.
229func readMain(repo string) (string, bool, error) {
230 out, err := git(repo, "rev-parse", "--verify", "--quiet", "refs/heads/main^{commit}")
231 var exit *exec.ExitError
232 if errors.As(err, &exit) && exit.ExitCode() == 1 {
233 return "", false, nil
234 }
235 if err != nil {
236 return "", false, err
237 }
238 tip := strings.TrimSpace(out)
239 if !commitID.MatchString(tip) {
240 return "", false, fmt.Errorf("git rev-parse printed %q, not a commit ID", out)
241 }
242 return tip, true, nil
243}
244
245func git(repo string, args ...string) (string, error) {
246 cmd := exec.Command(gitProgram, append([]string{"-C", repo}, args...)...)
247 var stderr strings.Builder
248 cmd.Stderr = &stderr
249 out, err := cmd.Output()
250 if err != nil {
251 if msg := strings.TrimSpace(stderr.String()); msg != "" {
252 return "", fmt.Errorf("%w: %s", err, msg)
253 }
254 return "", err
255 }
256 return string(out), nil
257}
258
259// requestRun requests a run at commit: it replaces the commit file whole,
260// by a rename, and then creates the request file. The order is the
261// bridge's half of the handoff writeEnvironment describes.
262func requestRun(commitFile, requestFile, commit string) error {
263 if err := replace(commitFile, commit+"\n"); err != nil {
264 return err
265 }
266 f, err := os.OpenFile(requestFile, os.O_WRONLY|os.O_CREATE, 0o644)
267 if err != nil {
268 return err
269 }
270 return f.Close()
271}
272
273// afterStep, when set, is called with the name of each step of
274// writeEnvironment as it completes, so tests can make the bridge write
275// between steps.
276var afterStep func(step string)
277
278func stepped(step string) {
279 if afterStep != nil {
280 afterStep(step)
281 }
282}
283
284// writeEnvironment writes the environment file the unit's command reads,
285// from the commit file the bridge wrote, and consumes the bridge's request.
286//
287// The bridge replaces the commit file and then creates the request; this
288// removes the request and then reads the commit file. So a commit the
289// bridge writes at any moment is either the one this run reads, or leaves
290// a request that starts the unit again after this run:
291//
292// - written before the read: this run reads it, or a newer one. Were its
293// request created after the removal, it also starts one more run,
294// which reads it again.
295// - written after the read, while this step writes the environment, the
296// unit's command runs, or the unit fails or stops: its request was
297// created after the removal, so it remains. The path unit holds no
298// watch while the unit is active, but looks for the file again when
299// the unit becomes inactive or failed, and starts it again.
300//
301// Read before removed, a commit written between the two would be lost:
302// this run would use the older commit, and the removal would take the
303// newer one's request.
304//
305// The request is removed before anything that can fail, so a run that
306// fails, here or in the unit's command, leaves nothing to start the unit
307// again.
308//
309// It runs as root, and the bridge's user owns both files and their
310// directory. So the commit file is opened without following a symbolic
311// link or waiting on a FIFO, must be a regular file, and is accepted only
312// as one commit ID and a newline. What it holds otherwise is never
313// printed. The repository is the flag's, never the bridge's.
314func writeEnvironment(repo, commitFile, requestFile, out string) error {
315 if err := os.Remove(requestFile); err != nil && !errors.Is(err, fs.ErrNotExist) {
316 return fmt.Errorf("removing the bridge's request: %w", err)
317 }
318 stepped("removed")
319 if !environmentSafe(repo) {
320 return fmt.Errorf("%q holds a space, a quote, a backslash, a $, a backtick or a character that is not printable ASCII, which the environment file cannot carry as written", repo)
321 }
322 commit, err := readCommit(commitFile)
323 stepped("read")
324 if err != nil {
325 return err
326 }
327 return replace(out, fmt.Sprintf("VALLEY_REPOSITORY=%s\nVALLEY_COMMIT=%s\n", repo, commit))
328}
329
330// readCommit returns the one commit ID the commit file holds.
331func readCommit(commitFile string) (string, error) {
332 f, err := os.OpenFile(commitFile, os.O_RDONLY|syscall.O_NOFOLLOW|syscall.O_NONBLOCK, 0)
333 if err != nil {
334 return "", fmt.Errorf("reading the commit the bridge wrote: %w", err)
335 }
336 defer f.Close()
337 if info, err := f.Stat(); err != nil || !info.Mode().IsRegular() {
338 return "", fmt.Errorf("%s is not a regular file", commitFile)
339 }
340 // One byte more than the longest commit ID and its newline, so a
341 // longer file is seen to be one.
342 data, err := io.ReadAll(io.LimitReader(f, 66))
343 if err != nil {
344 return "", fmt.Errorf("reading the commit the bridge wrote: %w", err)
345 }
346 commit, ok := strings.CutSuffix(string(data), "\n")
347 if !ok || !commitID.MatchString(commit) {
348 return "", fmt.Errorf("%s holds something other than one commit ID, so no environment is written for it", commitFile)
349 }
350 return commit, nil
351}
352
353// environmentSafe says whether s can stand unquoted as a value in a
354// systemd environment file and be read back as written.
355func environmentSafe(s string) bool {
356 for _, r := range s {
357 if r <= ' ' || r > '~' || strings.ContainsRune("\"'\\$`", r) {
358 return false
359 }
360 }
361 return s != ""
362}
363
364// replace replaces the file at path whole with content, by a rename, so a
365// reader never sees part of it.
366func replace(path, content string) error {
367 tmp, err := os.CreateTemp(filepath.Dir(path), ".onmain-*")
368 if err != nil {
369 return err
370 }
371 defer os.Remove(tmp.Name())
372 _, err = tmp.WriteString(content)
373 if err == nil {
374 err = tmp.Chmod(0o644)
375 }
376 if cerr := tmp.Close(); err == nil {
377 err = cerr
378 }
379 if err != nil {
380 return err
381 }
382 return os.Rename(tmp.Name(), path)
383}