oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1//go:build linux
2
3package thin
4
5import (
6 "context"
7 "errors"
8 "fmt"
9 "os"
10 "os/signal"
11 "path/filepath"
12 "strconv"
13 "sync/atomic"
14 "testing"
15 "time"
16 "unsafe"
17
18 "golang.org/x/sys/unix"
19)
20
21// Adversaries a sandbox may run against the pause (Astra task 9 round 1,
22// F1 and F4). The pause does not stop them; the copy must then refuse with
23// busy, by its check that nothing it read changed while it was made.
24//
25// The helpers run as this test binary, started inside the test's sandbox
26// with EQUIPO_WORKSNAP_HELPER naming one; init runs them before any test.
27func init() {
28 switch os.Getenv("EQUIPO_WORKSNAP_HELPER") {
29 case "":
30 return
31 case "selfcont":
32 helperSelfCont(os.Getenv("FILE"), filepath.SplitList(os.Getenv("WATCH")))
33 case "uring":
34 helperURing(os.Getenv("FILE"), os.Getenv("READY"))
35 }
36 os.Exit(2)
37}
38
39// helperSelfCont resumes itself, two ways, while it overwrites FILE (same
40// size, a new count) about every 200 microseconds. A POSIX timer sends it
41// SIGCONT every millisecond; since Linux 6.13 that timer re-arms only when
42// its signal is delivered, so a SIGSTOP that flushes a pending SIGCONT
43// (as stop signals do) ends it, and the pause wins. So an inotify
44// descriptor on the watch directories also has the kernel send it
45// SIGCONT (O_ASYNC, F_SETSIG) whenever anything there is opened or read:
46// the copy itself. It handles SIGCONT, which is ignored by default and
47// parked.
48func helperSelfCont(file string, watch []string) {
49 signal.Notify(make(chan os.Signal, 1), unix.SIGCONT)
50 ino, err := unix.InotifyInit1(unix.IN_CLOEXEC | unix.IN_NONBLOCK)
51 if err != nil {
52 os.Exit(7)
53 }
54 for _, dir := range append(watch, filepath.Dir(file)) {
55 if _, err := unix.InotifyAddWatch(ino, dir, unix.IN_OPEN|unix.IN_ACCESS); err != nil {
56 os.Exit(7)
57 }
58 }
59 if _, err := unix.FcntlInt(uintptr(ino), unix.F_SETOWN, os.Getpid()); err != nil {
60 os.Exit(7)
61 }
62 if _, err := unix.FcntlInt(uintptr(ino), unix.F_SETSIG, int(unix.SIGCONT)); err != nil {
63 os.Exit(7)
64 }
65 if _, err := unix.FcntlInt(uintptr(ino), unix.F_SETFL, unix.O_ASYNC|unix.O_NONBLOCK); err != nil {
66 os.Exit(7)
67 }
68 var ev [64]byte // struct sigevent: value (8), signo (4), notify (4: SIGEV_SIGNAL = 0)
69 *(*int32)(unsafe.Pointer(&ev[8])) = int32(unix.SIGCONT)
70 var id int32
71 if _, _, e := unix.Syscall(unix.SYS_TIMER_CREATE, uintptr(unix.CLOCK_MONOTONIC), uintptr(unsafe.Pointer(&ev[0])), uintptr(unsafe.Pointer(&id))); e != 0 {
72 os.Exit(3)
73 }
74 spec := [4]int64{0, 1_000_000, 0, 1_000_000} // interval, value
75 if _, _, e := unix.Syscall6(unix.SYS_TIMER_SETTIME, uintptr(id), 0, uintptr(unsafe.Pointer(&spec[0])), 0, 0, 0); e != 0 {
76 os.Exit(4)
77 }
78 f, err := os.OpenFile(file, os.O_WRONLY, 0)
79 if err != nil {
80 os.Exit(5)
81 }
82 events := make([]byte, 4096)
83 for i := 0; ; i++ {
84 f.WriteAt([]byte(fmt.Sprintf("%08d", i%100000000)), 0)
85 // Drained, so the queue never overflows and each access queues
86 // an event (and its signal) of its own.
87 for {
88 if n, err := unix.Read(ino, events); n <= 0 || err != nil {
89 break
90 }
91 }
92 time.Sleep(200 * time.Microsecond)
93 }
94}
95
96// io_uring, by raw system calls (golang.org/x/sys has no ring types).
97type uringParams struct {
98 sqEntries, cqEntries, flags, sqThreadCPU, sqThreadIdle, features, wqFd uint32
99 resv [3]uint32
100 sq struct {
101 head, tail, ringMask, ringEntries, flags, dropped, array, resv1 uint32
102 userAddr uint64
103 }
104 cq struct {
105 head, tail, ringMask, ringEntries, overflow, cqes, flags, resv1 uint32
106 userAddr uint64
107 }
108}
109
110type uringSQE struct {
111 opcode, flags uint8
112 ioprio uint16
113 fd int32
114 off, addr uint64
115 len, rwFlags uint32
116 userData uint64
117 bufIndex, personality uint16
118 spliceFdIn int32
119 addr3, pad uint64
120}
121
122const (
123 uringOpWrite = 23
124 uringSQELink = 1 << 2
125 uringSQEAsync = 1 << 4
126 uringGetEvents = 1
127 uringChain = 128
128 uringBlock = 64 << 10
129)
130
131// helperURing writes READY ("ok" or "unavailable"), then keeps submitting
132// chains of linked asynchronous O_DSYNC overwrites of FILE's first 64 KiB
133// (its size never changes) and waiting for each: work the kernel's io-wq
134// workers carry on with after the submitting thread stops.
135func helperURing(file, ready string) {
136 say := func(s string) { os.WriteFile(ready, []byte(s), 0o600) }
137 var p uringParams
138 ring, _, e := unix.Syscall(unix.SYS_IO_URING_SETUP, uringChain, uintptr(unsafe.Pointer(&p)), 0)
139 if e != 0 {
140 say("unavailable: io_uring_setup: " + e.Error())
141 select {}
142 }
143 fd := int(ring)
144 sqRing, err1 := unix.Mmap(fd, 0, int(p.sq.array+p.sqEntries*4), unix.PROT_READ|unix.PROT_WRITE, unix.MAP_SHARED|unix.MAP_POPULATE)
145 cqRing, err2 := unix.Mmap(fd, 0x8000000, int(p.cq.cqes+p.cqEntries*16), unix.PROT_READ|unix.PROT_WRITE, unix.MAP_SHARED|unix.MAP_POPULATE)
146 sqes, err3 := unix.Mmap(fd, 0x10000000, int(p.sqEntries)*int(unsafe.Sizeof(uringSQE{})), unix.PROT_READ|unix.PROT_WRITE, unix.MAP_SHARED|unix.MAP_POPULATE)
147 target, err4 := unix.Open(file, unix.O_WRONLY|unix.O_DSYNC|unix.O_CLOEXEC, 0)
148 if err := errors.Join(err1, err2, err3, err4); err != nil {
149 say("unavailable: " + err.Error())
150 select {}
151 }
152 u32 := func(b []byte, off uint32) *uint32 { return (*uint32)(unsafe.Pointer(&b[off])) }
153 sqTail, sqMask, sqArray := u32(sqRing, p.sq.tail), *u32(sqRing, p.sq.ringMask), p.sq.array
154 cqHead, cqTail := u32(cqRing, p.cq.head), u32(cqRing, p.cq.tail)
155 buf := make([]byte, uringBlock)
156 for round := 0; ; round++ {
157 for i := range buf {
158 buf[i] = byte('a' + round%26)
159 }
160 tail := atomic.LoadUint32(sqTail)
161 for i := uint32(0); i < uringChain; i++ {
162 slot := (tail + i) & sqMask
163 sqe := (*uringSQE)(unsafe.Pointer(&sqes[uintptr(slot)*unsafe.Sizeof(uringSQE{})]))
164 *sqe = uringSQE{opcode: uringOpWrite, flags: uringSQEAsync, fd: int32(target), addr: uint64(uintptr(unsafe.Pointer(&buf[0]))), len: uringBlock}
165 if i < uringChain-1 {
166 sqe.flags |= uringSQELink
167 }
168 *u32(sqRing, sqArray+slot*4) = slot
169 }
170 atomic.StoreUint32(sqTail, tail+uringChain)
171 if _, _, e := unix.Syscall6(unix.SYS_IO_URING_ENTER, uintptr(fd), uringChain, 0, 0, 0, 0); e != 0 {
172 say("unavailable: io_uring_enter: " + e.Error())
173 select {}
174 }
175 if round == 0 {
176 say("ok")
177 }
178 // Wait for the whole chain, then consume its completions.
179 if _, _, e := unix.Syscall6(unix.SYS_IO_URING_ENTER, uintptr(fd), 0, uringChain, uringGetEvents, 0, 0); e != 0 && e != unix.EINTR {
180 os.Exit(6)
181 }
182 atomic.StoreUint32(cqHead, atomic.LoadUint32(cqTail))
183 _ = runtimeKeep(buf)
184 }
185}
186
187//go:noinline
188func runtimeKeep(b []byte) int { return len(b) }
189
190// adversarySnapshots runs snapshots while the adversary writes into
191// site/page.bin; each must be busy whenever the page changed while the
192// copy was made (seen from inside the pause by the workCopied seam). It
193// returns how many saw the page change inside the pause: there, or in a
194// window as the copy begins (the workParsed seam), since a copy that
195// catches the change itself refuses before it reaches workCopied.
196func adversarySnapshots(t *testing.T, h *sandboxHandle, ws string, rounds int) (changed, busy int) {
197 t.Helper()
198 page := filepath.Join(ws, "site/page.bin")
199 var moved, active bool
200 window := func() bool {
201 before, _ := os.Stat(page)
202 time.Sleep(150 * time.Millisecond)
203 after, _ := os.Stat(page)
204 return before == nil || after == nil || !before.ModTime().Equal(after.ModTime())
205 }
206 workParsed = func() { active = window() }
207 workCopied = func() { moved = window() }
208 defer func() { workParsed, workCopied = nil, nil }()
209 for i := range rounds {
210 moved, active = false, false
211 stage := filepath.Join(t.TempDir(), "stage"+strconv.Itoa(i))
212 _, err := h.snapshot(context.Background(), ws, stage, "")
213 if moved || active {
214 changed++
215 }
216 if errors.Is(err, errWorkBusy) {
217 busy++
218 continue
219 }
220 if err != nil {
221 t.Fatalf("round %d: %v", i, err)
222 }
223 if moved {
224 t.Fatalf("round %d: the page changed while the copy was made, and the copy was accepted", i)
225 }
226 }
227 return changed, busy
228}
229
230func adversaryTree(t *testing.T) string {
231 files := siteFiles()
232 files["site/page.bin"] = string(make([]byte, uringBlock))
233 return workTree(t, files, nil)
234}
235
236func helperSandbox(t *testing.T, env ...string) *sandboxHandle {
237 t.Helper()
238 self, err := os.Executable()
239 if err != nil {
240 t.Fatal(err)
241 }
242 r := stepSandbox(t, append([]string{"BIN=" + self}, env...), `exec "$BIN" -test.run=NONE`)
243 h := &sandboxHandle{}
244 h.keep(r)
245 return h
246}
247
248// waitMoving waits until file's mtime moves.
249func waitMoving(t *testing.T, file string) {
250 t.Helper()
251 first, _ := os.Stat(file)
252 for deadline := time.Now().Add(10 * time.Second); ; {
253 if now, err := os.Stat(file); err == nil && first != nil && !now.ModTime().Equal(first.ModTime()) {
254 return
255 }
256 if time.Now().After(deadline) {
257 t.Fatal("the adversary never wrote")
258 }
259 time.Sleep(5 * time.Millisecond)
260 }
261}
262
263// F1: a process that resumes itself with a SIGCONT timer and overwrites
264// a page (same size) during the copy: every copy it changes is refused.
265func TestSnapshotRefusesASelfResumingWriter(t *testing.T) {
266 ws := adversaryTree(t)
267 page := filepath.Join(ws, "site/page.bin")
268 watch := filepath.Join(ws, "release") + string(filepath.ListSeparator) + filepath.Join(ws, "site")
269 h := helperSandbox(t, "EQUIPO_WORKSNAP_HELPER=selfcont", "FILE="+page, "WATCH="+watch)
270 waitMoving(t, page)
271 changed, busy := adversarySnapshots(t, h, ws, 5)
272 t.Logf("%d of 5 copies saw the page change; %d refused busy", changed, busy)
273 if changed == 0 {
274 t.Fatal("the self-resuming writer never wrote during a copy: the test proves nothing")
275 }
276}
277
278// F1: two processes that SIGCONT each other and stop themselves, one
279// overwriting the page each turn: every copy they change is refused, and
280// a copy they do not change is accepted.
281func TestSnapshotRefusesSIGCONTPeers(t *testing.T) {
282 ws := adversaryTree(t)
283 page := filepath.Join(ws, "site/page.bin")
284 d := t.TempDir()
285 peer := `echo $$ > "$D/$0.pid"; while [ ! -s "$D/$1.pid" ]; do :; done; read other < "$D/$1.pid"; i=0
286while :; do kill -CONT $other; if [ "$0" = a ]; then i=$((i+1)); printf '%08d' $i 1<> "$PAGE"; fi; kill -STOP $$; done`
287 r := stepSandbox(t, []string{"D=" + d, "PAGE=" + page, "P=" + peer}, `sh -c "$P" a b & sh -c "$P" b a & wait`)
288 h := &sandboxHandle{}
289 h.keep(r)
290 waitMoving(t, page)
291 changed, busy := adversarySnapshots(t, h, ws, 5)
292 // Each copy is busy or saw no change (adversarySnapshots). Here the
293 // pause's repeated SIGSTOPs usually catch both peers stopped at once,
294 // after which neither can resume the other: then nothing changes.
295 t.Logf("%d of 5 copies saw the page change; %d refused busy", changed, busy)
296}
297
298// F4: asynchronous writes (io_uring, linked O_DSYNC overwrites punted to
299// the kernel's workers) submitted before the pause and completing during
300// the copy: every copy they change is refused. Skipped where io_uring
301// is unavailable. (On 6.12 the chain does not advance while the
302// submitting process is stopped, so the copies see no change.)
303func TestSnapshotRefusesAsyncWrites(t *testing.T) {
304 ws := adversaryTree(t)
305 page := filepath.Join(ws, "site/page.bin")
306 ready := filepath.Join(t.TempDir(), "ready")
307 h := helperSandbox(t, "EQUIPO_WORKSNAP_HELPER=uring", "FILE="+page, "READY="+ready)
308 for deadline := time.Now().Add(10 * time.Second); ; {
309 raw, _ := os.ReadFile(ready)
310 if string(raw) == "ok" {
311 break
312 }
313 if len(raw) > 0 {
314 t.Skipf("io_uring is unavailable here: %s", raw)
315 }
316 if time.Now().After(deadline) {
317 t.Fatal("the io_uring helper never started")
318 }
319 time.Sleep(5 * time.Millisecond)
320 }
321 waitMoving(t, page)
322 changed, busy := adversarySnapshots(t, h, ws, 5)
323 t.Logf("%d of 5 copies saw the page change; %d refused busy", changed, busy)
324}
325
326// The copy's own check, driven from inside it (the workCopied seam runs
327// once every file is copied): any change to what it read refuses with
328// busy, a same-size overwrite whose mtime is put back (only ctime shows
329// it) included; and a deadline passing during the copy refuses too.
330func TestWorkSiteRefusesAChangeDuringTheCopy(t *testing.T) {
331 restored := func(path string, write func()) func() {
332 return func() {
333 info, err := os.Stat(path)
334 if err != nil {
335 t.Fatal(err)
336 }
337 time.Sleep(20 * time.Millisecond) // past the timestamp granularity
338 write()
339 if err := os.Chtimes(path, info.ModTime(), info.ModTime()); err != nil {
340 t.Fatal(err)
341 }
342 }
343 }
344 for name, change := range map[string]func(ws string) func(){
345 "a same-size overwrite, mtime put back": func(ws string) func() {
346 p := filepath.Join(ws, "site/index.html")
347 return restored(p, func() { os.WriteFile(p, []byte("<h1>HOME</h1>"), 0o644) })
348 },
349 "a new file in a directory": func(ws string) func() {
350 return func() { os.WriteFile(filepath.Join(ws, "site/a/b/new.html"), []byte("x"), 0o644) }
351 },
352 "a file removed": func(ws string) func() {
353 return func() { os.Remove(filepath.Join(ws, "site/a/b/c/d.css")) }
354 },
355 "preview.json rewritten, mtime put back": func(ws string) func() {
356 p := filepath.Join(ws, "release/preview.json")
357 return restored(p, func() { os.WriteFile(p, []byte(`{"output": "sitf"}`), 0o644) })
358 },
359 } {
360 ws := workTree(t, siteFiles(), nil)
361 workCopied = change(ws)
362 _, _, err := copySite(t, ws, "")
363 workCopied = nil
364 if !errors.Is(err, errWorkBusy) {
365 t.Errorf("%s: %v", name, err)
366 }
367 }
368 // Nothing changed: accepted.
369 ws := workTree(t, siteFiles(), nil)
370 workCopied = func() { time.Sleep(20 * time.Millisecond) }
371 _, _, err := copySite(t, ws, "")
372 workCopied = nil
373 if err != nil {
374 t.Fatalf("an unchanged tree: %v", err)
375 }
376 // The deadline passes while the copy is being made.
377 st, err := openSiteStage(filepath.Join(t.TempDir(), "stage"))
378 if err != nil {
379 t.Fatal(err)
380 }
381 defer st.close()
382 deadline := time.Now().Add(time.Second)
383 workCopied = func() { time.Sleep(time.Until(deadline) + 10*time.Millisecond) }
384 defer func() { workCopied = nil }()
385 if _, err := copyWorkSite(ws, st, "", deadline); !errors.Is(err, errWorkBusy) {
386 t.Fatalf("a copy past its deadline: %v", err)
387 }
388}
389
390// A directory whose names differ from the walk's is refused even when its
391// times are equal (a change within the same timestamp tick): unchanged
392// compares the names, here given as the walk would have seen them before
393// one file appeared.
394func TestWorkSiteUnchangedComparesNames(t *testing.T) {
395 ws := workTree(t, siteFiles(), nil)
396 w, err := openWorkRoot(ws)
397 if err != nil {
398 t.Fatal(err)
399 }
400 defer w.close()
401 st, err := w.stat("site/a/b")
402 if err != nil {
403 t.Fatal(err)
404 }
405 seen := map[string]unix.Stat_t{"site/a/b": st}
406 if err := w.unchanged(seen, map[string][]string{"site/a/b": {"c"}}); err != nil {
407 t.Fatalf("the same names: %v", err)
408 }
409 for name, before := range map[string][]string{"one more now": {}, "one fewer now": {"c", "gone.html"}, "renamed": {"d"}} {
410 if err := w.unchanged(seen, map[string][]string{"site/a/b": before}); !errors.Is(err, errWorkBusy) {
411 t.Errorf("%s: %v", name, err)
412 }
413 }
414}
415
416// Astra round 2, N1: with {"output": "release"} the walk sees
417// release/preview.json a second time. Rewritten in place between the
418// parse and the walk (same size, mtime put back, so only ctime shows it;
419// the directory's names and times need not move), the walk must not take
420// the new stat as the one to check against: the copy is refused.
421func TestWorkSiteRefusesAConfigChangedBeforeTheWalk(t *testing.T) {
422 ws := workTree(t, map[string]string{
423 "release/preview.json": `{"output": "release"}`,
424 "release/index.html": "<h1>release</h1>",
425 "another/index.html": "<h1>another</h1>",
426 }, nil)
427 cfg := filepath.Join(ws, "release/preview.json")
428 info, err := os.Stat(cfg)
429 if err != nil {
430 t.Fatal(err)
431 }
432 fired := false
433 workParsed = func() {
434 fired = true
435 time.Sleep(20 * time.Millisecond) // past the timestamp tick
436 f, err := os.OpenFile(cfg, os.O_WRONLY, 0)
437 if err != nil {
438 t.Fatal(err)
439 }
440 f.WriteAt([]byte(`{"output": "another"}`), 0) // same size, in place
441 f.Close()
442 os.Chtimes(cfg, info.ModTime(), info.ModTime())
443 }
444 defer func() { workParsed = nil }()
445 _, _, err = copySite(t, ws, "")
446 if !fired {
447 t.Fatal("the seam never ran")
448 }
449 if !errors.Is(err, errWorkBusy) {
450 t.Fatalf("a config changed before the walk: %v", err)
451 }
452 // Unchanged, the same tree copies (the config is part of the output).
453 workParsed = nil
454 if _, _, err := copySite(t, workTree(t, map[string]string{
455 "release/preview.json": `{"output": "release"}`,
456 "release/index.html": "<h1>release</h1>",
457 }, nil), ""); err != nil {
458 t.Fatalf("an unchanged config in its output: %v", err)
459 }
460}
461