package mac import ( "context" "crypto/rand" "encoding/hex" "errors" "os" "slices" "sync" "time" "amadan.net/oficina/equipo/internal/runner/mac/creds" "amadan.net/oficina/equipo/internal/runner/mac/proc" "amadan.net/oficina/equipo/internal/wire" ) // Op is what a turn is for. Every operation that runs repository code, // runs Xcode or has a model token in a process takes the Mac's one turn // for its own life and no longer (spec ยง8.3 item 4); what it starts // itself (Xcode under Engineering, a simulator under a check) is its. type Op string const ( OpCheck Op = "check" OpEngineering Op = "engineering" OpAsk Op = "ask" OpProbe Op = "probe" OpTokenCheck Op = "token_check" OpSignIn Op = "sign_in" OpTokenStore Op = "token_store" OpWarm Op = "warm" // OpRecover settles what an earlier operation left (Verify). OpRecover Op = "recover" ) // ErrNoTurn refuses a start outside a turn of the Mac's Turns. var ErrNoTurn = errors.New("mac: no turn held") // ErrUnsettled refuses a turn while an earlier one's processes may // still be running (its end not proven), or while another live runner // process left a turn record. var ErrUnsettled = errors.New("mac: an earlier turn is not settled") // ErrPendingCleanup refuses a sandboxed run while another attempt's // user-temp cleanup is unfinished and not this turn's to finish. var ErrPendingCleanup = errors.New("mac: another attempt's cleanup is pending") // Turns is the Mac's one machine lock, across the runner's processes (a // channel within a process, an flock on a file in the state dir, which // no profile lets a sandboxed command reach, between them). Beside the // lock it keeps two durable records: // // - lock+".turn": the turn now (or the last one whose end was not // proven): its operation, the runner process that took it, the // runner user's processes when it began (the sweep's "before"), and // the markers, groups and sessions of what it started. A later turn // settles it before it begins; a restart does the same. // - lock+".pending": a sandboxed attempt's user-temp cleanup not yet // done, owned by the turn that wrote it: only that attempt (its run, // or its proof later in the same runner) or a restart may finish it. type Turns struct { lock string lk *proc.Lock // sweep is the table every turn sweeps the runner user with at its // end (MachineProcs on a Mac); nil: no runner-user sweep. sweep Procs // own is the runner's own processes (runnerOwn; tests stand in). own *Own // ids reads runner processes' identities (the platform's table; // tests stand in). ids Procs // beforeWrite runs before each turn record write (tests: a slow or // failing disk). beforeWrite func() error beforeDrop func() // before the pending record's removal (tests) // boot reads this boot (creds.BootID, creds.BootTime; tests stand in). boot func() (proc.Boot, error) // Settle bounds settling an earlier turn (30 s). Settle time.Duration // mem is the turn record without a lock file (one process). // records keeps the turn record (lock+".turn"), pends the pending // cleanup (lock+".pending"). records, pends *proc.Store // debts is what unproven turns still owe (lock+".owed"). debts proc.Debts } // NewTurns makes the runner's one turn; lock is its file in the state // dir ("" keeps the turn, and its record, within this process). func NewTurns(lock string) *Turns { t := &Turns{lock: lock, lk: proc.NewLock(lock), records: &proc.Store{}, pends: &proc.Store{}} if lock != "" { t.debts.Path, t.records.Path, t.pends.Path = lock+".owed", lock+".turn", lock+".pending" } return t } // Sweep makes every turn sweep the runner user with p at its end: a // Mac's turns (MachineProcs). A table that may not sweep (Linux outside // a test's scope) makes every turn fail to begin; nil sweeps nothing. func (t *Turns) Sweep(p Procs) *Turns { t.sweep = p return t } func (t *Turns) owned() *Own { if t != nil && t.own != nil { return t.own } return runnerOwn } // table is the process table the turns' records are read with. func (t *Turns) table() Procs { if t != nil && t.sweep != nil { return t.sweep } return platformProcs } // Turn is one operation's hold on the Mac. type Turn struct { t *Turns ID string Op Op mu sync.Mutex rec turnRecord adopted []string unproven bool // finished is each launch's stop final note written; lost is set // once any evidence write of the turn failed (no launch after it). finished map[string]bool lost bool gave sync.Once given bool } // turnRecord is a turn on disk (lock+".turn"). type turnRecord struct { ID string `json:"id"` Op Op `json:"op"` Runner ProcID `json:"runner"` // Sweep: Before is the runner user's table when the turn began. Sweep bool `json:"sweep"` Before []ProcID `json:"before,omitempty"` Markers []string `json:"markers,omitempty"` Groups span `json:"groups,omitempty"` Sessions span `json:"sessions,omitempty"` // Killed is what the turn's stops signalled: each must be gone. Killed []ProcID `json:"killed,omitempty"` // Complete: the stop's final note was written, after every other. Complete bool `json:"complete,omitempty"` // Began and BootID: when, and in which boot, the turn began. Began time.Time `json:"began,omitzero"` BootID string `json:"boot_id,omitempty"` // FlagsKnown: written at the start, so UnsandboxedRan is meaningful; // UnsandboxedRan: something ran outside a sandbox in the turn. FlagsKnown bool `json:"flags_known,omitempty"` UnsandboxedRan bool `json:"unsandboxed_ran,omitempty"` } // Take waits for the turn and begins op: an earlier turn left unsettled // is settled first (or the take fails: ErrUnsettled), the runner user's // table is read for the sweep, and the record is written before Take // returns. Give it back with Give. func (t *Turns) Take(ctx context.Context, op Op) (*Turn, error) { if err := t.lk.Acquire(ctx); err != nil { return nil, err } u, err := t.begin(op, time.Now().Add(t.settleLimit())) if err != nil { t.lk.Release() return nil, err } return u, nil } func (t *Turns) settleLimit() time.Duration { if t.Settle > 0 { return t.Settle } return 30 * time.Second } // TryTake takes the turn for op only if it is free now (in this process // and the others) and begins; ok is false otherwise. func (t *Turns) TryTake(op Op) (*Turn, bool) { return t.tryTakeBy(op, time.Now().Add(t.settleLimit())) } // tryTakeBy is TryTake settling an earlier turn by deadline. func (t *Turns) tryTakeBy(op Op, deadline time.Time) (*Turn, bool) { if !t.lk.TryAcquire() { return nil, false } u, err := t.begin(op, deadline) if err != nil { t.lk.Release() return nil, false } return u, true } // Hold is op's turn in ctx: the one ctx already holds (what an // operation starts itself is its own: the probe run's gates), else a // new one, waited for, given back by give. On a nil Turns it holds // nothing (the test build's fake worker). func (t *Turns) Hold(ctx context.Context, op Op) (context.Context, func(), error) { if t == nil { return ctx, func() {}, nil } if HeldTurn(ctx, t) != nil { return ctx, func() {}, nil } u, err := t.Take(ctx, op) if err != nil { return ctx, func() {}, err } return u.Context(ctx), u.Give, nil } type turnKey struct{ t *Turns } // Context carries the turn to what the operation starts. func (u *Turn) Context(ctx context.Context) context.Context { return context.WithValue(ctx, turnKey{u.t}, u) } // HeldTurn is the turn of t that ctx holds, nil when none (or given). func HeldTurn(ctx context.Context, t *Turns) *Turn { if t == nil || ctx == nil { return nil } u, _ := ctx.Value(turnKey{t}).(*Turn) if u == nil { return nil } u.mu.Lock() defer u.mu.Unlock() if u.given { return nil } return u } // Give ends the turn. Its record goes only when every launch in it was // proven ended; otherwise it stays, and the next turn (in any runner // process) settles it before it begins. func (u *Turn) Give() { u.gave.Do(func() { u.mu.Lock() u.given = true keep := u.unproven u.mu.Unlock() if !keep { _ = u.t.dropTurn(u.ID) } u.t.lk.Release() }) } // Before is the runner user's table when the turn began (nil: no sweep). func (u *Turn) before() []ProcID { u.mu.Lock() defer u.mu.Unlock() if !u.rec.Sweep { return nil } return slices.Clone(u.rec.Before) } // launch puts an attempt's marker on the turn's record before anything // of it starts. func (u *Turn) launch(marker string) error { u.mu.Lock() defer u.mu.Unlock() if u.lost { // An earlier launch's evidence was not written: its record can // never be completed, so nothing more runs in this turn. return errors.New("mac: this turn lost a launch's evidence") } if !slices.Contains(u.rec.Markers, marker) { u.rec.Markers = append(u.rec.Markers, marker) } if u.finished == nil { u.finished = map[string]bool{} } u.finished[marker] = false // Incomplete again until this launch's stop writes its final note. u.rec.Complete = false if err := u.t.saveTurn(u.rec); err != nil { u.lost = true return err } return nil } // finish is launch marker's stop's final note: everything it made, // written whatever grew. The record is complete only once every launch // of the turn has finished its own writes and none was ever lost. func (u *Turn) finish(marker string, groups, sessions span, killed []ProcID) error { if err := u.note(groups, sessions, killed...); err != nil { return err } u.mu.Lock() defer u.mu.Unlock() if u.lost { return errors.New("mac: this turn lost a launch's evidence") } u.finished[marker] = true rec := u.rec rec.Complete = true for _, done := range u.finished { rec.Complete = rec.Complete && done } if err := u.t.saveTurn(rec); err != nil { u.lost = true return err } u.rec = rec return nil } // note adds groups and sessions an attempt made to the record (best // effort: the record before the start has the marker and the table). func (u *Turn) note(groups, sessions span, killed ...ProcID) error { u.mu.Lock() defer u.mu.Unlock() // Merged into a copy and kept only once written: a failed write is // tried again at the next note, and the caller stops the operation. rec := u.rec rec.Groups, rec.Sessions, rec.Killed = rec.Groups.Clone(), rec.Sessions.Clone(), slices.Clone(rec.Killed) grew := false for _, m := range []struct { to *span from span }{{&rec.Groups, groups}, {&rec.Sessions, sessions}} { if *m.to == nil { *m.to = span{} } for id, at := range m.from { if _, ok := (*m.to)[id]; !ok { (*m.to)[id] = at grew = true } } } for _, id := range killed { if !slices.Contains(rec.Killed, id) { rec.Killed = append(rec.Killed, id) grew = true } } if !grew { return nil } if err := u.t.saveTurn(rec); err != nil { u.lost = true return err } u.rec = rec return nil } // unprovenEnd keeps the record past Give: a launch's end is not proven. func (u *Turn) unprovenEnd() { u.mu.Lock() u.unproven = true u.mu.Unlock() } // owns: the attempt was launched in this turn, or the turn settles it // (Verify's recovery turn). func (u *Turn) owns(attempt string) bool { if u == nil { return false } u.mu.Lock() defer u.mu.Unlock() return slices.Contains(u.rec.Markers, attempt) || slices.Contains(u.adopted, attempt) } func (u *Turn) adopt(attempt string) { u.mu.Lock() u.adopted = append(u.adopted, attempt) u.mu.Unlock() } func (t *Turns) begin(op Op, deadline time.Time) (*Turn, error) { if err := t.settle(deadline); err != nil { return nil, err } b, _ := t.bootNow() var raw [8]byte _, _ = rand.Read(raw[:]) rec := turnRecord{ID: hex.EncodeToString(raw[:]), Op: op, Runner: proc.Self(), Began: time.Now(), BootID: b.ID, FlagsKnown: true} if t.sweep != nil { if !t.sweep.Sweeps() { return nil, ErrNoSweep } list, _, err := t.owned().Snapshot(time.Now().Add(30*time.Second), t.sweep, nil) if err != nil { return nil, err } rec.Sweep = true rec.Before = make([]ProcID, 0, len(list)) for _, q := range list { rec.Before = append(rec.Before, q.ID) } } if err := t.saveTurn(rec); err != nil { return nil, err } return &Turn{t: t, ID: rec.ID, Op: op, rec: rec}, nil } // settle ends what an earlier turn left: every process of its scope // (its seen groups and sessions, its markers and, if it swept, every // process of the runner user that did not exist when it began, but for // this runner's own and launchd's system agents) killed, checked again // before each signal, until none is left within Settle. A record of // another live runner process is never settled from here. func (t *Turns) settle(deadline time.Time) error { rec, ok, err := t.loadTurn() if err != nil || !ok { return err } if b, err := t.bootNow(); proc.Rebooted(rec.BootID, rec.Began, b, err) { // Nothing of a turn from an earlier boot runs now: no sweep (its // table is that boot's). Kept as a boot-qualified obligation, so // its attempts' proof skips the old boot's process checks. if err := t.debts.Owe(proc.Obligation{Markers: rec.Markers, Began: rec.Began, BootID: rec.BootID}); err != nil { return errors.Join(ErrUnsettled, err) } return t.dropTurn(rec.ID) } if rec.Runner != proc.Self() { // Another runner process's record: only once it is surely gone. if alive, known := proc.Alive(t.identities(), rec.Runner); alive || !known { return ErrUnsettled } } if rec.Sweep && (t.sweep == nil || !t.sweep.Sweeps()) { return ErrUnsettled } s := proc.Resume(t.table(), rec.Markers, rec.Sweep, rec.Before, rec.Groups, rec.Sessions, rec.Killed) out := s.Settle(t.owned(), deadline, 0, func() bool { return true }, nil) owe := func() proc.Obligation { o := s.Owe() o.Began, o.BootID, o.Before, o.FlagsKnown, o.UnsandboxedRan = rec.Began, rec.BootID, rec.Before, rec.FlagsKnown, rec.UnsandboxedRan return o } if out != proc.Left && !rec.Complete && len(rec.Markers) > 0 { // Its final note never came: what it left is not all on record, // so its attempts are never proven over (the Machines page says // so). Nothing of the runner user's is left: the Mac goes on. o := owe() o.Incomplete = true if err := t.debts.Owe(o); err != nil { return errors.Join(ErrUnsettled, err) } return t.dropTurn(rec.ID) } switch out { case proc.Proven: return t.dropTurn(rec.ID) case proc.Owed: // Nothing of the runner user's is left to kill, so the Mac may // take turns again; what another user now holds stays owed by // the attempt, and its proof waits for it. if err := t.debts.Owe(owe()); err != nil { return errors.Join(ErrUnsettled, err) } return t.dropTurn(rec.ID) } return ErrUnsettled } // unsettledFor: the stored turn record names attempt (its leftovers are // not settled yet). func (t *Turns) unsettledFor(attempt string) bool { rec, ok, err := t.loadTurn() return err != nil || ok && slices.Contains(rec.Markers, attempt) } func (t *Turns) saveTurn(rec turnRecord) error { if t.beforeWrite != nil { if err := t.beforeWrite(); err != nil { return err } } return t.records.Save(rec) } func (t *Turns) loadTurn() (turnRecord, bool, error) { var rec turnRecord ok, err := t.records.Load(&rec) if err == nil && ok && rec.ID == "" { err = errors.New("no id") } if err != nil { return turnRecord{}, false, errors.Join(ErrUnsettled, errors.New("mac: unreadable turn record"), err) } return rec, ok, nil } // dropTurn removes the stored record if it is still id's. func (t *Turns) dropTurn(id string) error { rec, ok, err := t.loadTurn() if err != nil || !ok || rec.ID != id { return err } return t.records.Drop() } func (t *Turns) identities() Procs { if t != nil && t.ids != nil { return t.ids } return platformProcs } func (t *Turns) pending() string { if t == nil || t.lock == "" { return "" } return t.lock + ".pending" } // pendingRecord is a sandboxed attempt whose T cleanup is not done yet: // written before anything of the attempt starts (and again with its // group once there is one), removed only once its end is proven and T // is cleaned. Runner is the runner process whose turn wrote it: only // that attempt in that process, or a later process once it is gone (a // restart), may finish it. type pendingRecord struct { Attempt string `json:"attempt"` PGID int `json:"pgid"` Before tempListing `json:"before"` Runner ProcID `json:"runner"` // Began and BootID: the turn's (a later boot proves the attempt over). Began time.Time `json:"began,omitzero"` BootID string `json:"boot_id,omitempty"` } // writePending records r durably. Without a lock file (tests) there is // nowhere to keep it. func (t *Turns) writePending(r pendingRecord) error { if t.pending() == "" { return nil } return t.pends.Save(r) } // readPending is the record an earlier attempt left; ok is false when // there is none. One that cannot be read is an error: nothing runs // until a person looks. func (t *Turns) readPending() (r pendingRecord, ok bool, err error) { if t.pending() == "" { return r, false, nil } if ok, err = t.pends.Load(&r); err == nil && ok && (r.Attempt == "" || r.Before == nil) { err = errors.New("incomplete") } if err != nil { return pendingRecord{}, false, errors.Join(ErrUserTemp, errors.New("mac: unreadable pending cleanup"), err) } return r, ok, nil } // mayFinish: u may finish r. Its owner: the attempt, in the runner // process that wrote it (the run itself, or its proof later). A restart: // the process that wrote it is gone (or was older than the owner field). // Never another turn of a live owner. func (t *Turns) mayFinish(u *Turn, r pendingRecord) bool { if r.Runner.PID == 0 { return true } if r.Runner == proc.Self() { return u.owns(r.Attempt) } // A restart only once the writer is surely gone: an identity that // cannot be read is not a dead one. alive, known := proc.Alive(t.identities(), r.Runner) return known && !alive } // dropPending removes the record once its cleanup is done. func (t *Turns) dropPending() error { if t.pending() == "" { return nil } if t.beforeDrop != nil { t.beforeDrop() } return t.pends.Drop() } // clearOwed judges what attempt owes (proc.Debts.Assess) before // deadline. It runs only holding u, a live turn of t: no operation can // start a process meanwhile. It removes nothing. func (t *Turns) clearOwed(u *Turn, attempt string, deadline time.Time) (rebooted, met bool, err error) { if u == nil || u.t != t || HeldTurn(u.Context(context.Background()), t) == nil { return false, false, ErrNoTurn } b, err := t.bootNow() rebooted, met = t.debts.Assess(attempt, t.table(), t.owned(), b, err, deadline) return rebooted, met, nil } // markUnsandboxed puts on the turn's record, durably and before it // starts, that something runs outside a sandbox in it: then only a // reboot can clear the turn if its end is not proven. func (u *Turn) markUnsandboxed() error { u.mu.Lock() defer u.mu.Unlock() rec := u.rec rec.UnsandboxedRan = true if err := u.t.saveTurn(rec); err != nil { u.lost = true return err } u.rec = rec return nil } func (t *Turns) bootNow() (proc.Boot, error) { if t.boot != nil { return t.boot() } return creds.Boot() } // Unproven is the Machines page's code for an attempt whose end is not // proven here, and how many unaccounted processes keep it so. func (t *Turns) Unproven() (string, int) { switch incomplete, left := t.debts.Unproven(); { case incomplete && left > 0: return wire.UnprovenProcessesLeft, left case incomplete: return wire.UnprovenRecordIncomplete, 0 } return "", 0 } // Incomplete reports whether an attempt's end can never be proven: its // turn's record was not complete (the Machines page says so). func (t *Turns) Incomplete() bool { return t.debts.Incomplete() } // Pending reports whether an attempt's cleanup is still to be done // (the warm waits for it: that attempt's end is not proven yet). func (t *Turns) Pending() bool { _, err := os.Lstat(t.pending()) return t.pending() != "" && err == nil }