oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package thin
2
3import (
4 "context"
5 "crypto/sha256"
6 "encoding/hex"
7 "encoding/json"
8 "errors"
9 "net/http"
10 "net/http/httptest"
11 "os"
12 "path/filepath"
13 "strconv"
14 "strings"
15 "syscall"
16 "testing"
17 "time"
18
19 "amadan.net/oficina/equipo/internal/release"
20 "amadan.net/oficina/equipo/internal/runner"
21 "amadan.net/oficina/equipo/internal/runner/mac"
22 "amadan.net/oficina/equipo/internal/wire"
23)
24
25// stallXcrun plays an xcrun whose simctl never answers: the hanging
26// call leaves a child (sleep) holding its output, as a stuck
27// CoreSimulator client would. Every pid goes in PIDS so the test can
28// prove them gone and kill any left, by pid.
29const stallXcrun = `#!/bin/sh
30echo $$ >> PIDS
31case "$*" in
32*"devices available"*) [ -z "HANG_AVAILABLE" ] && { cat SIMS; exit 0; } ;;
33esac
34sleep 600 &
35echo $! >> PIDS
36wait
37`
38
39const stallXcodebuild = `#!/bin/sh
40case "$*" in
41-version) echo "Xcode 16.2"; echo "Build version 16C5032a"; exit 0 ;;
42esac
43exit 64
44`
45
46// stallHost is a Mac host on Linux whose xcrun hangs: on every simctl
47// call (all) or only on the booted list the probes' gates ask (P6).
48func stallHost(t *testing.T, all bool) (*macHost, string) {
49 t.Helper()
50 root := t.TempDir()
51 pids := filepath.Join(root, "pids")
52 sims, err := filepath.Abs("../mac/testdata/simctl-devices.json")
53 if err != nil {
54 t.Fatal(err)
55 }
56 hang := ""
57 if all {
58 hang = "1"
59 }
60 xcrun := strings.NewReplacer("PIDS", pids, "SIMS", sims, `"HANG_AVAILABLE"`, `"`+hang+`"`).Replace(stallXcrun)
61 tools := mac.Tools{Xcrun: filepath.Join(root, "xcrun"), Xcodebuild: filepath.Join(root, "xcodebuild")}
62 for p, body := range map[string]string{tools.Xcrun: xcrun, tools.Xcodebuild: stallXcodebuild} {
63 if err := os.WriteFile(p, []byte(body), 0700); err != nil {
64 t.Fatal(err)
65 }
66 }
67 t.Cleanup(func() {
68 raw, _ := os.ReadFile(pids)
69 for _, f := range strings.Fields(string(raw)) {
70 if pid, err := strconv.Atoi(f); err == nil && pid > 1 {
71 _ = syscall.Kill(pid, syscall.SIGKILL)
72 }
73 }
74 })
75 was, users := mac.QueryLimit, macUsers
76 mac.QueryLimit, macUsers = 300*time.Millisecond, filepath.Join(root, "Users")
77 t.Cleanup(func() { mac.QueryLimit, macUsers = was, users })
78 c := runner.Config{StateDir: filepath.Join(root, "state"), ScratchRoot: filepath.Join(root, "scratch"), WorkspaceRoot: filepath.Join(root, "work"), Executable: filepath.Join(root, "lib", "runner")}
79 for _, d := range []string{c.StateDir, c.ScratchRoot} {
80 if err := os.MkdirAll(d, 0700); err != nil {
81 t.Fatal(err)
82 }
83 }
84 h, err := newMacHost(c, OptionsFromEnv(func(string) string { return "" }))
85 if err != nil {
86 t.Fatal(err)
87 }
88 h.tools = tools
89 return h, pids
90}
91
92// alive lists the recorded pids still running after a short settle.
93func alive(pids string) []string {
94 deadline := time.Now().Add(3 * time.Second)
95 for {
96 raw, _ := os.ReadFile(pids)
97 var left []string
98 for _, f := range strings.Fields(string(raw)) {
99 if pid, err := strconv.Atoi(f); err == nil && syscall.Kill(pid, 0) == nil {
100 if stat, _ := os.ReadFile("/proc/" + f + "/stat"); !strings.Contains(string(stat), ") Z ") {
101 left = append(left, f)
102 }
103 }
104 }
105 if len(left) == 0 || time.Now().After(deadline) {
106 return left
107 }
108 time.Sleep(50 * time.Millisecond)
109 }
110}
111
112// A simctl that never answers no longer holds the probes: each query is
113// killed at QueryLimit with what it started, the run finishes, ready
114// closes, and the report says why the simulator probes could not run.
115// The booted list the probes' gates ask (Paul's Studio, 15:44) is
116// bounded as well as the capability list.
117func TestMacProbesFinishWhenSimctlHangs(t *testing.T) {
118 for _, all := range []bool{true, false} {
119 t.Run(map[bool]string{true: "every simctl", false: "the booted list"}[all], func(t *testing.T) {
120 h, pids := stallHost(t, all)
121 start := time.Now()
122 h.probes.start(t.Context(), func() {})
123 ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
124 defer cancel()
125 if err := h.probes.wait(ctx); err != nil {
126 t.Fatalf("the probe run did not finish (ready never closed): %v", err)
127 }
128 if took := time.Since(start); took > 15*time.Second {
129 t.Fatalf("the probe run took %s", took)
130 }
131 r := h.probes.report()
132 if len(r.Probes) != len(wire.ProbeIDs) || len(r.Unfinished) != 0 {
133 t.Fatalf("report %+v", r)
134 }
135 if err := wire.ValidCapabilities(wire.Capabilities{Probes: r.Probes}); err != nil {
136 t.Fatalf("report outside the capability rules: %v", err)
137 }
138 p1, p6 := r.Probe("P1"), r.Probe("P6")
139 if all {
140 why := "simulator_unavailable:300ms"
141 if p1.Verdict != wire.ProbeFailed || !strings.Contains(p1.Detail, why) || p6.Verdict != wire.ProbeUnavailable || p6.Detail != why {
142 t.Fatalf("P1 %+v P6 %+v", p1, p6)
143 }
144 } else if p6.Verdict != wire.ProbeFailed || !strings.Contains(p6.Detail, "test_not_started:") {
145 // The fake xcodebuild runs no test: P6 ran its gate (which
146 // asked the booted list twice) and says so.
147 t.Fatalf("P6 %+v", p6)
148 }
149 if left := alive(pids); len(left) != 0 {
150 t.Fatalf("hung simctl processes left: %v", left)
151 }
152 })
153 }
154}
155
156// updateServer serves release bbb2222 with a runner whose digest its
157// manifest names.
158func updateServer(t *testing.T) (string, []byte) {
159 newBin := []byte("#!new runner\n")
160 sum := sha256.Sum256(newBin)
161 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
162 switch {
163 case r.URL.Path == "/releases/bbb2222/install-manifest.json":
164 _ = json.NewEncoder(w).Encode(release.InstallManifest{Version: "bbb2222", Targets: map[string]release.InstallTarget{release.TargetDarwin: {RunnerSHA256: hex.EncodeToString(sum[:])}}})
165 case strings.HasPrefix(r.URL.Path, "/releases/bbb2222/"+release.DarwinDir+"/"):
166 _, _ = w.Write(newBin)
167 default:
168 http.NotFound(w, r)
169 }
170 }))
171 t.Cleanup(srv.Close)
172 return srv.URL, newBin
173}
174
175// heldGate runs only once the test lets it.
176type heldGate struct {
177 *stubGate
178 started, release chan struct{}
179}
180
181func (g heldGate) Run(ctx context.Context, a, dir string, argv []string, l time.Duration, record func(string) error) gateResult {
182 close(g.started)
183 <-g.release
184 return g.stubGate.Run(ctx, a, dir, argv, l, record)
185}
186
187// The updater does not wait for the probes: with the probes stalled for
188// good and a step waiting on them, a new release is swapped in and the
189// worker stopped with ErrUpdated at once. A step that really runs still
190// holds the swap until it ends.
191func TestMacUpdateWhileProbesStall(t *testing.T) {
192 origin, newBin := updateServer(t)
193 update := func(t *testing.T, w *Worker, stop func()) (string, *macUpdater) {
194 binary := filepath.Join(t.TempDir(), "runner")
195 if err := os.WriteFile(binary, []byte("#!old runner\n"), 0700); err != nil {
196 t.Fatal(err)
197 }
198 u := &macUpdater{origin: origin, version: "aaa1111", binary: binary, fetch: fetchLimited}
199 u.offer(wire.Welcome{Release: "bbb2222"}, w.hold, stop, nil)
200 return binary, u
201 }
202 swapped := func(binary string) bool { raw, _ := os.ReadFile(binary); return string(raw) == string(newBin) }
203
204 t.Run("probes stalled", func(t *testing.T) {
205 x := newWorkerRig(t)
206 x.chunk(t, "c1", x.header(), x.pack, 0, 1, "")
207 waiting := make(chan struct{})
208 x.w.Ready = func(ctx context.Context) error {
209 close(waiting)
210 <-ctx.Done()
211 return ctx.Err()
212 }
213 ctx, stop := context.WithCancelCause(context.Background())
214 defer stop(nil)
215 reps := make(chan wire.StepReport, 1)
216 go func() { reps <- x.w.Exec(ctx, x.r, func(wire.StepReport) {}) }()
217 <-waiting
218 binary, u := update(t, x.w, func() { stop(ErrUpdated) })
219 select {
220 case err := <-u.done:
221 if err != nil || !swapped(binary) || !errors.Is(context.Cause(ctx), ErrUpdated) {
222 t.Fatalf("update: %v swapped=%v cause=%v", err, swapped(binary), context.Cause(ctx))
223 }
224 case <-time.After(10 * time.Second):
225 t.Fatal("the update waited for probes that never finish")
226 }
227 select {
228 case rep := <-reps:
229 if rep.State != wire.StepCancelled || len(x.gate.ran) != 0 {
230 t.Fatalf("waiting step %+v ran %v", rep, x.gate.ran)
231 }
232 case <-time.After(5 * time.Second):
233 t.Fatal("the waiting step did not end with the worker")
234 }
235 })
236
237 t.Run("step running", func(t *testing.T) {
238 x := newWorkerRig(t)
239 x.chunk(t, "c1", x.header(), x.pack, 0, 1, "")
240 g := heldGate{stubGate: x.gate, started: make(chan struct{}), release: make(chan struct{})}
241 x.w.Gate = g
242 reps := make(chan wire.StepReport, 1)
243 go func() { reps <- x.run() }()
244 <-g.started
245 stopped := make(chan struct{})
246 binary, u := update(t, x.w, func() { close(stopped) })
247 select {
248 case <-u.done:
249 t.Fatal("the update did not wait for the running step")
250 case <-time.After(500 * time.Millisecond):
251 }
252 if swapped(binary) {
253 t.Fatal("binary swapped while a step ran")
254 }
255 close(g.release)
256 if rep := <-reps; rep.State != wire.StepDone {
257 t.Fatalf("step %+v", rep)
258 }
259 select {
260 case err := <-u.done:
261 if err != nil || !swapped(binary) {
262 t.Fatalf("update after the step: %v", err)
263 }
264 <-stopped
265 case <-time.After(10 * time.Second):
266 t.Fatal("the update never applied after the step")
267 }
268 })
269}
270