oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package thin
2
3import (
4 "context"
5 "crypto/sha256"
6 "encoding/base64"
7 "encoding/hex"
8 "os"
9 "os/exec"
10 "path/filepath"
11 "strings"
12 "testing"
13 "time"
14
15 "amadan.net/oficina/equipo/internal/wire"
16)
17
18// stubGate records what it was asked to run and answers code.
19type stubGate struct {
20 ran [][]string
21 dirs []string
22 code int
23 sandbox string
24}
25
26func (g *stubGate) Sandbox() string { return wire.SandboxNone }
27func (g *stubGate) Run(_ context.Context, _, dir string, argv []string, _ time.Duration, record func(string) error) gateResult {
28 g.ran = append(g.ran, argv)
29 g.dirs = append(g.dirs, dir)
30 record("pg:1:stub")
31 head, _ := os.ReadFile(filepath.Join(dir, "Swipe.swift"))
32 return gateResult{code: g.code, terminated: true, output: "ran on " + strings.TrimSpace(string(head)), sandbox: g.sandbox}
33}
34func (g *stubGate) Verify(string) bool { return true }
35
36type workerRig struct {
37 w *Worker
38 gate *stubGate
39 r stepRow
40 base, commit string
41 pack, other []byte
42}
43
44func onePack(t *testing.T, dir, sha string) []byte {
45 t.Helper()
46 objects, err := exec.Command("git", "-C", dir, "rev-list", "--objects", "--no-walk", sha).Output()
47 if err != nil {
48 t.Fatal(err)
49 }
50 packer := exec.Command("git", "-C", dir, "pack-objects", "--stdout", "-q")
51 packer.Stdin = strings.NewReader(string(objects))
52 pack, err := packer.Output()
53 if err != nil {
54 t.Fatal(err)
55 }
56 return pack
57}
58
59func newWorkerRig(t *testing.T) *workerRig {
60 t.Helper()
61 root := t.TempDir()
62 seed := filepath.Join(root, "seed")
63 gitOut(t, root, "init", "-q", "-b", "main", seed)
64 os.MkdirAll(filepath.Join(seed, ".amadan"), 0755)
65 os.WriteFile(filepath.Join(seed, ".amadan", "ci"), []byte("#!/bin/sh\nxcodebuild test\n"), 0755)
66 os.WriteFile(filepath.Join(seed, "Swipe.swift"), []byte("let back = false\n"), 0644)
67 gitOut(t, seed, "add", "-A")
68 gitOut(t, seed, "commit", "-q", "-m", "base")
69 base := gitOut(t, seed, "rev-parse", "HEAD")
70 os.WriteFile(filepath.Join(seed, "Swipe.swift"), []byte("let back = true\n"), 0644)
71 gitOut(t, seed, "commit", "-q", "-am", "swipe")
72 commit := gitOut(t, seed, "rev-parse", "HEAD")
73 state := filepath.Join(root, "state")
74 os.MkdirAll(state, 0700)
75 s, err := OpenState(context.Background(), state)
76 if err != nil {
77 t.Fatal(err)
78 }
79 t.Cleanup(func() { s.Close() })
80 e := &Engineer{}
81 e.O.Runner.GitPath, e.O.Runner.StateDir, e.O.State = "/usr/bin/git", state, s
82 g := &stubGate{}
83 r := stepRow{DispatchCommand: wire.DispatchCommand{Person: "p@x", TaskID: "tk1", StepID: "s2", Attempt: 1, Specialist: wire.SpecialistChecks, Repo: "amadan.net/woodstar/woodstar", Branch: "equipo/tk1-swipe", BaseSHA: base, CandidateSHA: commit, Needs: []string{wire.TagMacOS, wire.TagXcode}}}
84 return &workerRig{w: &Worker{State: s, Engine: e, Gate: g, PackWait: 300 * time.Millisecond}, gate: g, r: r, base: base, commit: commit, pack: onePack(t, seed, commit), other: onePack(t, seed, base)}
85}
86
87func (x *workerRig) header() wire.TransferHeader {
88 return wire.TransferHeader{ID: "tr_1", Direction: wire.TransferInbound, Repo: x.r.Repo, TaskID: x.r.TaskID, StepID: x.r.StepID, Attempt: x.r.Attempt, BaseSHA: x.r.BaseSHA, CandidateSHA: x.r.CandidateSHA}
89}
90
91func (x *workerRig) chunk(t *testing.T, id string, h wire.TransferHeader, data []byte, index, total int, digest string) {
92 t.Helper()
93 if digest == "" {
94 sum := sha256.Sum256(data)
95 digest = hex.EncodeToString(sum[:])
96 }
97 if err := x.w.State.AcceptChunk(context.Background(), id, wire.Blob{Transfer: h, Index: index, Total: total, SHA256: digest, Data: base64.StdEncoding.EncodeToString(data)}); err != nil {
98 t.Fatal(err)
99 }
100}
101
102func (x *workerRig) run() wire.StepReport {
103 return x.w.Exec(context.Background(), x.r, func(wire.StepReport) {})
104}
105
106// The relayed candidate is checked out at exactly its SHA and the gate
107// runs there; the report proves termination by process group and says
108// the worker now holds the commit.
109func TestWorkerRunsChecksOnTheRelayedCandidate(t *testing.T) {
110 x := newWorkerRig(t)
111 x.chunk(t, "c1", x.header(), x.pack, 0, 1, "")
112 rep := x.run()
113 if rep.State != wire.StepDone || rep.Checks != wire.ChecksPassed || rep.Gate != ".amadan/ci" || rep.ExitCode == nil || *rep.ExitCode != 0 || !rep.Termination || rep.TerminationKind != wire.TerminationProcessGroup || len(rep.Have) != 1 || rep.Have[0] != x.commit {
114 t.Fatalf("report %+v", rep)
115 }
116 if len(x.gate.ran) != 1 || !strings.Contains(rep.Output, "let back = true") {
117 t.Fatalf("gate %v output %q", x.gate.ran, rep.Output)
118 }
119 if _, err := os.Stat(x.gate.dirs[0]); !os.IsNotExist(err) {
120 t.Fatal("the checks tree was kept")
121 }
122 x.gate.code = 65
123 x.r.Attempt = 2
124 h := x.header()
125 h.ID = "tr_2"
126 x.chunk(t, "c2", h, x.pack, 0, 1, "")
127 if rep = x.run(); rep.State != wire.StepDone || rep.Checks != wire.ChecksFailed || *rep.ExitCode != 65 {
128 t.Fatalf("failing gate %+v", rep)
129 }
130}
131
132// M7 at the receiver: a pack whose digest is wrong, a pack that does not
133// hold the dispatched SHA, chunks under another task's header, and a
134// missing chunk are all refused before the gate runs.
135func TestWorkerRefusesTamperedPacks(t *testing.T) {
136 for name, feed := range map[string]func(*testing.T, *workerRig){
137 "bad sha256": func(t *testing.T, x *workerRig) {
138 x.chunk(t, "c1", x.header(), x.pack, 0, 1, strings.Repeat("0", 64))
139 },
140 "wrong SHA": func(t *testing.T, x *workerRig) { x.chunk(t, "c1", x.header(), x.other, 0, 1, "") },
141 "another task's header": func(t *testing.T, x *workerRig) {
142 h := x.header()
143 h.TaskID = "tkother"
144 x.chunk(t, "c1", h, x.pack, 0, 1, "")
145 },
146 "missing chunk": func(t *testing.T, x *workerRig) {
147 half := len(x.pack) / 2
148 sum := sha256.Sum256(x.pack)
149 x.chunk(t, "c1", x.header(), x.pack[:half], 0, 2, hex.EncodeToString(sum[:]))
150 },
151 "bytes changed": func(t *testing.T, x *workerRig) {
152 bad := append([]byte{}, x.pack...)
153 bad[len(bad)/2] ^= 0xff
154 sum := sha256.Sum256(x.pack)
155 x.chunk(t, "c1", x.header(), bad, 0, 1, hex.EncodeToString(sum[:]))
156 },
157 } {
158 t.Run(name, func(t *testing.T) {
159 x := newWorkerRig(t)
160 feed(t, x)
161 rep := x.run()
162 if rep.State != wire.StepFailed || rep.Reason != "candidate_unavailable" || !rep.Termination || len(x.gate.ran) != 0 {
163 t.Fatalf("%s: %+v gate %v", name, rep, x.gate.ran)
164 }
165 })
166 }
167}
168
169// A withdrawn attempt never runs: the start authorization is refused and
170// it ends cancelled (withdrawn) with nothing run. A dispatch whose needs
171// the runner lacks is refused (placement_refused) and marks the
172// capability report stale.
173func TestWorkerStartAndPlacement(t *testing.T) {
174 x := newWorkerRig(t)
175 x.chunk(t, "c1", x.header(), x.pack, 0, 1, "")
176 x.w.Engine.AuthorizeStep = func(context.Context, string, int64) error { return ErrWithdrawn }
177 if rep := x.run(); rep.State != wire.StepCancelled || rep.Reason != "withdrawn" || !rep.Termination || len(x.gate.ran) != 0 {
178 t.Fatalf("withdrawn %+v", rep)
179 }
180 stale := false
181 guard := placementGuard(func() []string { return []string{wire.TagLinux} }, func() { stale = true }, x.w.Exec)
182 if rep := guard(context.Background(), x.r, func(wire.StepReport) {}); rep.State != wire.StepFailed || rep.Reason != "placement_refused" || !rep.Termination || !stale || len(x.gate.ran) != 0 {
183 t.Fatalf("placement %+v stale %v", rep, stale)
184 }
185}
186