oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package release
2
3import (
4 "bytes"
5 "os"
6 "os/exec"
7 "path/filepath"
8 "strings"
9 "testing"
10)
11
12const (
13 cutoverVersion = "abc1234"
14 oldInstanceID = "OLDINSTANCE000000000000000"
15 newInstanceID = "NEWINSTANCE000000000000000"
16)
17
18// cutoverRig runs scripts/cutover-thin.sh against stub carlos, systemctl,
19// curl and make on a temporary HOME. Nothing here reaches a real service.
20type cutoverRig struct {
21 t *testing.T
22 root, home, runner string
23 script string
24 log string
25 serviceEnv, unit []byte
26}
27
28func newCutoverRig(t *testing.T) *cutoverRig {
29 t.Helper()
30 root := t.TempDir()
31 r := &cutoverRig{t: t, root: root, home: filepath.Join(root, "home"), log: filepath.Join(root, "calls.log")}
32 r.runner = filepath.Join(r.home, ".local/share/equipo-runner")
33 repo := filepath.Join(root, "repo")
34 src, err := os.ReadFile("../../scripts/cutover-thin.sh")
35 r.must(err)
36 r.script = filepath.Join(repo, "scripts", "cutover-thin.sh")
37 r.write(r.script, string(src), 0700)
38 r.write(filepath.Join(repo, "releases", "equipo-linux-arm64-"+cutoverVersion), "instance", 0600)
39 release := filepath.Join(repo, "releases", "equipo-runner-linux-amd64-"+cutoverVersion)
40 // The staged runner's enrol records the instance id it was given.
41 // It also answers verify-installed, with the tool proxy it was told to use.
42 r.write(filepath.Join(release, "equipo-runner"), "#!/bin/sh\n"+rendererStub(r.log)+"if [ \"$1\" = verify-installed ]; then echo \"equipo-runner verify-installed $EQUIPO_TOOL_PROXY_PATH\" >> "+r.log+"; [ ! -e "+filepath.Join(root, "verifyfail")+" ]; exit; fi\necho \"equipo-runner $1\" >> "+r.log+"\necho \"$EQUIPO_INSTANCE_ID\" > "+filepath.Join(root, "enrolled")+"\necho new > \"$EQUIPO_RUNNER_STATE_DIR/credentials.json\"\n"+linkedScanner+linkedRenderer, 0700)
43 r.write(filepath.Join(release, RendererArchive), string(rendererArchiveBytes), 0600)
44 r.write(filepath.Join(release, "equipo-tool-proxy"), "proxy", 0700)
45 r.write(filepath.Join(release, "gitleaks"), scannerBytes, 0700)
46 r.serviceEnv = []byte("EQUIPO_ORIGIN=\"https://equipo.bds.oncarlos.com\"\nEQUIPO_INSTANCE_ID=\"" + oldInstanceID + "\"\nEQUIPO_TOOL_PROXY_PATH=\"/old/equipo-tool-proxy\"\nEQUIPO_RUNNER_STATE_DIR=\"" + filepath.Join(r.runner, "state") + "\"\nEQUIPO_SCRATCH_ROOT=\"/old/scratch\"\nEQUIPO_WORKSPACE_ROOT=\"/old/work\"\n")
47 r.unit = []byte("[Service]\nExecStart=/old/equipo-runner run\nRestart=on-failure\nRestartSec=5\n")
48 r.write(filepath.Join(r.runner, "service.env"), string(r.serviceEnv), 0600)
49 r.write(filepath.Join(r.runner, "equipo-runner.service"), string(r.unit), 0600)
50 r.write(filepath.Join(r.runner, "state", "credentials.json"), "old", 0600)
51 r.write(filepath.Join(root, "served"), "prev999\n", 0600)
52 r.write(filepath.Join(root, "teamid"), newInstanceID, 0600)
53 bin := filepath.Join(root, "bin")
54 log := "echo \"$(basename $0) $*\" >> " + r.log + "\n"
55 r.write(filepath.Join(bin, "systemctl"), "#!/bin/sh\n"+log, 0700)
56 r.write(filepath.Join(bin, "make"), "#!/bin/sh\n"+log, 0700)
57 r.write(filepath.Join(bin, "curl"), "#!/bin/sh\ncat "+filepath.Join(root, "served")+"\n", 0700)
58 r.write(filepath.Join(bin, "carlos"), "#!/bin/sh\n"+log+`case "$1 $2" in
59"env list") [ -e `+filepath.Join(root, "envfail")+` ] && exit 1; printf 'using console\nKEY VALUE\nEQUIPO_ALWAYS_ON 1\nEQUIPO_ORIGIN https://equipo.bds.oncarlos.com\n' ;;
60"db pull") for a; do case $prev in --out) python3 -c "import sqlite3,sys; c=sqlite3.connect(sys.argv[1]); [c.execute('create table '+t+'(x)') for t in ('members','tasks','conversation_messages','runners')]; c.commit()" "$a" ;; esac; prev=$a; done ;;
61"db query") printf 'id\n%s\n' "$(cat `+filepath.Join(root, "teamid")+`)" ;;
62deploy*) [ -e `+filepath.Join(root, "deployfail")+` ] && exit 1; for a; do case $prev in --version) echo "$a" > `+filepath.Join(root, "served")+` ;; esac; prev=$a; done ;;
63promote*) shift; for a; do last2=$last; last=$a; done; echo "$last2" > `+filepath.Join(root, "served")+` ;;
64esac
65`, 0700)
66 return r
67}
68
69func (r *cutoverRig) must(err error) {
70 r.t.Helper()
71 if err != nil {
72 r.t.Fatal(err)
73 }
74}
75
76func (r *cutoverRig) write(path, body string, mode os.FileMode) {
77 r.t.Helper()
78 r.must(os.MkdirAll(filepath.Dir(path), 0700))
79 r.must(os.WriteFile(path, []byte(body), mode))
80}
81
82func (r *cutoverRig) run(args ...string) (string, error) {
83 cmd := exec.Command("bash", append([]string{r.script}, args...)...)
84 cmd.Env = []string{"HOME=" + r.home, "PATH=" + filepath.Join(r.root, "bin") + ":/usr/bin:/bin", "CUTOVER_YES=1", "CUTOVER_ID_TRIES=2", "CUTOVER_ID_WAIT=0", "LANG=C.UTF-8"}
85 out, err := cmd.CombinedOutput()
86 return string(out), err
87}
88
89// answer runs the script without CUTOVER_YES, answering its step prompts
90// from input.
91func (r *cutoverRig) answer(input string, args ...string) (string, error) {
92 cmd := exec.Command("bash", append([]string{r.script}, args...)...)
93 cmd.Env = []string{"HOME=" + r.home, "PATH=" + filepath.Join(r.root, "bin") + ":/usr/bin:/bin", "CUTOVER_ID_TRIES=2", "CUTOVER_ID_WAIT=0", "LANG=C.UTF-8"}
94 cmd.Stdin = strings.NewReader(input)
95 out, err := cmd.CombinedOutput()
96 return string(out), err
97}
98
99func (r *cutoverRig) read(path string) string {
100 raw, _ := os.ReadFile(path)
101 return string(raw)
102}
103
104// The runner enrols with the new instance's id, read from the new database
105// before any runner change; a replica still showing the old instance stops
106// the cutover with the runner untouched.
107func TestCutoverEnrolsWithTheNewInstance(t *testing.T) {
108 r := newCutoverRig(t)
109 out, err := r.run(cutoverVersion, "--execute")
110 if err != nil {
111 t.Fatalf("cutover: %v\n%s", err, out)
112 }
113 if got := strings.TrimSpace(r.read(filepath.Join(r.root, "enrolled"))); got != newInstanceID {
114 t.Fatalf("enrolled with instance %q, want %q", got, newInstanceID)
115 }
116 env := r.read(filepath.Join(r.runner, "service.env"))
117 if !strings.Contains(env, newInstanceID) || !strings.Contains(env, filepath.Join(r.runner, "releases", cutoverVersion, "equipo-tool-proxy")) {
118 t.Fatalf("runner config not updated:\n%s", env)
119 }
120 if strings.Index(out, "select id from teams") > strings.Index(out, "state.pre-thin-") {
121 t.Fatal("instance id read after the runner state moved")
122 }
123 calls := r.read(r.log)
124 for _, want := range []string{"env set --app equipo --account oficina --console https://console.carloku.com --no-prompt EQUIPO_DATABASE=equipo-v1.db", "env unset --app equipo --account oficina --console https://console.carloku.com EQUIPO_ALWAYS_ON", "--swap hold"} {
125 if !strings.Contains(calls, want) {
126 t.Fatalf("missing call %q:\n%s", want, calls)
127 }
128 }
129 // A completed cutover is not run again.
130 if out, err = r.run(cutoverVersion, "--execute"); err == nil || !strings.Contains(out, "complete") {
131 t.Fatalf("second cutover allowed: %v %s", err, out)
132 }
133}
134
135func TestCutoverRefusesWithoutANewInstanceID(t *testing.T) {
136 r := newCutoverRig(t)
137 r.write(filepath.Join(r.root, "teamid"), oldInstanceID, 0600)
138 if out, err := r.run(cutoverVersion, "--execute"); err == nil {
139 t.Fatalf("cutover continued with the old instance id:\n%s", out)
140 }
141 if r.read(filepath.Join(r.runner, "state", "credentials.json")) != "old" || r.read(filepath.Join(r.runner, "service.env")) != string(r.serviceEnv) {
142 t.Fatal("runner changed before the new instance id was known")
143 }
144}
145
146// Before its deploy begins, rollback restores the complete prior
147// configuration. Once a deploy may have begun it is refused: on CARLOS the
148// activator passes the app an absolute --db, so a deploy migrates the old
149// database in place and the previous version cannot read it.
150func TestCutoverRollbackRestoresEverythingBeforeTheDeploy(t *testing.T) {
151 r := newCutoverRig(t)
152 if out, err := r.answer("yes\nyes\nyes\nyes\nno\n", cutoverVersion, "--execute"); err == nil || !strings.Contains(out, "stopped before: 5") {
153 t.Fatalf("cutover did not stop before its deploy: %v\n%s", err, out)
154 }
155 out, err := r.run("rollback", "--execute")
156 if err != nil {
157 t.Fatalf("rollback: %v\n%s", err, out)
158 }
159 if !bytes.Equal([]byte(r.read(filepath.Join(r.runner, "service.env"))), r.serviceEnv) || !bytes.Equal([]byte(r.read(filepath.Join(r.runner, "equipo-runner.service"))), r.unit) {
160 t.Fatal("runner configuration not restored exactly")
161 }
162 if r.read(filepath.Join(r.runner, "state", "credentials.json")) != "old" {
163 t.Fatal("old runner state not kept")
164 }
165 calls := r.read(r.log)
166 for _, want := range []string{"env unset --app equipo --account oficina --console https://console.carloku.com EQUIPO_DATABASE", "env set --app equipo --account oficina --console https://console.carloku.com --no-prompt EQUIPO_ALWAYS_ON=1", "promote --app equipo --account oficina --console https://console.carloku.com prev999 edge", "systemctl --user start"} {
167 if !strings.Contains(calls, want) {
168 t.Fatalf("missing call %q:\n%s", want, calls)
169 }
170 }
171 if strings.TrimSpace(r.read(filepath.Join(r.root, "served"))) != "prev999" {
172 t.Fatal("previous release not served")
173 }
174 if out, err = r.run("rollback", "--execute"); err == nil {
175 t.Fatalf("second rollback allowed: %s", out)
176 }
177}
178
179func TestCutoverRollbackRefusedOnceADeployMayHaveBegun(t *testing.T) {
180 for name, set := range map[string]func(r *cutoverRig){
181 // The deploy failed or was cut off: CARLOS may have started the new version.
182 "deploy failed": func(r *cutoverRig) {
183 r.write(filepath.Join(r.root, "deployfail"), "", 0600)
184 if out, err := r.run(cutoverVersion, "--execute"); err == nil {
185 r.t.Fatalf("cutover went on after a failed deploy:\n%s", out)
186 }
187 },
188 // A record from before deploy_started existed, past step 4.
189 "older record": func(r *cutoverRig) {
190 r.write(filepath.Join(r.home, ".local/share/equipo-cutover/cutover.state"), "version="+cutoverVersion+"\nstamp=X\nprev_version=prev999\ndone_preflight=1\ndone_export=1\ndone_config=1\n", 0600)
191 r.write(filepath.Join(r.home, ".local/share/equipo-cutover/prior/service.env"), string(r.serviceEnv), 0600)
192 r.write(filepath.Join(r.home, ".local/share/equipo-cutover/prior/equipo-runner.service"), string(r.unit), 0600)
193 },
194 } {
195 t.Run(name, func(t *testing.T) {
196 r := newCutoverRig(t)
197 r.t = t
198 set(r)
199 before := r.read(r.log)
200 out, err := r.run("rollback", "--execute")
201 if err == nil || !strings.Contains(out, "prev999 cannot read it") || r.read(r.log) != before {
202 t.Fatalf("rollback offered prev999: %v\n%s", err, out)
203 }
204 })
205 }
206}
207
208func TestCutoverRollbackRefusedAfterTheDeploy(t *testing.T) {
209 r := newCutoverRig(t)
210 if out, err := r.run(cutoverVersion, "--execute"); err != nil {
211 t.Fatalf("cutover: %v\n%s", err, out)
212 }
213 before := r.read(r.log)
214 out, err := r.run("rollback", "--execute")
215 if err == nil || !strings.Contains(out, "prev999 cannot read it") || !strings.Contains(out, "cutover-finish-thin.sh") {
216 t.Fatalf("rollback to a version that cannot read the migrated database: %v\n%s", err, out)
217 }
218 if r.read(r.log) != before {
219 t.Fatalf("a refused rollback changed something:\n%s", strings.TrimPrefix(r.read(r.log), before))
220 }
221}
222
223// A snapshot read that fails stops the cutover before any change, so a
224// later rollback never unsets a value it could not read.
225func TestCutoverStopsWhenASnapshotReadFails(t *testing.T) {
226 r := newCutoverRig(t)
227 r.write(filepath.Join(r.root, "envfail"), "", 0600)
228 if out, err := r.run(cutoverVersion, "--execute"); err == nil {
229 t.Fatalf("cutover continued without the prior configuration:\n%s", out)
230 }
231 calls := r.read(r.log)
232 for _, change := range []string{"systemctl", "env set", "env unset", "deploy", "db pull"} {
233 if strings.Contains(calls, change) {
234 t.Fatalf("changed something (%s) after a failed snapshot read:\n%s", change, calls)
235 }
236 }
237 if r.read(filepath.Join(r.runner, "service.env")) != string(r.serviceEnv) || r.read(filepath.Join(r.runner, "state", "credentials.json")) != "old" {
238 t.Fatal("runner changed after a failed snapshot read")
239 }
240 if strings.Contains(r.read(filepath.Join(r.home, ".local/share/equipo-cutover/cutover.state")), "done_preflight") {
241 t.Fatal("a failed snapshot was recorded as complete")
242 }
243}
244
245// Before the staged runner enrols or its unit starts, the runner itself
246// checks every program in its new configuration against the release
247// (equipo-runner verify-installed). A program that is not the pinned one
248// stops the cutover with nothing enrolled and nothing started.
249func TestCutoverVerifiesInstalledProgramsBeforeStarting(t *testing.T) {
250 r := newCutoverRig(t)
251 r.write(filepath.Join(r.root, "verifyfail"), "", 0600)
252 out, err := r.run(cutoverVersion, "--execute")
253 calls := r.read(r.log)
254 if err == nil || !strings.Contains(calls, "equipo-runner verify-installed") {
255 t.Fatalf("cutover went on with unverified programs: %v\n%s\n%s", err, out, calls)
256 }
257 if strings.Contains(calls, "equipo-runner enrol") || strings.Contains(calls, "systemctl --user start") || r.read(filepath.Join(r.root, "enrolled")) != "" {
258 t.Fatalf("enrolled or started after a refused verification:\n%s", calls)
259 }
260 // With the programs right, the same cutover resumes: verify, enrol, start.
261 r.must(os.Remove(filepath.Join(r.root, "verifyfail")))
262 if out, err = r.run(cutoverVersion, "--execute"); err != nil {
263 t.Fatalf("cutover: %v\n%s", err, out)
264 }
265 calls = r.read(r.log)
266 verify := strings.LastIndex(calls, "equipo-runner verify-installed "+filepath.Join(r.runner, "releases", cutoverVersion, "equipo-tool-proxy"))
267 enrol, start := strings.Index(calls, "equipo-runner enrol"), strings.Index(calls, "systemctl --user start")
268 if verify < 0 || enrol < verify || start < enrol {
269 t.Fatalf("want verify-installed with the staged tool proxy, then enrol, then start:\n%s", calls)
270 }
271}
272