package release import ( "bytes" "os" "os/exec" "path/filepath" "strings" "testing" ) const ( cutoverVersion = "abc1234" oldInstanceID = "OLDINSTANCE000000000000000" newInstanceID = "NEWINSTANCE000000000000000" ) // cutoverRig runs scripts/cutover-thin.sh against stub carlos, systemctl, // curl and make on a temporary HOME. Nothing here reaches a real service. type cutoverRig struct { t *testing.T root, home, runner string script string log string serviceEnv, unit []byte } func newCutoverRig(t *testing.T) *cutoverRig { t.Helper() root := t.TempDir() r := &cutoverRig{t: t, root: root, home: filepath.Join(root, "home"), log: filepath.Join(root, "calls.log")} r.runner = filepath.Join(r.home, ".local/share/equipo-runner") repo := filepath.Join(root, "repo") src, err := os.ReadFile("../../scripts/cutover-thin.sh") r.must(err) r.script = filepath.Join(repo, "scripts", "cutover-thin.sh") r.write(r.script, string(src), 0700) r.write(filepath.Join(repo, "releases", "equipo-linux-arm64-"+cutoverVersion), "instance", 0600) release := filepath.Join(repo, "releases", "equipo-runner-linux-amd64-"+cutoverVersion) // The staged runner's enrol records the instance id it was given. // It also answers verify-installed, with the tool proxy it was told to use. 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) r.write(filepath.Join(release, RendererArchive), string(rendererArchiveBytes), 0600) r.write(filepath.Join(release, "equipo-tool-proxy"), "proxy", 0700) r.write(filepath.Join(release, "gitleaks"), scannerBytes, 0700) 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") r.unit = []byte("[Service]\nExecStart=/old/equipo-runner run\nRestart=on-failure\nRestartSec=5\n") r.write(filepath.Join(r.runner, "service.env"), string(r.serviceEnv), 0600) r.write(filepath.Join(r.runner, "equipo-runner.service"), string(r.unit), 0600) r.write(filepath.Join(r.runner, "state", "credentials.json"), "old", 0600) r.write(filepath.Join(root, "served"), "prev999\n", 0600) r.write(filepath.Join(root, "teamid"), newInstanceID, 0600) bin := filepath.Join(root, "bin") log := "echo \"$(basename $0) $*\" >> " + r.log + "\n" r.write(filepath.Join(bin, "systemctl"), "#!/bin/sh\n"+log, 0700) r.write(filepath.Join(bin, "make"), "#!/bin/sh\n"+log, 0700) r.write(filepath.Join(bin, "curl"), "#!/bin/sh\ncat "+filepath.Join(root, "served")+"\n", 0700) r.write(filepath.Join(bin, "carlos"), "#!/bin/sh\n"+log+`case "$1 $2" in "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' ;; "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 ;; "db query") printf 'id\n%s\n' "$(cat `+filepath.Join(root, "teamid")+`)" ;; deploy*) [ -e `+filepath.Join(root, "deployfail")+` ] && exit 1; for a; do case $prev in --version) echo "$a" > `+filepath.Join(root, "served")+` ;; esac; prev=$a; done ;; promote*) shift; for a; do last2=$last; last=$a; done; echo "$last2" > `+filepath.Join(root, "served")+` ;; esac `, 0700) return r } func (r *cutoverRig) must(err error) { r.t.Helper() if err != nil { r.t.Fatal(err) } } func (r *cutoverRig) write(path, body string, mode os.FileMode) { r.t.Helper() r.must(os.MkdirAll(filepath.Dir(path), 0700)) r.must(os.WriteFile(path, []byte(body), mode)) } func (r *cutoverRig) run(args ...string) (string, error) { cmd := exec.Command("bash", append([]string{r.script}, args...)...) 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"} out, err := cmd.CombinedOutput() return string(out), err } // answer runs the script without CUTOVER_YES, answering its step prompts // from input. func (r *cutoverRig) answer(input string, args ...string) (string, error) { cmd := exec.Command("bash", append([]string{r.script}, args...)...) 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"} cmd.Stdin = strings.NewReader(input) out, err := cmd.CombinedOutput() return string(out), err } func (r *cutoverRig) read(path string) string { raw, _ := os.ReadFile(path) return string(raw) } // The runner enrols with the new instance's id, read from the new database // before any runner change; a replica still showing the old instance stops // the cutover with the runner untouched. func TestCutoverEnrolsWithTheNewInstance(t *testing.T) { r := newCutoverRig(t) out, err := r.run(cutoverVersion, "--execute") if err != nil { t.Fatalf("cutover: %v\n%s", err, out) } if got := strings.TrimSpace(r.read(filepath.Join(r.root, "enrolled"))); got != newInstanceID { t.Fatalf("enrolled with instance %q, want %q", got, newInstanceID) } env := r.read(filepath.Join(r.runner, "service.env")) if !strings.Contains(env, newInstanceID) || !strings.Contains(env, filepath.Join(r.runner, "releases", cutoverVersion, "equipo-tool-proxy")) { t.Fatalf("runner config not updated:\n%s", env) } if strings.Index(out, "select id from teams") > strings.Index(out, "state.pre-thin-") { t.Fatal("instance id read after the runner state moved") } calls := r.read(r.log) 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"} { if !strings.Contains(calls, want) { t.Fatalf("missing call %q:\n%s", want, calls) } } // A completed cutover is not run again. if out, err = r.run(cutoverVersion, "--execute"); err == nil || !strings.Contains(out, "complete") { t.Fatalf("second cutover allowed: %v %s", err, out) } } func TestCutoverRefusesWithoutANewInstanceID(t *testing.T) { r := newCutoverRig(t) r.write(filepath.Join(r.root, "teamid"), oldInstanceID, 0600) if out, err := r.run(cutoverVersion, "--execute"); err == nil { t.Fatalf("cutover continued with the old instance id:\n%s", out) } if r.read(filepath.Join(r.runner, "state", "credentials.json")) != "old" || r.read(filepath.Join(r.runner, "service.env")) != string(r.serviceEnv) { t.Fatal("runner changed before the new instance id was known") } } // Before its deploy begins, rollback restores the complete prior // configuration. Once a deploy may have begun it is refused: on CARLOS the // activator passes the app an absolute --db, so a deploy migrates the old // database in place and the previous version cannot read it. func TestCutoverRollbackRestoresEverythingBeforeTheDeploy(t *testing.T) { r := newCutoverRig(t) if out, err := r.answer("yes\nyes\nyes\nyes\nno\n", cutoverVersion, "--execute"); err == nil || !strings.Contains(out, "stopped before: 5") { t.Fatalf("cutover did not stop before its deploy: %v\n%s", err, out) } out, err := r.run("rollback", "--execute") if err != nil { t.Fatalf("rollback: %v\n%s", err, out) } 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) { t.Fatal("runner configuration not restored exactly") } if r.read(filepath.Join(r.runner, "state", "credentials.json")) != "old" { t.Fatal("old runner state not kept") } calls := r.read(r.log) 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"} { if !strings.Contains(calls, want) { t.Fatalf("missing call %q:\n%s", want, calls) } } if strings.TrimSpace(r.read(filepath.Join(r.root, "served"))) != "prev999" { t.Fatal("previous release not served") } if out, err = r.run("rollback", "--execute"); err == nil { t.Fatalf("second rollback allowed: %s", out) } } func TestCutoverRollbackRefusedOnceADeployMayHaveBegun(t *testing.T) { for name, set := range map[string]func(r *cutoverRig){ // The deploy failed or was cut off: CARLOS may have started the new version. "deploy failed": func(r *cutoverRig) { r.write(filepath.Join(r.root, "deployfail"), "", 0600) if out, err := r.run(cutoverVersion, "--execute"); err == nil { r.t.Fatalf("cutover went on after a failed deploy:\n%s", out) } }, // A record from before deploy_started existed, past step 4. "older record": func(r *cutoverRig) { 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) r.write(filepath.Join(r.home, ".local/share/equipo-cutover/prior/service.env"), string(r.serviceEnv), 0600) r.write(filepath.Join(r.home, ".local/share/equipo-cutover/prior/equipo-runner.service"), string(r.unit), 0600) }, } { t.Run(name, func(t *testing.T) { r := newCutoverRig(t) r.t = t set(r) before := r.read(r.log) out, err := r.run("rollback", "--execute") if err == nil || !strings.Contains(out, "prev999 cannot read it") || r.read(r.log) != before { t.Fatalf("rollback offered prev999: %v\n%s", err, out) } }) } } func TestCutoverRollbackRefusedAfterTheDeploy(t *testing.T) { r := newCutoverRig(t) if out, err := r.run(cutoverVersion, "--execute"); err != nil { t.Fatalf("cutover: %v\n%s", err, out) } before := r.read(r.log) out, err := r.run("rollback", "--execute") if err == nil || !strings.Contains(out, "prev999 cannot read it") || !strings.Contains(out, "cutover-finish-thin.sh") { t.Fatalf("rollback to a version that cannot read the migrated database: %v\n%s", err, out) } if r.read(r.log) != before { t.Fatalf("a refused rollback changed something:\n%s", strings.TrimPrefix(r.read(r.log), before)) } } // A snapshot read that fails stops the cutover before any change, so a // later rollback never unsets a value it could not read. func TestCutoverStopsWhenASnapshotReadFails(t *testing.T) { r := newCutoverRig(t) r.write(filepath.Join(r.root, "envfail"), "", 0600) if out, err := r.run(cutoverVersion, "--execute"); err == nil { t.Fatalf("cutover continued without the prior configuration:\n%s", out) } calls := r.read(r.log) for _, change := range []string{"systemctl", "env set", "env unset", "deploy", "db pull"} { if strings.Contains(calls, change) { t.Fatalf("changed something (%s) after a failed snapshot read:\n%s", change, calls) } } if r.read(filepath.Join(r.runner, "service.env")) != string(r.serviceEnv) || r.read(filepath.Join(r.runner, "state", "credentials.json")) != "old" { t.Fatal("runner changed after a failed snapshot read") } if strings.Contains(r.read(filepath.Join(r.home, ".local/share/equipo-cutover/cutover.state")), "done_preflight") { t.Fatal("a failed snapshot was recorded as complete") } } // Before the staged runner enrols or its unit starts, the runner itself // checks every program in its new configuration against the release // (equipo-runner verify-installed). A program that is not the pinned one // stops the cutover with nothing enrolled and nothing started. func TestCutoverVerifiesInstalledProgramsBeforeStarting(t *testing.T) { r := newCutoverRig(t) r.write(filepath.Join(r.root, "verifyfail"), "", 0600) out, err := r.run(cutoverVersion, "--execute") calls := r.read(r.log) if err == nil || !strings.Contains(calls, "equipo-runner verify-installed") { t.Fatalf("cutover went on with unverified programs: %v\n%s\n%s", err, out, calls) } if strings.Contains(calls, "equipo-runner enrol") || strings.Contains(calls, "systemctl --user start") || r.read(filepath.Join(r.root, "enrolled")) != "" { t.Fatalf("enrolled or started after a refused verification:\n%s", calls) } // With the programs right, the same cutover resumes: verify, enrol, start. r.must(os.Remove(filepath.Join(r.root, "verifyfail"))) if out, err = r.run(cutoverVersion, "--execute"); err != nil { t.Fatalf("cutover: %v\n%s", err, out) } calls = r.read(r.log) verify := strings.LastIndex(calls, "equipo-runner verify-installed "+filepath.Join(r.runner, "releases", cutoverVersion, "equipo-tool-proxy")) enrol, start := strings.Index(calls, "equipo-runner enrol"), strings.Index(calls, "systemctl --user start") if verify < 0 || enrol < verify || start < enrol { t.Fatalf("want verify-installed with the staged tool proxy, then enrol, then start:\n%s", calls) } }