package thin import ( "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "net/http" "net/http/httptest" "os" "path/filepath" "strconv" "strings" "syscall" "testing" "time" "amadan.net/oficina/equipo/internal/release" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/mac" "amadan.net/oficina/equipo/internal/wire" ) // stallXcrun plays an xcrun whose simctl never answers: the hanging // call leaves a child (sleep) holding its output, as a stuck // CoreSimulator client would. Every pid goes in PIDS so the test can // prove them gone and kill any left, by pid. const stallXcrun = `#!/bin/sh echo $$ >> PIDS case "$*" in *"devices available"*) [ -z "HANG_AVAILABLE" ] && { cat SIMS; exit 0; } ;; esac sleep 600 & echo $! >> PIDS wait ` const stallXcodebuild = `#!/bin/sh case "$*" in -version) echo "Xcode 16.2"; echo "Build version 16C5032a"; exit 0 ;; esac exit 64 ` // stallHost is a Mac host on Linux whose xcrun hangs: on every simctl // call (all) or only on the booted list the probes' gates ask (P6). func stallHost(t *testing.T, all bool) (*macHost, string) { t.Helper() root := t.TempDir() pids := filepath.Join(root, "pids") sims, err := filepath.Abs("../mac/testdata/simctl-devices.json") if err != nil { t.Fatal(err) } hang := "" if all { hang = "1" } xcrun := strings.NewReplacer("PIDS", pids, "SIMS", sims, `"HANG_AVAILABLE"`, `"`+hang+`"`).Replace(stallXcrun) tools := mac.Tools{Xcrun: filepath.Join(root, "xcrun"), Xcodebuild: filepath.Join(root, "xcodebuild")} for p, body := range map[string]string{tools.Xcrun: xcrun, tools.Xcodebuild: stallXcodebuild} { if err := os.WriteFile(p, []byte(body), 0700); err != nil { t.Fatal(err) } } t.Cleanup(func() { raw, _ := os.ReadFile(pids) for _, f := range strings.Fields(string(raw)) { if pid, err := strconv.Atoi(f); err == nil && pid > 1 { _ = syscall.Kill(pid, syscall.SIGKILL) } } }) was, users := mac.QueryLimit, macUsers mac.QueryLimit, macUsers = 300*time.Millisecond, filepath.Join(root, "Users") t.Cleanup(func() { mac.QueryLimit, macUsers = was, users }) c := runner.Config{StateDir: filepath.Join(root, "state"), ScratchRoot: filepath.Join(root, "scratch"), WorkspaceRoot: filepath.Join(root, "work"), Executable: filepath.Join(root, "lib", "runner")} for _, d := range []string{c.StateDir, c.ScratchRoot} { if err := os.MkdirAll(d, 0700); err != nil { t.Fatal(err) } } h, err := newMacHost(c, OptionsFromEnv(func(string) string { return "" })) if err != nil { t.Fatal(err) } h.tools = tools return h, pids } // alive lists the recorded pids still running after a short settle. func alive(pids string) []string { deadline := time.Now().Add(3 * time.Second) for { raw, _ := os.ReadFile(pids) var left []string for _, f := range strings.Fields(string(raw)) { if pid, err := strconv.Atoi(f); err == nil && syscall.Kill(pid, 0) == nil { if stat, _ := os.ReadFile("/proc/" + f + "/stat"); !strings.Contains(string(stat), ") Z ") { left = append(left, f) } } } if len(left) == 0 || time.Now().After(deadline) { return left } time.Sleep(50 * time.Millisecond) } } // A simctl that never answers no longer holds the probes: each query is // killed at QueryLimit with what it started, the run finishes, ready // closes, and the report says why the simulator probes could not run. // The booted list the probes' gates ask (Paul's Studio, 15:44) is // bounded as well as the capability list. func TestMacProbesFinishWhenSimctlHangs(t *testing.T) { for _, all := range []bool{true, false} { t.Run(map[bool]string{true: "every simctl", false: "the booted list"}[all], func(t *testing.T) { h, pids := stallHost(t, all) start := time.Now() h.probes.start(t.Context(), func() {}) ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() if err := h.probes.wait(ctx); err != nil { t.Fatalf("the probe run did not finish (ready never closed): %v", err) } if took := time.Since(start); took > 15*time.Second { t.Fatalf("the probe run took %s", took) } r := h.probes.report() if len(r.Probes) != len(wire.ProbeIDs) || len(r.Unfinished) != 0 { t.Fatalf("report %+v", r) } if err := wire.ValidCapabilities(wire.Capabilities{Probes: r.Probes}); err != nil { t.Fatalf("report outside the capability rules: %v", err) } p1, p6 := r.Probe("P1"), r.Probe("P6") if all { why := "simulator_unavailable:300ms" if p1.Verdict != wire.ProbeFailed || !strings.Contains(p1.Detail, why) || p6.Verdict != wire.ProbeUnavailable || p6.Detail != why { t.Fatalf("P1 %+v P6 %+v", p1, p6) } } else if p6.Verdict != wire.ProbeFailed || !strings.Contains(p6.Detail, "test_not_started:") { // The fake xcodebuild runs no test: P6 ran its gate (which // asked the booted list twice) and says so. t.Fatalf("P6 %+v", p6) } if left := alive(pids); len(left) != 0 { t.Fatalf("hung simctl processes left: %v", left) } }) } } // updateServer serves release bbb2222 with a runner whose digest its // manifest names. func updateServer(t *testing.T) (string, []byte) { newBin := []byte("#!new runner\n") sum := sha256.Sum256(newBin) srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch { case r.URL.Path == "/releases/bbb2222/install-manifest.json": _ = json.NewEncoder(w).Encode(release.InstallManifest{Version: "bbb2222", Targets: map[string]release.InstallTarget{release.TargetDarwin: {RunnerSHA256: hex.EncodeToString(sum[:])}}}) case strings.HasPrefix(r.URL.Path, "/releases/bbb2222/"+release.DarwinDir+"/"): _, _ = w.Write(newBin) default: http.NotFound(w, r) } })) t.Cleanup(srv.Close) return srv.URL, newBin } // heldGate runs only once the test lets it. type heldGate struct { *stubGate started, release chan struct{} } func (g heldGate) Run(ctx context.Context, a, dir string, argv []string, l time.Duration, record func(string) error) gateResult { close(g.started) <-g.release return g.stubGate.Run(ctx, a, dir, argv, l, record) } // The updater does not wait for the probes: with the probes stalled for // good and a step waiting on them, a new release is swapped in and the // worker stopped with ErrUpdated at once. A step that really runs still // holds the swap until it ends. func TestMacUpdateWhileProbesStall(t *testing.T) { origin, newBin := updateServer(t) update := func(t *testing.T, w *Worker, stop func()) (string, *macUpdater) { binary := filepath.Join(t.TempDir(), "runner") if err := os.WriteFile(binary, []byte("#!old runner\n"), 0700); err != nil { t.Fatal(err) } u := &macUpdater{origin: origin, version: "aaa1111", binary: binary, fetch: fetchLimited} u.offer(wire.Welcome{Release: "bbb2222"}, w.hold, stop, nil) return binary, u } swapped := func(binary string) bool { raw, _ := os.ReadFile(binary); return string(raw) == string(newBin) } t.Run("probes stalled", func(t *testing.T) { x := newWorkerRig(t) x.chunk(t, "c1", x.header(), x.pack, 0, 1, "") waiting := make(chan struct{}) x.w.Ready = func(ctx context.Context) error { close(waiting) <-ctx.Done() return ctx.Err() } ctx, stop := context.WithCancelCause(context.Background()) defer stop(nil) reps := make(chan wire.StepReport, 1) go func() { reps <- x.w.Exec(ctx, x.r, func(wire.StepReport) {}) }() <-waiting binary, u := update(t, x.w, func() { stop(ErrUpdated) }) select { case err := <-u.done: if err != nil || !swapped(binary) || !errors.Is(context.Cause(ctx), ErrUpdated) { t.Fatalf("update: %v swapped=%v cause=%v", err, swapped(binary), context.Cause(ctx)) } case <-time.After(10 * time.Second): t.Fatal("the update waited for probes that never finish") } select { case rep := <-reps: if rep.State != wire.StepCancelled || len(x.gate.ran) != 0 { t.Fatalf("waiting step %+v ran %v", rep, x.gate.ran) } case <-time.After(5 * time.Second): t.Fatal("the waiting step did not end with the worker") } }) t.Run("step running", func(t *testing.T) { x := newWorkerRig(t) x.chunk(t, "c1", x.header(), x.pack, 0, 1, "") g := heldGate{stubGate: x.gate, started: make(chan struct{}), release: make(chan struct{})} x.w.Gate = g reps := make(chan wire.StepReport, 1) go func() { reps <- x.run() }() <-g.started stopped := make(chan struct{}) binary, u := update(t, x.w, func() { close(stopped) }) select { case <-u.done: t.Fatal("the update did not wait for the running step") case <-time.After(500 * time.Millisecond): } if swapped(binary) { t.Fatal("binary swapped while a step ran") } close(g.release) if rep := <-reps; rep.State != wire.StepDone { t.Fatalf("step %+v", rep) } select { case err := <-u.done: if err != nil || !swapped(binary) { t.Fatalf("update after the step: %v", err) } <-stopped case <-time.After(10 * time.Second): t.Fatal("the update never applied after the step") } }) }