| 1 | package mac |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "errors" |
| 7 | "os" |
| 8 | "os/exec" |
| 9 | "path/filepath" |
| 10 | "slices" |
| 11 | "strconv" |
| 12 | "strings" |
| 13 | "sync" |
| 14 | "time" |
| 15 | |
| 16 | "amadan.net/oficina/equipo/internal/wire" |
| 17 | ) |
| 18 | |
| 19 | // Result is one gate run: the output's last lines, the exit code, why it |
| 20 | // did not finish ("cancelled", "checks_timeout", "checks_unavailable"), |
| 21 | // whether its end is proven, and how it was confined. |
| 22 | type Result struct { |
| 23 | Output, Reason string |
| 24 | Code int |
| 25 | Terminated bool |
| 26 | // Sandbox is wire.SandboxSeatbelt when srt confined the gate, else |
| 27 | // wire.SandboxNone. |
| 28 | Sandbox string |
| 29 | } |
| 30 | |
| 31 | // Gate runs a repository's checks in a process group of their own |
| 32 | // (spec §5): a new session, EQUIPO_ATTEMPT=<key> in the environment, an |
| 33 | // environment from scratch. With SRT set the gate runs under srt with |
| 34 | // the attempt's checks profile; without, it runs outside the sandbox |
| 35 | // (the test build's fake worker, or a Mac whose P2 did not deny). |
| 36 | type Gate struct { |
| 37 | // SRT is the srt executable; "" runs the gate without a sandbox. |
| 38 | SRT string |
| 39 | // Settings writes the attempt's srt settings for a tree and scratch. |
| 40 | Settings func(tree, attempt string) ([]byte, error) |
| 41 | // Env is the gate's whole environment but TMPDIR, EQUIPO_ATTEMPT and |
| 42 | // EQUIPO_GATE_STATUS (and under srt CLAUDE_CODE_TMPDIR and |
| 43 | // XDG_CONFIG_HOME), which the run adds. |
| 44 | Env []string |
| 45 | // Caffeinate keeps the Mac awake while a gate runs |
| 46 | // (/usr/bin/caffeinate); "" does not. |
| 47 | Caffeinate string |
| 48 | // Booted lists the simulators booted now; Shutdown shuts one down. |
| 49 | // A run shuts down the simulators it booted. |
| 50 | Booted func(context.Context) []string |
| 51 | Shutdown func(context.Context, string) |
| 52 | // Grace is SIGTERM to SIGKILL (10 s); Settle bounds the proof (30 s). |
| 53 | Grace, Settle time.Duration |
| 54 | // Lines bounds the output kept (the last 200 lines). |
| 55 | Lines int |
| 56 | // Sandbox labels the result: srt confines it (seatbelt) or not (none). |
| 57 | Sandbox string |
| 58 | // ScratchHome sets HOME to the attempt's scratch too (the test |
| 59 | // build's fake worker; a Mac keeps the runner user's home, where |
| 60 | // Xcode's caches are). |
| 61 | ScratchHome bool |
| 62 | // UserTemp is the runner user's DARWIN_USER_TEMP_DIR ("T", which a |
| 63 | // checks profile lets the gate write): what appears in it and in |
| 64 | // T/TemporaryItems while a run lasts is removed once the run's end |
| 65 | // is proven. "" removes nothing. |
| 66 | UserTemp string |
| 67 | // QuietSimulators, when set, runs once a run with a UserTemp has |
| 68 | // proven its end and before T is cleaned: on a Mac, every |
| 69 | // simulator of the runner user shut down (bounded), and what is |
| 70 | // left of them logged. |
| 71 | QuietSimulators func(context.Context) |
| 72 | // Turns, when set, lets one run at a time hold the Mac (shared by |
| 73 | // every gate of the runner), so a cleanup of T sees only its own. |
| 74 | Turns *Turns |
| 75 | // Watch sees each line of output as it comes (probe P6 waits for a |
| 76 | // test to start before it kills the group). |
| 77 | Watch func(string) |
| 78 | // procs and own stand in for the process table and the runner's own |
| 79 | // processes (tests). |
| 80 | procs Procs |
| 81 | own *Own |
| 82 | } |
| 83 | |
| 84 | // executor is the gate's share of the Mac's executor. |
| 85 | func (g *Gate) executor() *Executor { |
| 86 | return &Executor{Turns: g.Turns, Procs: g.procs, Own: g.own, Grace: g.Grace, Settle: g.Settle, UserTemp: g.UserTemp, QuietSimulators: g.QuietSimulators, |
| 87 | Unsandboxed: g.SRT == "" || g.Sandbox != wire.SandboxSeatbelt} |
| 88 | } |
| 89 | |
| 90 | // statusScript runs the gate and records its exit status in a file: srt |
| 91 | // exits 0 when the command it wraps dies of SIGTERM or SIGINT |
| 92 | // (cli.ts), so the exit code alone could turn a killed gate into a pass. |
| 93 | const statusScript = `"$@"; s=$?; printf '%s\n' "$s" > "$EQUIPO_GATE_STATUS"; exit "$s"` |
| 94 | |
| 95 | // Run runs argv in dir as a check: in the Mac's turn (the one ctx holds, |
| 96 | // else its own for the run's life), through the executor, so record |
| 97 | // gets the attempt's marker before anything starts and its group once |
| 98 | // the leader exists (spec §5). Nothing runs if the first record fails; |
| 99 | // the group is stopped if the second does. |
| 100 | func (g *Gate) Run(ctx context.Context, attempt, dir string, argv []string, limit time.Duration, record func(string) error) Result { |
| 101 | res := Result{Code: -1, Sandbox: g.Sandbox} |
| 102 | unavailable := func() Result { res.Reason, res.Terminated = "checks_unavailable", true; return res } |
| 103 | if len(argv) == 0 || !validMarker(attempt) { |
| 104 | return unavailable() |
| 105 | } |
| 106 | ctx, give, err := g.Turns.Hold(ctx, OpCheck) |
| 107 | if err != nil { |
| 108 | if ctx.Err() == nil { |
| 109 | return unavailable() |
| 110 | } |
| 111 | res.Reason, res.Terminated = "cancelled", true |
| 112 | return res |
| 113 | } |
| 114 | defer give() |
| 115 | scratch, err := os.MkdirTemp(filepath.Dir(dir), "attempt-") |
| 116 | if err != nil { |
| 117 | return unavailable() |
| 118 | } |
| 119 | defer os.RemoveAll(scratch) |
| 120 | status := filepath.Join(scratch, ".equipo-status") |
| 121 | cmdline := append([]string{"/bin/sh", "-c", statusScript, "sh"}, argv...) |
| 122 | if g.SRT != "" { |
| 123 | raw, err := g.Settings(dir, scratch) |
| 124 | if err != nil { |
| 125 | return unavailable() |
| 126 | } |
| 127 | // Beside the tree and scratch, not in them: the gate cannot |
| 128 | // rewrite its own profile (it is read once, at start, anyway). |
| 129 | settings := filepath.Join(filepath.Dir(dir), "srt-settings-"+filepath.Base(scratch)+".json") |
| 130 | if err := os.WriteFile(settings, raw, 0600); err != nil { |
| 131 | return unavailable() |
| 132 | } |
| 133 | defer os.Remove(settings) |
| 134 | cmdline = append([]string{g.SRT, "--settings", settings, "--"}, cmdline...) |
| 135 | } |
| 136 | env := append(append([]string{}, g.Env...), "TMPDIR="+scratch, "EQUIPO_ATTEMPT="+attempt, "EQUIPO_GATE_STATUS="+status) |
| 137 | if g.SRT != "" { |
| 138 | // srt 0.0.81 sets the command's TMPDIR to CLAUDE_CODE_TMPDIR, else |
| 139 | // to its own /tmp/claude (generateProxyEnvVars in sandbox-utils), |
| 140 | // a directory every srt user on the Mac shares and none cleans: |
| 141 | // keep it this attempt's scratch, which the profile already lets |
| 142 | // the gate write and the run removes. |
| 143 | env = append(env, "CLAUDE_CODE_TMPDIR="+scratch) |
| 144 | // SwiftPM keeps ~/.swiftpm (links to its security, configuration |
| 145 | // and cache folders, and a lock it takes) at $XDG_CONFIG_HOME/ |
| 146 | // swiftpm when that is set (dotSwiftPM in SwiftPM's Basics), and |
| 147 | // removes and remakes the security link on every resolve: under |
| 148 | // srt that is a write to the real home, which the profile |
| 149 | // refuses. In the attempt's scratch it is the attempt's alone. |
| 150 | env = append(env, "XDG_CONFIG_HOME="+filepath.Join(scratch, "config")) |
| 151 | } |
| 152 | if g.ScratchHome { |
| 153 | env = append(env, "HOME="+scratch) |
| 154 | } |
| 155 | var before []string |
| 156 | if g.Booted != nil { |
| 157 | before = g.Booted(ctx) |
| 158 | } |
| 159 | out := &tail{max: max(g.Lines, 1), watch: g.Watch} |
| 160 | // A cleanup of T an earlier attempt left is finished first, only by |
| 161 | // its owner or after a restart; T that cannot be listed (or is no |
| 162 | // longer this user's own folder) or cleaned runs nothing. |
| 163 | run, err := g.executor().Start(ctx, Command{Argv: cmdline, Env: env, Dir: dir, Stdout: out, Stderr: out}, attempt, record) |
| 164 | if err != nil { |
| 165 | res.Output = out.String() |
| 166 | if errors.Is(err, ErrUnproven) { |
| 167 | res.Reason = "checks_unavailable" |
| 168 | return res |
| 169 | } |
| 170 | return unavailable() |
| 171 | } |
| 172 | if g.Caffeinate != "" { |
| 173 | // Outside the group, the runner's own: it ends by itself when the |
| 174 | // gate's leader does. |
| 175 | awake := exec.Command(g.Caffeinate, "-i", "-w", strconv.Itoa(run.pgid)) |
| 176 | if StartOwn(awake) == nil { |
| 177 | go func() { _ = awake.Wait() }() |
| 178 | } |
| 179 | } |
| 180 | timer := time.NewTimer(limit) |
| 181 | defer timer.Stop() |
| 182 | select { |
| 183 | case <-run.Exited(): |
| 184 | res.Code = exitCode(run.ExitErr()) |
| 185 | if res.Code == 0 { |
| 186 | // Both must say 0: srt's own exit and the status the gate's |
| 187 | // shell recorded. |
| 188 | raw, rerr := os.ReadFile(status) |
| 189 | if n, perr := strconv.Atoi(strings.TrimSpace(string(raw))); rerr != nil || perr != nil || n != 0 { |
| 190 | res.Code = 1 |
| 191 | if perr == nil && n > 0 { |
| 192 | res.Code = n |
| 193 | } |
| 194 | } |
| 195 | } |
| 196 | case <-run.Aborted(): |
| 197 | // Its turn's record could not be written: stopped, and its end |
| 198 | // proven only once a write succeeds. |
| 199 | res.Reason = "checks_unavailable" |
| 200 | case <-ctx.Done(): |
| 201 | res.Reason = "cancelled" |
| 202 | case <-timer.C: |
| 203 | res.Reason = "checks_timeout" |
| 204 | } |
| 205 | res.Terminated = run.Stop() |
| 206 | if g.Booted != nil && g.Shutdown != nil { |
| 207 | for _, udid := range g.Booted(context.WithoutCancel(ctx)) { |
| 208 | if !slices.Contains(before, udid) { |
| 209 | g.Shutdown(context.WithoutCancel(ctx), udid) |
| 210 | } |
| 211 | } |
| 212 | } |
| 213 | // Only once the run's end is proven: a process of it still alive |
| 214 | // could be writing T as it is cleaned. Unproven, or not finished, |
| 215 | // the cleanup waits for this attempt's proof (Verify) or a restart, |
| 216 | // and the run is not terminated: its end is proven only with T clean. |
| 217 | if !run.Finish(ctx) { |
| 218 | res.Terminated = false |
| 219 | } |
| 220 | res.Output = out.String() |
| 221 | return res |
| 222 | } |
| 223 | |
| 224 | // Verify reports whether a recorded attempt has ended for sure, killing |
| 225 | // what is left of it (Executor.Verify): after a crash this is what |
| 226 | // kills every marked process before the runner reports runner_restarted. |
| 227 | func (g *Gate) Verify(id string) bool { return g.executor().Verify(id) } |
| 228 | |
| 229 | // Acknowledge is Executor.Acknowledge. |
| 230 | func (g *Gate) Acknowledge(id, consumer string) { g.executor().Acknowledge(id, consumer) } |
| 231 | |
| 232 | func exitCode(err error) int { |
| 233 | if err == nil { |
| 234 | return 0 |
| 235 | } |
| 236 | var exit *exec.ExitError |
| 237 | if errors.As(err, &exit) { |
| 238 | if code := exit.ExitCode(); code >= 0 { |
| 239 | return code |
| 240 | } |
| 241 | } |
| 242 | return -1 |
| 243 | } |
| 244 | |
| 245 | // tail keeps the last max lines written to it, each at most |
| 246 | // maxLineBytes (the rest of a longer line is dropped), so what it holds |
| 247 | // is bounded however much a gate prints, with or without newlines. |
| 248 | type tail struct { |
| 249 | mu sync.Mutex |
| 250 | max int |
| 251 | watch func(string) |
| 252 | lines []string |
| 253 | partial []byte |
| 254 | } |
| 255 | |
| 256 | const maxLineBytes = 4 << 10 |
| 257 | |
| 258 | func (t *tail) Write(p []byte) (int, error) { |
| 259 | t.mu.Lock() |
| 260 | defer t.mu.Unlock() |
| 261 | n := len(p) |
| 262 | for len(p) > 0 { |
| 263 | i := bytes.IndexByte(p, '\n') |
| 264 | chunk := p |
| 265 | if i >= 0 { |
| 266 | chunk = p[:i] |
| 267 | } |
| 268 | if room := maxLineBytes - len(t.partial); room > 0 { |
| 269 | t.partial = append(t.partial, chunk[:min(len(chunk), room)]...) |
| 270 | } |
| 271 | if i < 0 { |
| 272 | break |
| 273 | } |
| 274 | line := string(t.partial) |
| 275 | t.partial = t.partial[:0] |
| 276 | t.lines = append(t.lines, line) |
| 277 | if len(t.lines) > t.max { |
| 278 | t.lines = append(t.lines[:0:0], t.lines[len(t.lines)-t.max:]...) |
| 279 | } |
| 280 | if t.watch != nil { |
| 281 | t.watch(line) |
| 282 | } |
| 283 | p = p[i+1:] |
| 284 | } |
| 285 | return n, nil |
| 286 | } |
| 287 | |
| 288 | func (t *tail) String() string { |
| 289 | t.mu.Lock() |
| 290 | defer t.mu.Unlock() |
| 291 | lines := t.lines |
| 292 | if len(t.partial) > 0 { |
| 293 | lines = append(append([]string{}, lines...), string(t.partial)) |
| 294 | } |
| 295 | if len(lines) > t.max { |
| 296 | lines = lines[len(lines)-t.max:] |
| 297 | } |
| 298 | return strings.Join(lines, "\n") |
| 299 | } |
| 300 | |