package thin import ( "context" "errors" "os" "os/exec" "path/filepath" "strings" "time" "amadan.net/oficina/equipo/internal/runner/mac" "amadan.net/oficina/equipo/internal/runner/workspace" "amadan.net/oficina/equipo/internal/wire" "amadan.net/oficina/equipo/internal/wire/forgekey" ) // A worker's checks of a candidate the primary relays as a pack (Mac // runners spec ยง1.4): the pack into the worker's store, the candidate's // tree checked out afresh, the gate run there. // checks runs one checks attempt placed on this worker. func (w *Worker) checks(ctx context.Context, r stepRow, progress func(wire.StepReport)) wire.StepReport { rep := judgeReport(r) rep.Findings = []wire.Finding{} end := func(state, reason string) wire.StepReport { rep.State, rep.Reason, rep.Termination = state, reason, true return rep } if r.Specialist != wire.SpecialistChecks || !forgekey.ValidHub(r.Repo) || !shaPattern.MatchString(r.CandidateSHA) { // Only checks are placed on workers until slice F. return end(wire.StepFailed, "placement_refused") } // Ready first, outside mu: a step waiting for the probes is not a // step running, and the updater's hold must not wait for it. if w.Ready != nil { if err := w.Ready(ctx); err != nil { return end(wire.StepCancelled, "cancelled") } } w.mu.Lock() defer w.mu.Unlock() // An update may have swapped the binary and stopped the worker while // this step waited for mu. if ctx.Err() != nil { return end(wire.StepCancelled, "cancelled") } // The attempt's marker is on record before anything of it runs: every // process it starts (git here, the gate later) carries it, so a // restarted runner can find them even if no group was recorded. w.marker = "checks/" + stepKey(r) defer func() { w.marker = "" }() if err := w.State.setStepNamespace(ctx, r, mac.RecordID(0, w.marker)); err != nil { w.Engine.log("worker record", err) return end(wire.StepFailed, "workspace_refused") } if err := w.Engine.lease(ctx, r); err != nil { return end(wire.StepCancelled, leaseReason(err)) } defer func() { _ = w.State.dropStepChunks(context.WithoutCancel(ctx), r.StepID, r.Attempt) }() pack, err := w.awaitPack(ctx, r, wire.TransferHeader{Direction: wire.TransferInbound, Repo: r.Repo, TaskID: r.TaskID, StepID: r.StepID, Attempt: r.Attempt, BaseSHA: r.BaseSHA, CandidateSHA: r.CandidateSHA}) switch { case ctx.Err() != nil: return end(wire.StepCancelled, "cancelled") case err != nil: w.Engine.log("worker pack", err) return end(wire.StepFailed, "candidate_unavailable") } store := w.objects(r.Repo) if err := w.index(ctx, store, pack, r.CandidateSHA); err != nil { w.Engine.log("worker index", err) return end(wire.StepFailed, "candidate_unavailable") } rep.Have = []string{r.CandidateSHA} dir := filepath.Join(w.stepsDir(), stepKey(r)) defer os.RemoveAll(dir) tree := workspace.TaskTree{Dir: filepath.Join(dir, "tree"), GitDir: store, Git: w.Engine.O.Runner.GitPath, Branch: r.Branch, Base: r.BaseSHA} if err := w.checkout(ctx, tree, r.CandidateSHA); err != nil { w.Engine.log("worker tree", err) return end(wire.StepFailed, "workspace_refused") } progress(rep) g, reason, ok := w.find(tree.Dir) switch { case !ok: rep.LogTail = "No checks found: no .amadan/ci.d, .amadan/ci or make ci target." rep.Checks = wire.ChecksNone return end(wire.StepDone, "") case reason != "": rep.Checks = wire.ChecksCannotRun return end(wire.StepDone, reason) } if err := w.Engine.checkRepository(ctx, tree, r.CandidateSHA); err != nil { w.Engine.log("worker checks repository", err) return end(wire.StepFailed, "workspace_refused") } limit := w.MaxStep if limit <= 0 { limit = DefaultMaxStep } res := w.Gate.Run(withUnsandboxed(ctx, r.Unsandboxed), "checks/"+stepKey(r), tree.Dir, g.argv, limit, func(id string) error { return w.State.setStepNamespace(context.WithoutCancel(ctx), r, id) }) if res.reason == wire.ReasonSandboxUnproven { // Nothing ran: the Mac's sandbox is not proven and nobody chose // to run outside it. The instance puts the step back to wait. return end(wire.StepFailed, wire.ReasonSandboxUnproven) } rep.TerminationKind, rep.ChecksSandbox = wire.TerminationProcessGroup, res.sandbox rep.Gate, rep.Output, rep.LogTail = g.name, res.output, lastLines(res.output, stepTailLines, wire.MaxLogTail) if !res.terminated { rep.State, rep.Reason, rep.Termination = wire.StepFailed, firstNonEmpty(res.reason, "provider_failed"), false return rep } if ctx.Err() != nil { return end(wire.StepCancelled, "cancelled") } done := func(outcome, reason string) wire.StepReport { rep.Checks = outcome return end(wire.StepDone, reason) } switch { case res.reason == "checks_timeout": rep.Gate = "" return done(wire.ChecksCannotRun, "checks_timeout") case res.reason != "": rep.Gate, rep.Output = "", "" return done(wire.ChecksCannotRun, "checks_unavailable") } code := res.code rep.ExitCode = &code if code == 0 { return done(wire.ChecksPassed, "") } return done(wire.ChecksFailed, "") } // awaitPack waits for every chunk of the attempt's inbound transfer // (the transfer its first chunk names) and reassembles it: State.pack // refuses it unless every chunk's header is want (what the step row says, // with that id). func (w *Worker) awaitPack(ctx context.Context, r stepRow, want wire.TransferHeader) ([]byte, error) { wait := w.PackWait if wait <= 0 { wait = 10 * time.Minute } deadline := time.Now().Add(wait) for { h, ok, err := w.State.inboundHeader(ctx, r) if err != nil { return nil, err } if ok { // State.pack is the one comparison: every chunk's header, // the first included, must be want. want.ID = h.ID pack, err := w.State.pack(ctx, want) if !errors.Is(err, ErrPackIncomplete) { return pack, err } } if time.Now().After(deadline) { return nil, ErrPackIncomplete } select { case <-ctx.Done(): return nil, ctx.Err() case <-time.After(200 * time.Millisecond): } } } // index adds the pack to the repository's store and requires that it // yields exactly the candidate, a commit whose whole tree is present. func (w *Worker) index(ctx context.Context, store string, pack []byte, sha string) error { if _, err := os.Stat(store); err != nil { if err := os.MkdirAll(store, 0700); err != nil { return err } if _, err := w.git(ctx, nil, "init", "-q", "--bare", "--template=", "--object-format="+map[bool]string{true: "sha256", false: "sha1"}[len(sha) == 64], store); err != nil { return err } } if _, err := w.git(ctx, strings.NewReader(string(pack)), "--git-dir="+store, "index-pack", "--stdin"); err != nil { return err } if kind, err := w.git(ctx, nil, "--git-dir="+store, "cat-file", "-t", "--end-of-options", sha); err != nil || kind != "commit" { return errors.New("the pack does not hold the candidate") } _, err := w.git(ctx, nil, "--git-dir="+store, "rev-list", "--objects", "--no-walk", "--end-of-options", sha) return err } // checkout writes the candidate's tree into a fresh directory. func (w *Worker) checkout(ctx context.Context, t workspace.TaskTree, sha string) error { if err := os.MkdirAll(t.Dir, 0700); err != nil { return err } index := filepath.Join(filepath.Dir(t.Dir), "index") env := []string{"GIT_INDEX_FILE=" + index} run := func(args ...string) error { cmd := exec.CommandContext(ctx, w.Engine.O.Runner.GitPath, append([]string{"--git-dir=" + t.GitDir, "--work-tree=" + t.Dir}, args...)...) for k, v := range workspace.GitEnvironment() { cmd.Env = append(cmd.Env, k+"="+v) } cmd.Env = append(cmd.Env, append(env, "HOME=/nonexistent", "EQUIPO_ATTEMPT="+w.marker)...) cmd.Dir = t.Dir _, err := ownOutput(cmd) return err } if err := run("read-tree", "--end-of-options", sha); err != nil { return err } if err := run("checkout-index", "-a", "-f"); err != nil { return err } return os.Remove(index) }