| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "os" |
| 7 | "os/exec" |
| 8 | "path/filepath" |
| 9 | "strings" |
| 10 | "time" |
| 11 | |
| 12 | "amadan.net/oficina/equipo/internal/runner/mac" |
| 13 | "amadan.net/oficina/equipo/internal/runner/workspace" |
| 14 | "amadan.net/oficina/equipo/internal/wire" |
| 15 | "amadan.net/oficina/equipo/internal/wire/forgekey" |
| 16 | ) |
| 17 | |
| 18 | // A worker's checks of a candidate the primary relays as a pack (Mac |
| 19 | // runners spec §1.4): the pack into the worker's store, the candidate's |
| 20 | // tree checked out afresh, the gate run there. |
| 21 | |
| 22 | // checks runs one checks attempt placed on this worker. |
| 23 | func (w *Worker) checks(ctx context.Context, r stepRow, progress func(wire.StepReport)) wire.StepReport { |
| 24 | rep := judgeReport(r) |
| 25 | rep.Findings = []wire.Finding{} |
| 26 | end := func(state, reason string) wire.StepReport { |
| 27 | rep.State, rep.Reason, rep.Termination = state, reason, true |
| 28 | return rep |
| 29 | } |
| 30 | if r.Specialist != wire.SpecialistChecks || !forgekey.ValidHub(r.Repo) || !shaPattern.MatchString(r.CandidateSHA) { |
| 31 | // Only checks are placed on workers until slice F. |
| 32 | return end(wire.StepFailed, "placement_refused") |
| 33 | } |
| 34 | // Ready first, outside mu: a step waiting for the probes is not a |
| 35 | // step running, and the updater's hold must not wait for it. |
| 36 | if w.Ready != nil { |
| 37 | if err := w.Ready(ctx); err != nil { |
| 38 | return end(wire.StepCancelled, "cancelled") |
| 39 | } |
| 40 | } |
| 41 | w.mu.Lock() |
| 42 | defer w.mu.Unlock() |
| 43 | // An update may have swapped the binary and stopped the worker while |
| 44 | // this step waited for mu. |
| 45 | if ctx.Err() != nil { |
| 46 | return end(wire.StepCancelled, "cancelled") |
| 47 | } |
| 48 | // The attempt's marker is on record before anything of it runs: every |
| 49 | // process it starts (git here, the gate later) carries it, so a |
| 50 | // restarted runner can find them even if no group was recorded. |
| 51 | w.marker = "checks/" + stepKey(r) |
| 52 | defer func() { w.marker = "" }() |
| 53 | if err := w.State.setStepNamespace(ctx, r, mac.RecordID(0, w.marker)); err != nil { |
| 54 | w.Engine.log("worker record", err) |
| 55 | return end(wire.StepFailed, "workspace_refused") |
| 56 | } |
| 57 | if err := w.Engine.lease(ctx, r); err != nil { |
| 58 | return end(wire.StepCancelled, leaseReason(err)) |
| 59 | } |
| 60 | defer func() { _ = w.State.dropStepChunks(context.WithoutCancel(ctx), r.StepID, r.Attempt) }() |
| 61 | 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}) |
| 62 | switch { |
| 63 | case ctx.Err() != nil: |
| 64 | return end(wire.StepCancelled, "cancelled") |
| 65 | case err != nil: |
| 66 | w.Engine.log("worker pack", err) |
| 67 | return end(wire.StepFailed, "candidate_unavailable") |
| 68 | } |
| 69 | store := w.objects(r.Repo) |
| 70 | if err := w.index(ctx, store, pack, r.CandidateSHA); err != nil { |
| 71 | w.Engine.log("worker index", err) |
| 72 | return end(wire.StepFailed, "candidate_unavailable") |
| 73 | } |
| 74 | rep.Have = []string{r.CandidateSHA} |
| 75 | dir := filepath.Join(w.stepsDir(), stepKey(r)) |
| 76 | defer os.RemoveAll(dir) |
| 77 | tree := workspace.TaskTree{Dir: filepath.Join(dir, "tree"), GitDir: store, Git: w.Engine.O.Runner.GitPath, Branch: r.Branch, Base: r.BaseSHA} |
| 78 | if err := w.checkout(ctx, tree, r.CandidateSHA); err != nil { |
| 79 | w.Engine.log("worker tree", err) |
| 80 | return end(wire.StepFailed, "workspace_refused") |
| 81 | } |
| 82 | progress(rep) |
| 83 | g, reason, ok := w.find(tree.Dir) |
| 84 | switch { |
| 85 | case !ok: |
| 86 | rep.LogTail = "No checks found: no .amadan/ci.d, .amadan/ci or make ci target." |
| 87 | rep.Checks = wire.ChecksNone |
| 88 | return end(wire.StepDone, "") |
| 89 | case reason != "": |
| 90 | rep.Checks = wire.ChecksCannotRun |
| 91 | return end(wire.StepDone, reason) |
| 92 | } |
| 93 | if err := w.Engine.checkRepository(ctx, tree, r.CandidateSHA); err != nil { |
| 94 | w.Engine.log("worker checks repository", err) |
| 95 | return end(wire.StepFailed, "workspace_refused") |
| 96 | } |
| 97 | limit := w.MaxStep |
| 98 | if limit <= 0 { |
| 99 | limit = DefaultMaxStep |
| 100 | } |
| 101 | res := w.Gate.Run(withUnsandboxed(ctx, r.Unsandboxed), "checks/"+stepKey(r), tree.Dir, g.argv, limit, func(id string) error { |
| 102 | return w.State.setStepNamespace(context.WithoutCancel(ctx), r, id) |
| 103 | }) |
| 104 | if res.reason == wire.ReasonSandboxUnproven { |
| 105 | // Nothing ran: the Mac's sandbox is not proven and nobody chose |
| 106 | // to run outside it. The instance puts the step back to wait. |
| 107 | return end(wire.StepFailed, wire.ReasonSandboxUnproven) |
| 108 | } |
| 109 | rep.TerminationKind, rep.ChecksSandbox = wire.TerminationProcessGroup, res.sandbox |
| 110 | rep.Gate, rep.Output, rep.LogTail = g.name, res.output, lastLines(res.output, stepTailLines, wire.MaxLogTail) |
| 111 | if !res.terminated { |
| 112 | rep.State, rep.Reason, rep.Termination = wire.StepFailed, firstNonEmpty(res.reason, "provider_failed"), false |
| 113 | return rep |
| 114 | } |
| 115 | if ctx.Err() != nil { |
| 116 | return end(wire.StepCancelled, "cancelled") |
| 117 | } |
| 118 | done := func(outcome, reason string) wire.StepReport { |
| 119 | rep.Checks = outcome |
| 120 | return end(wire.StepDone, reason) |
| 121 | } |
| 122 | switch { |
| 123 | case res.reason == "checks_timeout": |
| 124 | rep.Gate = "" |
| 125 | return done(wire.ChecksCannotRun, "checks_timeout") |
| 126 | case res.reason != "": |
| 127 | rep.Gate, rep.Output = "", "" |
| 128 | return done(wire.ChecksCannotRun, "checks_unavailable") |
| 129 | } |
| 130 | code := res.code |
| 131 | rep.ExitCode = &code |
| 132 | if code == 0 { |
| 133 | return done(wire.ChecksPassed, "") |
| 134 | } |
| 135 | return done(wire.ChecksFailed, "") |
| 136 | } |
| 137 | |
| 138 | // awaitPack waits for every chunk of the attempt's inbound transfer |
| 139 | // (the transfer its first chunk names) and reassembles it: State.pack |
| 140 | // refuses it unless every chunk's header is want (what the step row says, |
| 141 | // with that id). |
| 142 | func (w *Worker) awaitPack(ctx context.Context, r stepRow, want wire.TransferHeader) ([]byte, error) { |
| 143 | wait := w.PackWait |
| 144 | if wait <= 0 { |
| 145 | wait = 10 * time.Minute |
| 146 | } |
| 147 | deadline := time.Now().Add(wait) |
| 148 | for { |
| 149 | h, ok, err := w.State.inboundHeader(ctx, r) |
| 150 | if err != nil { |
| 151 | return nil, err |
| 152 | } |
| 153 | if ok { |
| 154 | // State.pack is the one comparison: every chunk's header, |
| 155 | // the first included, must be want. |
| 156 | want.ID = h.ID |
| 157 | pack, err := w.State.pack(ctx, want) |
| 158 | if !errors.Is(err, ErrPackIncomplete) { |
| 159 | return pack, err |
| 160 | } |
| 161 | } |
| 162 | if time.Now().After(deadline) { |
| 163 | return nil, ErrPackIncomplete |
| 164 | } |
| 165 | select { |
| 166 | case <-ctx.Done(): |
| 167 | return nil, ctx.Err() |
| 168 | case <-time.After(200 * time.Millisecond): |
| 169 | } |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | // index adds the pack to the repository's store and requires that it |
| 174 | // yields exactly the candidate, a commit whose whole tree is present. |
| 175 | func (w *Worker) index(ctx context.Context, store string, pack []byte, sha string) error { |
| 176 | if _, err := os.Stat(store); err != nil { |
| 177 | if err := os.MkdirAll(store, 0700); err != nil { |
| 178 | return err |
| 179 | } |
| 180 | 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 { |
| 181 | return err |
| 182 | } |
| 183 | } |
| 184 | if _, err := w.git(ctx, strings.NewReader(string(pack)), "--git-dir="+store, "index-pack", "--stdin"); err != nil { |
| 185 | return err |
| 186 | } |
| 187 | if kind, err := w.git(ctx, nil, "--git-dir="+store, "cat-file", "-t", "--end-of-options", sha); err != nil || kind != "commit" { |
| 188 | return errors.New("the pack does not hold the candidate") |
| 189 | } |
| 190 | _, err := w.git(ctx, nil, "--git-dir="+store, "rev-list", "--objects", "--no-walk", "--end-of-options", sha) |
| 191 | return err |
| 192 | } |
| 193 | |
| 194 | // checkout writes the candidate's tree into a fresh directory. |
| 195 | func (w *Worker) checkout(ctx context.Context, t workspace.TaskTree, sha string) error { |
| 196 | if err := os.MkdirAll(t.Dir, 0700); err != nil { |
| 197 | return err |
| 198 | } |
| 199 | index := filepath.Join(filepath.Dir(t.Dir), "index") |
| 200 | env := []string{"GIT_INDEX_FILE=" + index} |
| 201 | run := func(args ...string) error { |
| 202 | cmd := exec.CommandContext(ctx, w.Engine.O.Runner.GitPath, append([]string{"--git-dir=" + t.GitDir, "--work-tree=" + t.Dir}, args...)...) |
| 203 | for k, v := range workspace.GitEnvironment() { |
| 204 | cmd.Env = append(cmd.Env, k+"="+v) |
| 205 | } |
| 206 | cmd.Env = append(cmd.Env, append(env, "HOME=/nonexistent", "EQUIPO_ATTEMPT="+w.marker)...) |
| 207 | cmd.Dir = t.Dir |
| 208 | _, err := ownOutput(cmd) |
| 209 | return err |
| 210 | } |
| 211 | if err := run("read-tree", "--end-of-options", sha); err != nil { |
| 212 | return err |
| 213 | } |
| 214 | if err := run("checkout-index", "-a", "-f"); err != nil { |
| 215 | return err |
| 216 | } |
| 217 | return os.Remove(index) |
| 218 | } |
| 219 | |