refactor: testing from the beginning. a journey in 150k lines of tests to none
This commit is contained in:
651 files changed
-146443
No files matched your search
@@ -1,226 +0,0 @@
|
||||
package releaseupdate
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// checkRun configures one end-to-end run of archie-update-check. The fake git
|
||||
// and curl placed on PATH are what make the test exercise the script's real
|
||||
// source-selection logic rather than the network.
|
||||
type checkRun struct {
|
||||
// git is the fake `git` body. Empty leaves git off PATH entirely, which
|
||||
// is how the API-only path is reached.
|
||||
git string
|
||||
// curl is the fake `curl` body. Empty means curl always fails, so the
|
||||
// git-tag path is reached.
|
||||
curl string
|
||||
// binVersion is what the fake archied reports for -version.
|
||||
binVersion string
|
||||
}
|
||||
|
||||
func runUpdateCheckScript(t *testing.T, run checkRun) (Snapshot, []string, string, error) {
|
||||
t.Helper()
|
||||
root, err := filepath.Abs(filepath.Join("..", ".."))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
work := t.TempDir()
|
||||
binDir := filepath.Join(work, "bin")
|
||||
fakeDir := filepath.Join(work, "fake-bin")
|
||||
callsPath := filepath.Join(work, "calls")
|
||||
if err := os.MkdirAll(binDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
version := run.binVersion
|
||||
if version == "" {
|
||||
version = "1.22.0"
|
||||
}
|
||||
writeFakeCommand(t, binDir, "archied", `printf 'archied %s\narchie-agent %s\n' "`+version+`" "1.19.9"`)
|
||||
if run.git != "" {
|
||||
writeFakeCommand(t, fakeDir, "git", run.git)
|
||||
}
|
||||
if run.curl != "" {
|
||||
writeFakeCommand(t, fakeDir, "curl", run.curl)
|
||||
}
|
||||
|
||||
cmd := exec.CommandContext(t.Context(), filepath.Join(root, "scripts", "archie-update-check"))
|
||||
cmd.Env = append(
|
||||
os.Environ(),
|
||||
"PATH="+fakeDir+":"+binDir+":"+os.Getenv("PATH"),
|
||||
"ARCHIE_BIN="+filepath.Join(binDir, "archied"),
|
||||
"ARCHIE_TEST_CALLS="+callsPath,
|
||||
// A remote that cannot be reached in this environment: anything the
|
||||
// script resolves came from a fake, never from the real network.
|
||||
"ARCHIE_SOURCE_URL=https://example.invalid/archie-core.git",
|
||||
"ARCHIE_FORGE_API=https://api.example.invalid",
|
||||
"ARCHIE_FORGE_TIMEOUT=5",
|
||||
)
|
||||
output, err := cmd.Output()
|
||||
var stderr string
|
||||
if exitErr, ok := errors.AsType[*exec.ExitError](err); ok {
|
||||
stderr = string(exitErr.Stderr)
|
||||
}
|
||||
var calls []string
|
||||
if data, readErr := os.ReadFile(callsPath); readErr == nil && len(data) > 0 {
|
||||
calls = strings.Split(strings.TrimSpace(string(data)), "\n")
|
||||
}
|
||||
if err != nil {
|
||||
return Snapshot{}, calls, stderr, err
|
||||
}
|
||||
var snapshot Snapshot
|
||||
if err := json.Unmarshal(output, &snapshot); err != nil {
|
||||
t.Fatalf("decode check output %q: %v", output, err)
|
||||
}
|
||||
return snapshot, calls, stderr, nil
|
||||
}
|
||||
|
||||
// The update check must not depend on a local checkout existing. It used to
|
||||
// resolve tags with `git -C "$REPO" ls-remote`, so a host with no clone --
|
||||
// or a clone under a different name -- silently reported no available
|
||||
// releases, which the /update command then rendered as "Archie is up to
|
||||
// date." This is the failure test for that: it must resolve from the remote
|
||||
// alone, and must not shell into any working tree.
|
||||
func TestUpdateCheckNeedsNoLocalCheckout(t *testing.T) {
|
||||
snapshot, calls, _, err := runUpdateCheckScript(t, checkRun{
|
||||
git: `
|
||||
printf '%s\n' "git $*" >> "$ARCHIE_TEST_CALLS"
|
||||
case "$*" in
|
||||
*archied/v*) printf '%s\n' refs/tags/archied/v1.22.0 refs/tags/archied/v1.23.0 ;;
|
||||
*archie/v*) printf '%s\n' refs/tags/archie/v1.21.0 ;;
|
||||
esac
|
||||
`,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("check failed: %v", err)
|
||||
}
|
||||
for _, fragment := range []string{"ls-remote", "example.invalid/archie-core.git"} {
|
||||
assertCallContains(t, calls, fragment)
|
||||
}
|
||||
// -C is how the old script targeted a checkout. Any use of it means the
|
||||
// checkout dependency came back.
|
||||
assertCallAbsent(t, calls, "git -C")
|
||||
assertCallAbsent(t, calls, "clone")
|
||||
|
||||
if got, want := componentAvailable(snapshot, ComponentDaemon), "1.23.0"; got != want {
|
||||
t.Errorf("daemon available = %q, want %q", got, want)
|
||||
}
|
||||
// One version covers every component; a stale archie/v* runtime tag must
|
||||
// never be offered as an update.
|
||||
if got, want := componentAvailable(snapshot, ComponentAgent), "1.23.0"; got != want {
|
||||
t.Errorf("agent available = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// A source that cannot be reached is a failure to check, not an absence. The
|
||||
// old script exited 0 with an empty Available for every component, which is
|
||||
// indistinguishable from "up to date" -- so an unreachable remote, a deleted
|
||||
// checkout, or a renamed repo all read as parity. It must instead refuse.
|
||||
func TestUpdateCheckFailsRatherThanReportingParity(t *testing.T) {
|
||||
_, _, stderr, err := runUpdateCheckScript(t, checkRun{
|
||||
git: `printf '%s\n' "git $*" >> "$ARCHIE_TEST_CALLS"; exit 128`,
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("check succeeded with every source unreachable; an empty result reads as \"up to date\"")
|
||||
}
|
||||
for _, fragment := range []string{"example.invalid/archie-core.git", "api.example.invalid"} {
|
||||
if !strings.Contains(stderr, fragment) {
|
||||
t.Errorf("failure must name the source it could not read (%s); stderr = %q", fragment, stderr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// With git unavailable, the forge API is the fallback source. It has to
|
||||
// resolve the same release the git path would, or a host without git can
|
||||
// never be told an update exists.
|
||||
func TestUpdateCheckFallsBackToForgeAPITags(t *testing.T) {
|
||||
snapshot, _, _, err := runUpdateCheckScript(t, checkRun{
|
||||
curl: `
|
||||
printf '%s\n' "curl $*" >> "$ARCHIE_TEST_CALLS"
|
||||
case "$*" in
|
||||
*"/tags"*)
|
||||
printf '%s\n' '[{"name":"archied/v1.22.0"},{"name":"archied/v1.24.0"},{"name":"archie/v1.23.0"}]'
|
||||
;;
|
||||
*) exit 22 ;;
|
||||
esac
|
||||
`,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("check failed: %v", err)
|
||||
}
|
||||
if got, want := componentAvailable(snapshot, ComponentDaemon), "1.24.0"; got != want {
|
||||
t.Errorf("daemon available = %q, want %q", got, want)
|
||||
}
|
||||
if got, want := componentAvailable(snapshot, ComponentAgent), "1.24.0"; got != want {
|
||||
t.Errorf("agent available = %q, want %q", got, want)
|
||||
}
|
||||
if ref := componentReference(snapshot, ComponentDaemon); !strings.Contains(ref, "forge-api-tags") {
|
||||
t.Errorf("daemon reference = %q, want the API source recorded", ref)
|
||||
}
|
||||
}
|
||||
|
||||
// A tagged release is announced whether or not it has a published artifact,
|
||||
// and the Reference says which, so an operator is never sent to a tag with
|
||||
// nothing to download without being told.
|
||||
func TestUpdateCheckReportsArtifactState(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
release string
|
||||
wantState string
|
||||
}{
|
||||
{name: "published with assets", release: `{"assets":[{"name":"zip"},{"name":"SHA256SUMS"}]}`, wantState: "2-assets"},
|
||||
{name: "tagged but never published", release: `{"assets":[]}`, wantState: "no-artifact"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
snapshot, _, _, err := runUpdateCheckScript(t, checkRun{
|
||||
git: `
|
||||
printf '%s\n' "git $*" >> "$ARCHIE_TEST_CALLS"
|
||||
case "$*" in
|
||||
*archied/v*) printf '%s\n' refs/tags/archied/v1.24.0 ;;
|
||||
*archie/v*) printf '%s\n' refs/tags/archie/v1.23.0 ;;
|
||||
esac
|
||||
`,
|
||||
curl: `
|
||||
printf '%s\n' "curl $*" >> "$ARCHIE_TEST_CALLS"
|
||||
case "$*" in
|
||||
*"/releases/tags/"*) printf '%s\n' '` + tt.release + `' ;;
|
||||
*) exit 22 ;;
|
||||
esac
|
||||
`,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("check failed: %v", err)
|
||||
}
|
||||
for _, id := range []string{ComponentDaemon, ComponentAgent} {
|
||||
ref := componentReference(snapshot, id)
|
||||
if !strings.Contains(ref, tt.wantState) {
|
||||
t.Errorf("%s reference = %q, want artifact state %q", id, ref, tt.wantState)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func componentAvailable(snapshot Snapshot, id string) string {
|
||||
for _, component := range snapshot.Components {
|
||||
if component.ID == id {
|
||||
return component.Available
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func componentReference(snapshot Snapshot, id string) string {
|
||||
for _, component := range snapshot.Components {
|
||||
if component.ID == id {
|
||||
return component.Reference
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -1,182 +0,0 @@
|
||||
package releaseupdate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// writeFixtureScript creates an executable shell script and returns its path.
|
||||
func writeFixtureScript(t *testing.T, body string) string {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "fixture.sh")
|
||||
script := "#!/usr/bin/env bash\nset -euo pipefail\n" + body
|
||||
if err := os.WriteFile(path, []byte(script), 0o755); err != nil {
|
||||
t.Fatalf("write fixture script: %v", err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
// TestCommandInstallerStreamsProgressLive confirms every stdout line the
|
||||
// script prints reaches progress() as it is emitted, not buffered until the
|
||||
// process exits -- this is the difference between silent-until-done and
|
||||
// live status.
|
||||
func TestCommandInstallerStreamsProgressLive(t *testing.T) {
|
||||
script := writeFixtureScript(t, `
|
||||
echo "==> fetching"
|
||||
echo "==> building"
|
||||
echo 'ARCHIE_UPDATE_RESULT {"previous":{"daemon":"1.0.0"},"installed":{"daemon":"1.1.0"},"components":[{"id":"daemon","label":"daemon","status":"updated"}],"restart_requested":true}'
|
||||
`)
|
||||
installer := CommandInstaller{Command: []string{script}}
|
||||
var progress []string
|
||||
result, err := installer.Install(context.Background(), Snapshot{}, InstallMeta{}, func(line string) { progress = append(progress, line) })
|
||||
if err != nil {
|
||||
t.Fatalf("Install() error = %v", err)
|
||||
}
|
||||
if len(progress) != 2 || progress[0] != "==> fetching" || progress[1] != "==> building" {
|
||||
t.Fatalf("progress = %#v, want the two stage lines (sentinel excluded)", progress)
|
||||
}
|
||||
if result.Previous["daemon"] != "1.0.0" || result.Installed["daemon"] != "1.1.0" {
|
||||
t.Fatalf("result versions = %#v", result)
|
||||
}
|
||||
if len(result.Components) != 1 || result.Components[0].Status != "updated" {
|
||||
t.Fatalf("result components = %#v", result.Components)
|
||||
}
|
||||
if !result.RestartRequested {
|
||||
t.Error("RestartRequested = false, want true")
|
||||
}
|
||||
}
|
||||
|
||||
// TestCommandInstallerMissingSentinelReturnsEmptyResult: a script that never
|
||||
// prints the sentinel line (e.g. an operator's older custom script) must not
|
||||
// crash the parse -- it just reports nothing structured, and progress lines
|
||||
// are still delivered.
|
||||
func TestCommandInstallerMissingSentinelReturnsEmptyResult(t *testing.T) {
|
||||
script := writeFixtureScript(t, `echo "==> done, no sentinel"`)
|
||||
installer := CommandInstaller{Command: []string{script}}
|
||||
var progress []string
|
||||
result, err := installer.Install(context.Background(), Snapshot{}, InstallMeta{}, func(line string) { progress = append(progress, line) })
|
||||
if err != nil {
|
||||
t.Fatalf("Install() error = %v", err)
|
||||
}
|
||||
if len(progress) != 1 || progress[0] != "==> done, no sentinel" {
|
||||
t.Fatalf("progress = %#v", progress)
|
||||
}
|
||||
if result.Previous != nil || result.Installed != nil || result.Components != nil {
|
||||
t.Fatalf("result = %#v, want zero value", result)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCommandInstallerMalformedSentinelReturnsError: a sentinel line present
|
||||
// but with invalid JSON is a script bug -- it must surface as an error
|
||||
// rather than silently reporting an empty (and therefore misleadingly
|
||||
// "nothing changed") result.
|
||||
func TestCommandInstallerMalformedSentinelReturnsError(t *testing.T) {
|
||||
script := writeFixtureScript(t, `echo 'ARCHIE_UPDATE_RESULT {not valid json}'`)
|
||||
installer := CommandInstaller{Command: []string{script}}
|
||||
_, err := installer.Install(context.Background(), Snapshot{}, InstallMeta{}, func(string) {})
|
||||
if err == nil {
|
||||
t.Fatal("Install() error = nil, want a decode error")
|
||||
}
|
||||
}
|
||||
|
||||
// TestCommandInstallerNonZeroExitReturnsPartialResultAndError: a script that
|
||||
// fails partway through should still surface whatever progress and result it
|
||||
// managed to emit before failing, alongside the error -- callers need to
|
||||
// know how far the update got.
|
||||
func TestCommandInstallerNonZeroExitReturnsPartialResultAndError(t *testing.T) {
|
||||
script := writeFixtureScript(t, `
|
||||
echo "==> fetching"
|
||||
echo "build failed" >&2
|
||||
exit 1
|
||||
`)
|
||||
installer := CommandInstaller{Command: []string{script}}
|
||||
var progress []string
|
||||
_, err := installer.Install(context.Background(), Snapshot{}, InstallMeta{}, func(line string) { progress = append(progress, line) })
|
||||
if err == nil {
|
||||
t.Fatal("Install() error = nil, want non-zero exit error")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "build failed") {
|
||||
t.Errorf("error = %v, want it to include stderr", err)
|
||||
}
|
||||
if len(progress) != 1 || progress[0] != "==> fetching" {
|
||||
t.Fatalf("progress = %#v, want the line emitted before failure", progress)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCommandInstallerForwardsMetaAsEnv: the script needs to know who to
|
||||
// report back to once the daemon restarts, since the process that requested
|
||||
// the update is not the process that observes the restart succeeding.
|
||||
func TestCommandInstallerForwardsMetaAsEnv(t *testing.T) {
|
||||
script := writeFixtureScript(t, `
|
||||
echo "channel=$ARCHIE_UPDATE_CHANNEL chat=$ARCHIE_UPDATE_CHAT_ID thread=$ARCHIE_UPDATE_THREAD_ID report=$ARCHIE_UPDATE_REPORT_PATH"
|
||||
`)
|
||||
installer := CommandInstaller{Command: []string{script}}
|
||||
meta := InstallMeta{Channel: "telegram", ChatID: 123, ThreadID: 7, ReportPath: "/var/lib/archie/update-report.json"}
|
||||
var progress []string
|
||||
if _, err := installer.Install(context.Background(), Snapshot{}, meta, func(line string) { progress = append(progress, line) }); err != nil {
|
||||
t.Fatalf("Install() error = %v", err)
|
||||
}
|
||||
want := "channel=telegram chat=123 thread=7 report=/var/lib/archie/update-report.json"
|
||||
if len(progress) != 1 || progress[0] != want {
|
||||
t.Fatalf("progress = %#v, want [%q]", progress, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommandInstallerForwardsApprovedComponentPlanAsEnv(t *testing.T) {
|
||||
script := writeFixtureScript(t, `
|
||||
echo "daemon=$ARCHIE_UPDATE_DAEMON_PREVIOUS->$ARCHIE_UPDATE_DAEMON_VERSION agent=$ARCHIE_UPDATE_AGENT_PREVIOUS->$ARCHIE_UPDATE_AGENT_VERSION"
|
||||
`)
|
||||
installer := CommandInstaller{Command: []string{script}}
|
||||
snapshot := Snapshot{Components: []Component{
|
||||
{ID: ComponentDaemon, Installed: "1.12.0", Available: "1.13.0"},
|
||||
{ID: ComponentAgent, Installed: "1.9.9", Available: "1.9.9"},
|
||||
}}
|
||||
var progress []string
|
||||
if _, err := installer.Install(context.Background(), snapshot, InstallMeta{}, func(line string) { progress = append(progress, line) }); err != nil {
|
||||
t.Fatalf("Install() error = %v", err)
|
||||
}
|
||||
want := "daemon=1.12.0->1.13.0 agent=1.9.9->"
|
||||
if len(progress) != 1 || progress[0] != want {
|
||||
t.Fatalf("progress = %#v, want [%q]", progress, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommandInstallerEmptyCommandReturnsError(t *testing.T) {
|
||||
installer := CommandInstaller{}
|
||||
if _, err := installer.Install(context.Background(), Snapshot{}, InstallMeta{}, func(string) {}); err == nil {
|
||||
t.Fatal("Install() error = nil, want empty-command error")
|
||||
}
|
||||
}
|
||||
|
||||
// TestCommandInstallerForwardsHealthURL: only the daemon knows which address
|
||||
// it serves /healthz on, so it, not the install script, decides what the
|
||||
// post-restart probe polls (archie-core-1r4g).
|
||||
func TestCommandInstallerForwardsHealthURL(t *testing.T) {
|
||||
script := writeFixtureScript(t, `
|
||||
echo "health=${ARCHIE_HEALTH_URL:-unset}"
|
||||
`)
|
||||
t.Setenv("ARCHIE_HEALTH_URL", "http://operator.example:9999")
|
||||
|
||||
for _, tc := range []struct{ name, healthURL, want string }{
|
||||
{name: "configured", healthURL: "http://127.0.0.1:9000", want: "health=http://127.0.0.1:9000"},
|
||||
// An unset field must not clobber an operator's own export: a
|
||||
// deployment with the dashboard off has no address to derive and
|
||||
// the exported value is the only one there is.
|
||||
{name: "unset leaves the environment alone", want: "health=http://operator.example:9999"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
installer := CommandInstaller{Command: []string{script}, HealthURL: tc.healthURL}
|
||||
var progress []string
|
||||
if _, err := installer.Install(context.Background(), Snapshot{}, InstallMeta{}, func(line string) { progress = append(progress, line) }); err != nil {
|
||||
t.Fatalf("Install() error = %v", err)
|
||||
}
|
||||
if len(progress) != 1 || progress[0] != tc.want {
|
||||
t.Fatalf("progress = %#v, want [%q]", progress, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,114 +0,0 @@
|
||||
package releaseupdate
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const snapshotConfig = "database_url = 'postgres://archie:hunter2@db.example/archie'\n\n[containers]\nimage = 'registry.example/archie-agent:stable'\n"
|
||||
|
||||
// The new State Store migrates on start and nothing undoes a migration
|
||||
// automatically, so a daemon update snapshots the whole database first,
|
||||
// through the release's own recovery subcommand, and hands the snapshot's
|
||||
// path to the watchdog. The connection string stays inside the config.
|
||||
func TestUpdateInstallSnapshotsTheDatabaseBeforeMigrating(t *testing.T) {
|
||||
snapshot := filepath.Join(t.TempDir(), "pre-update.dump")
|
||||
_, calls, _ := runUpdateInstallWithConfig(t, map[string]string{
|
||||
"ARCHIE_UPDATE_DAEMON_PREVIOUS": "1.22.0",
|
||||
"ARCHIE_UPDATE_DAEMON_VERSION": "1.23.0",
|
||||
"ARCHIE_UPDATE_AGENT_PREVIOUS": "1.21.0",
|
||||
"ARCHIE_DB_SNAPSHOT": snapshot,
|
||||
}, snapshotConfig, false)
|
||||
|
||||
assertCallContains(t, calls, "go run ./cmd/archie-state-store backup", "-config ", "-out "+snapshot)
|
||||
assertCallContains(t, calls, "systemd-run", "--setenv=ARCHIE_DB_SNAPSHOT="+snapshot)
|
||||
assertCallAbsent(t, calls, "hunter2")
|
||||
}
|
||||
|
||||
func TestUpdateInstallSnapshotScope(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
env map[string]string
|
||||
wantSnapshot bool
|
||||
wantRefusal bool
|
||||
}{
|
||||
{name: "agent-only update does not touch the database", env: map[string]string{
|
||||
"ARCHIE_UPDATE_AGENT_PREVIOUS": "1.21.0", "ARCHIE_UPDATE_AGENT_VERSION": "1.22.0",
|
||||
}},
|
||||
{name: "daemon update refuses when the snapshot fails", wantSnapshot: true, wantRefusal: true, env: map[string]string{
|
||||
"ARCHIE_UPDATE_DAEMON_PREVIOUS": "1.22.0", "ARCHIE_UPDATE_DAEMON_VERSION": "1.23.0",
|
||||
"ARCHIE_UPDATE_AGENT_PREVIOUS": "1.21.0", "ARCHIE_TEST_GO_FAILS_SNAPSHOT": "1",
|
||||
}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
_, calls, output := runUpdateInstallWithConfig(t, tt.env, snapshotConfig, tt.wantRefusal)
|
||||
snapshotted := false
|
||||
for _, call := range calls {
|
||||
if strings.Contains(call, "archie-state-store backup") && strings.Contains(call, "-config ") {
|
||||
snapshotted = true
|
||||
}
|
||||
}
|
||||
if snapshotted != tt.wantSnapshot {
|
||||
t.Fatalf("snapshot attempted = %v, want %v; calls = %q", snapshotted, tt.wantSnapshot, calls)
|
||||
}
|
||||
if !tt.wantRefusal {
|
||||
return
|
||||
}
|
||||
if !strings.Contains(output, "could not snapshot the database") {
|
||||
t.Errorf("refusal must say the snapshot failed; output = %q", output)
|
||||
}
|
||||
for _, call := range calls {
|
||||
if strings.Contains(call, "install -m755") && !strings.Contains(call, "/scripts/") {
|
||||
t.Errorf("refused update still installed %q", call)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A failed daemon update rolls the binaries back but never the database, and
|
||||
// says so, naming the explicit offline restore rather than running one.
|
||||
func TestUpdateWatchdogNeverRestoresTheDatabaseItself(t *testing.T) {
|
||||
root, err := filepath.Abs(filepath.Join("..", ".."))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
work := t.TempDir()
|
||||
binDir, fakeDir := filepath.Join(work, "bin"), filepath.Join(work, "fake-bin")
|
||||
if err := os.MkdirAll(binDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for name, content := range map[string]string{"archied": "new", "archied.prev": "old"} {
|
||||
if err := os.WriteFile(filepath.Join(binDir, name), []byte(content), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
callsPath := filepath.Join(work, "calls")
|
||||
writeFakeCommand(t, fakeDir, "systemctl", `exit 0`)
|
||||
writeFakeCommand(t, fakeDir, "curl", `exit 1`)
|
||||
for _, tool := range []string{"pg_restore", "psql", "go", "archie-state-store"} {
|
||||
writeFakeCommand(t, fakeDir, tool, `printf '%s\n' "`+tool+` $*" >> "$ARCHIE_TEST_CALLS"`)
|
||||
}
|
||||
snapshot := filepath.Join(work, "pre-update.dump")
|
||||
cmd := exec.CommandContext(t.Context(), filepath.Join(root, "scripts", "archie-update-watchdog"))
|
||||
cmd.Env = append(os.Environ(), "PATH="+fakeDir+":"+os.Getenv("PATH"), "ARCHIE_BIN_DIR="+binDir,
|
||||
"ARCHIE_TEST_CALLS="+callsPath, "ARCHIE_UPDATE_REPORT_PATH="+filepath.Join(work, "report.json"),
|
||||
"ARCHIE_UPDATE_HEALTH_TIMEOUT=0", "ARCHIE_UPDATE_COMPONENTS=daemon",
|
||||
"ARCHIE_DB_SNAPSHOT="+snapshot, "ARCHIE_CONFIG_PATH=/etc/archie/config.toml")
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("watchdog failed: %v\n%s", err, output)
|
||||
}
|
||||
if calls, _ := os.ReadFile(callsPath); len(calls) != 0 {
|
||||
t.Errorf("watchdog ran database tooling itself: %q", calls)
|
||||
}
|
||||
for _, want := range []string{"NOT rolled back", "archie-state-store restore -config /etc/archie/config.toml -from " + snapshot, "lost"} {
|
||||
if !strings.Contains(string(output), want) {
|
||||
t.Errorf("output lacks %q:\n%s", want, output)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,859 +0,0 @@
|
||||
package releaseupdate
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestUpdateInstallGatewayOnlySkipsRuntimeWork(t *testing.T) {
|
||||
result, calls := runUpdateInstallScript(t, map[string]string{
|
||||
"ARCHIE_UPDATE_DAEMON_PREVIOUS": "1.12.0",
|
||||
"ARCHIE_UPDATE_DAEMON_VERSION": "1.13.0",
|
||||
"ARCHIE_UPDATE_AGENT_PREVIOUS": "1.9.9",
|
||||
})
|
||||
|
||||
assertCallContains(t, calls, "git clone", "--no-checkout", "https://example.invalid/archie-core.git")
|
||||
assertCallContains(t, calls, "fetch --quiet --tags origin")
|
||||
assertCallAbsent(t, calls, "git pull")
|
||||
assertCallContains(t, calls, "git -C", "rev-parse --verify refs/tags/archied/v1.13.0^{commit}")
|
||||
assertCallContains(t, calls, "checkout --quiet --detach archied-v1.13.0")
|
||||
assertCallContains(t, calls, "go build", "internal/app/archied.runtimeVersion=1.9.9", "./cmd/archied")
|
||||
assertCallAbsent(t, calls, "./cmd/archie-agent")
|
||||
assertCallAbsent(t, calls, "docker compose build agent")
|
||||
if got := result.Installed[ComponentDaemon]; got != "1.13.0" {
|
||||
t.Fatalf("installed daemon = %q, want 1.13.0", got)
|
||||
}
|
||||
if _, found := result.Installed[ComponentAgent]; found {
|
||||
t.Fatalf("gateway-only result unexpectedly claims an agent install: %#v", result.Installed)
|
||||
}
|
||||
if !result.RestartRequested {
|
||||
t.Fatal("RestartRequested = false, want true for gateway update")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateInstallRuntimeOnlySkipsGatewayBuild(t *testing.T) {
|
||||
result, calls := runUpdateInstallScript(t, map[string]string{
|
||||
"ARCHIE_UPDATE_DAEMON_PREVIOUS": "1.13.0",
|
||||
"ARCHIE_UPDATE_AGENT_PREVIOUS": "1.9.9",
|
||||
"ARCHIE_UPDATE_AGENT_VERSION": "1.10.0",
|
||||
})
|
||||
|
||||
assertCallAbsent(t, calls, "./cmd/archied")
|
||||
assertCallAbsent(t, calls, "./cmd/archie-agent")
|
||||
assertCallContains(t, calls, "docker image save", "registry.example/archie-agent:stable")
|
||||
assertCallContains(t, calls, "docker build", "--build-arg RUNTIME_VERSION=1.10.0", "--tag registry.example/archie-agent:stable")
|
||||
if got := result.Installed[ComponentAgent]; got != "1.10.0" {
|
||||
t.Fatalf("installed agent = %q, want 1.10.0", got)
|
||||
}
|
||||
if _, found := result.Installed[ComponentDaemon]; found {
|
||||
t.Fatalf("runtime-only result unexpectedly claims a daemon install: %#v", result.Installed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateInstallBothComponentsBuildsDaemonAndManagedWorkerImage(t *testing.T) {
|
||||
result, calls := runUpdateInstallScript(t, map[string]string{
|
||||
"ARCHIE_UPDATE_DAEMON_PREVIOUS": "1.12.0",
|
||||
"ARCHIE_UPDATE_DAEMON_VERSION": "1.13.0",
|
||||
"ARCHIE_UPDATE_AGENT_PREVIOUS": "1.9.9",
|
||||
"ARCHIE_UPDATE_AGENT_VERSION": "1.10.0",
|
||||
})
|
||||
|
||||
assertCallContains(t, calls, "go build", "./cmd/archied")
|
||||
assertCallAbsent(t, calls, "./cmd/archie-agent")
|
||||
assertCallContains(t, calls, "docker image save", "registry.example/archie-agent:stable")
|
||||
assertCallContains(t, calls, "docker build", "RUNTIME_VERSION=1.10.0", "--tag registry.example/archie-agent:stable")
|
||||
if result.Installed[ComponentDaemon] != "1.13.0" || result.Installed[ComponentAgent] != "1.10.0" {
|
||||
t.Fatalf("installed = %#v, want both release versions", result.Installed)
|
||||
}
|
||||
}
|
||||
|
||||
// Components are independently versioned (RELEASING.md), so the newest
|
||||
// archied/v* and archie/v* tags usually sit on different commits -- gateway-only
|
||||
// releases are the norm. Each changed component must be built from its own
|
||||
// approved tag; forcing both tags onto one commit refuses every update once
|
||||
// the two components' newest releases diverge.
|
||||
// One version covers every component, so the managed worker image is built
|
||||
// from the release's own archied/v* tag -- never from a stale archie/v* tag.
|
||||
func TestUpdateInstallBuildsTheAgentImageFromTheReleaseTag(t *testing.T) {
|
||||
result, calls := runUpdateInstallScript(t, map[string]string{
|
||||
"ARCHIE_UPDATE_DAEMON_PREVIOUS": "1.12.0",
|
||||
"ARCHIE_UPDATE_DAEMON_VERSION": "1.13.0",
|
||||
"ARCHIE_UPDATE_AGENT_PREVIOUS": "1.12.0",
|
||||
"ARCHIE_UPDATE_AGENT_VERSION": "1.13.0",
|
||||
})
|
||||
|
||||
if result.Installed[ComponentDaemon] != "1.13.0" || result.Installed[ComponentAgent] != "1.13.0" {
|
||||
t.Fatalf("installed = %#v, want the release version for both", result.Installed)
|
||||
}
|
||||
assertCallAbsent(t, calls, "archie-v1.13.0")
|
||||
daemonBuild := indexOfCallContaining(t, calls, "go build", "./cmd/archied")
|
||||
agentImageBuild := indexOfCallContaining(t, calls, "docker build")
|
||||
lastCheckout := -1
|
||||
for i, call := range calls {
|
||||
if strings.Contains(call, "checkout --quiet --detach") && i < agentImageBuild {
|
||||
lastCheckout = i
|
||||
}
|
||||
}
|
||||
if daemonBuild < 0 || agentImageBuild < 0 || lastCheckout < 0 {
|
||||
t.Fatalf("missing expected step: daemon build %d, agent image build %d, checkout %d", daemonBuild, agentImageBuild, lastCheckout)
|
||||
}
|
||||
if !strings.Contains(calls[lastCheckout], "archied-v1.13.0") {
|
||||
t.Errorf("image built after checking out %q, want the archied/v1.13.0 release; calls = %#v", calls[lastCheckout], calls)
|
||||
}
|
||||
}
|
||||
|
||||
func indexOfCallContaining(t *testing.T, calls []string, fragments ...string) int {
|
||||
t.Helper()
|
||||
for i, call := range calls {
|
||||
matched := true
|
||||
for _, fragment := range fragments {
|
||||
matched = matched && strings.Contains(call, fragment)
|
||||
}
|
||||
if matched {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func TestUpdateInstallNoopDoesNotFetchBuildInstallOrRestart(t *testing.T) {
|
||||
result, calls := runUpdateInstallScript(t, map[string]string{
|
||||
"ARCHIE_UPDATE_DAEMON_PREVIOUS": "1.13.0",
|
||||
"ARCHIE_UPDATE_AGENT_PREVIOUS": "1.9.9",
|
||||
})
|
||||
|
||||
for _, forbidden := range []string{"git pull", "go build", "docker ", "systemd-run ", "install ", "cp "} {
|
||||
assertCallAbsent(t, calls, forbidden)
|
||||
}
|
||||
if len(result.Previous) != 0 || len(result.Installed) != 0 || len(result.Components) != 0 || result.RestartRequested {
|
||||
t.Fatalf("no-op result = %#v, want empty result without restart", result)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdateInstallForwardsHealthURLToTheWatchdogUnit closes the link between
|
||||
// the two: systemd-run starts the watchdog with a clean environment, so a
|
||||
// health address the daemon derived reaches the probe only if the install
|
||||
// script hands it over explicitly (archie-core-1r4g).
|
||||
func TestUpdateInstallForwardsHealthURLToTheWatchdogUnit(t *testing.T) {
|
||||
_, calls := runUpdateInstallScript(t, map[string]string{
|
||||
"ARCHIE_UPDATE_DAEMON_PREVIOUS": "1.12.0",
|
||||
"ARCHIE_UPDATE_DAEMON_VERSION": "1.13.0",
|
||||
"ARCHIE_UPDATE_AGENT_PREVIOUS": "1.9.9",
|
||||
"ARCHIE_HEALTH_URL": "http://127.0.0.1:9000",
|
||||
})
|
||||
|
||||
assertCallContains(t, calls, "systemd-run ", "--setenv=ARCHIE_HEALTH_URL=http://127.0.0.1:9000")
|
||||
}
|
||||
|
||||
func TestUpdateWatchdogRollsBackManagedWorkerImageAndReportsOnlyChangedComponents(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
components string
|
||||
wantDaemon string
|
||||
wantImageRollback bool
|
||||
}{
|
||||
{name: "gateway only", components: "daemon", wantDaemon: "old daemon"},
|
||||
{name: "runtime only", components: "agent", wantDaemon: "new daemon", wantImageRollback: true},
|
||||
{name: "both", components: "daemon,agent", wantDaemon: "old daemon", wantImageRollback: true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
report, daemon, calls := runUpdateWatchdogFailure(t, tt.components)
|
||||
if daemon != tt.wantDaemon {
|
||||
t.Fatalf("daemon after rollback = %q, want %q", daemon, tt.wantDaemon)
|
||||
}
|
||||
if tt.wantImageRollback {
|
||||
assertCallContains(t, calls, "docker image load", "archie-agent-image.prev.tar")
|
||||
} else {
|
||||
assertCallAbsent(t, calls, "docker image load")
|
||||
}
|
||||
if !report.RolledBack || report.HealthCheck != "failed" {
|
||||
t.Fatalf("report = %#v, want failed rollback", report)
|
||||
}
|
||||
if _, found := report.Installed[ComponentDaemon]; found != strings.Contains(tt.components, "daemon") {
|
||||
t.Fatalf("daemon report membership = %v for components %q", found, tt.components)
|
||||
}
|
||||
if _, found := report.Installed[ComponentAgent]; found != strings.Contains(tt.components, "agent") {
|
||||
t.Fatalf("agent report membership = %v for components %q", found, tt.components)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdateWatchdogPassesHealthCheckAgainstRealListener exercises the branch
|
||||
// no other test reaches: a daemon that comes back up. Every other watchdog
|
||||
// test fakes curl as an immediate failure, so before this one the probe URL
|
||||
// the script actually builds was never dialled and its default could point
|
||||
// anywhere (archie-core-1r4g).
|
||||
func TestUpdateWatchdogPassesHealthCheckAgainstRealListener(t *testing.T) {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) })
|
||||
daemon := httptest.NewServer(mux)
|
||||
defer daemon.Close()
|
||||
|
||||
report, installed, calls := runUpdateWatchdog(t, watchdogRun{
|
||||
components: "daemon",
|
||||
env: map[string]string{
|
||||
"ARCHIE_HEALTH_URL": daemon.URL,
|
||||
"ARCHIE_UPDATE_HEALTH_TIMEOUT": "10",
|
||||
},
|
||||
})
|
||||
|
||||
if report.HealthCheck != "passed" || report.RolledBack {
|
||||
t.Fatalf("report = %#v, want a passed health check with no rollback", report)
|
||||
}
|
||||
if installed != "new daemon" {
|
||||
t.Fatalf("installed daemon = %q, want the new binary left in place", installed)
|
||||
}
|
||||
assertCallAbsent(t, calls, "docker image load")
|
||||
}
|
||||
|
||||
// TestUpdateWatchdogDefaultHealthURLTargetsTheDaemon pins the fallback the
|
||||
// script uses when nothing exports one. It has to be the address archied
|
||||
// itself serves /healthz on ([health] listen); anything else times out and
|
||||
// rolls back a healthy release.
|
||||
func TestUpdateWatchdogDefaultHealthURLTargetsTheDaemon(t *testing.T) {
|
||||
report, _, calls := runUpdateWatchdog(t, watchdogRun{
|
||||
components: "daemon",
|
||||
curl: `printf '%s\n' "curl $*" >> "$ARCHIE_TEST_CALLS"; exit 0`,
|
||||
env: map[string]string{"ARCHIE_UPDATE_HEALTH_TIMEOUT": "10"},
|
||||
})
|
||||
|
||||
assertCallContains(t, calls, "curl ", "http://127.0.0.1:8485/healthz")
|
||||
if report.HealthCheck != "passed" || report.RolledBack {
|
||||
t.Fatalf("report = %#v, want a passed health check with no rollback", report)
|
||||
}
|
||||
}
|
||||
|
||||
func runUpdateInstallScript(t *testing.T, environment map[string]string) (Result, []string) {
|
||||
t.Helper()
|
||||
result, calls, _ := runUpdateInstall(t, environment, false)
|
||||
return result, calls
|
||||
}
|
||||
|
||||
// runUpdateInstall runs the adapter, optionally expecting it to refuse. It
|
||||
// returns the parsed result (empty when the run was expected to fail), the
|
||||
// recorded calls, and the combined output.
|
||||
func runUpdateInstall(t *testing.T, environment map[string]string, wantErr bool) (Result, []string, string) {
|
||||
t.Helper()
|
||||
return runUpdateInstallWithConfig(t, environment, "[containers]\nimage = 'registry.example/archie-agent:stable'\n", wantErr)
|
||||
}
|
||||
|
||||
// runUpdateInstallWithConfig is runUpdateInstall with the operator's config
|
||||
// file under the caller's control. Config-derived behaviour -- which database
|
||||
// the updater backs up, which image it rebuilds -- is otherwise untestable,
|
||||
// which is how the task-database backup path came to be wrong.
|
||||
func runUpdateInstallWithConfig(t *testing.T, environment map[string]string, configBody string, wantErr bool) (Result, []string, string) {
|
||||
t.Helper()
|
||||
return runUpdateInstallEdited(t, environment, configBody, nil, wantErr)
|
||||
}
|
||||
|
||||
// runUpdateInstallEdited is runUpdateInstallWithConfig with the ability to edit
|
||||
// the installer's text before it runs. The service list is hardcoded, so the
|
||||
// only way to test the coverage guard against the stale list it exists for is to
|
||||
// change that text -- which is exactly the state the guard must catch.
|
||||
func runUpdateInstallEdited(t *testing.T, environment map[string]string, configBody string, edit func(string) string, wantErr bool) (Result, []string, string) {
|
||||
t.Helper()
|
||||
return runUpdateInstallFull(t, environment, configBody, nil, edit, wantErr)
|
||||
}
|
||||
|
||||
// runUpdateInstallFull is runUpdateInstallEdited with control over the versions
|
||||
// already installed in the bin directory, so a skewed host can be built on
|
||||
// purpose (archie-core-k94o).
|
||||
func runUpdateInstallFull(t *testing.T, environment map[string]string, configBody string, installed map[string]string, edit func(string) string, wantErr bool) (Result, []string, string) {
|
||||
t.Helper()
|
||||
ctx := t.Context()
|
||||
|
||||
root, err := filepath.Abs(filepath.Join("..", ".."))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
work := t.TempDir()
|
||||
binDir := filepath.Join(work, "bin")
|
||||
configPath := filepath.Join(work, "config.toml")
|
||||
fakeDir := filepath.Join(work, "fake-bin")
|
||||
callsPath := filepath.Join(work, "calls")
|
||||
if err := os.MkdirAll(binDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(configPath, []byte(configBody), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
previousVersion := environment["ARCHIE_UPDATE_DAEMON_PREVIOUS"]
|
||||
if previousVersion == "" {
|
||||
previousVersion = "dev"
|
||||
}
|
||||
writeFakeBinary(t, binDir, "archied", previousVersion)
|
||||
if err := os.WriteFile(filepath.Join(binDir, "archie-agent"), []byte("old archie-agent"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for name, version := range installed {
|
||||
writeFakeBinary(t, binDir, name, version)
|
||||
}
|
||||
writeFakeCommand(t, fakeDir, "git", `
|
||||
printf '%s\n' "git $*" >> "$ARCHIE_TEST_CALLS"
|
||||
case "$*" in
|
||||
*"clone "*)
|
||||
source_dir="${@: -1}"
|
||||
mkdir -p "$source_dir"
|
||||
/usr/bin/cp -R "$ARCHIE_TEST_SOURCE_DIR/scripts" "$source_dir/scripts"
|
||||
for c in archied archie-gateway archie-state-store archie-ui archie-messaging archie-playbooks archie-agent; do
|
||||
mkdir -p "$source_dir/cmd/$c"
|
||||
done
|
||||
: > "$source_dir/docker-compose.yml"
|
||||
;;
|
||||
*"rev-parse --verify refs/tags/"*)
|
||||
tag="$(printf '%s' "$*" | sed 's/.*refs\/tags\///; s/\^.*//')"
|
||||
echo "${tag//\//-}"
|
||||
;;
|
||||
esac
|
||||
`)
|
||||
writeFakeCommand(t, fakeDir, "go", `
|
||||
printf '%s\n' "go $*" >> "$ARCHIE_TEST_CALLS"
|
||||
# The pre-flight database snapshot runs through the release's own
|
||||
# archie-state-store subcommand, so a release whose recovery path cannot run
|
||||
# must refuse the update.
|
||||
if [ "$1" = "run" ]; then
|
||||
[ "${ARCHIE_TEST_GO_FAILS_SNAPSHOT:-}" = "1" ] && exit 1
|
||||
exit 0
|
||||
fi
|
||||
out=""
|
||||
name=""
|
||||
version="dev"
|
||||
while [ "$#" -gt 0 ]; do
|
||||
if [ "$1" = "-o" ]; then out="$2"; fi
|
||||
case "$1" in
|
||||
./cmd/*) name="${1#./cmd/}" ;;
|
||||
*buildinfo.Version=*)
|
||||
version="${1##*buildinfo.Version=}"
|
||||
version="${version%% *}"
|
||||
;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
mkdir -p "$(dirname "$out")"
|
||||
# The installed binary must answer -version the way a real one does, or the
|
||||
# updater's skew check cannot read it.
|
||||
printf '#!/usr/bin/env bash\necho "%s %s"\n' "$name" "$version" > "$out"
|
||||
chmod 755 "$out"
|
||||
`)
|
||||
writeFakeCommand(t, fakeDir, "docker", `
|
||||
printf '%s\n' "docker $*" >> "$ARCHIE_TEST_CALLS"
|
||||
if [ "$1" = image ] && [ "$2" = save ]; then
|
||||
while [ "$#" -gt 0 ]; do
|
||||
if [ "$1" = --output ]; then
|
||||
: > "$2"
|
||||
break
|
||||
fi
|
||||
shift
|
||||
done
|
||||
fi
|
||||
`)
|
||||
writeFakeCommand(t, fakeDir, "systemd-run", `printf '%s\n' "systemd-run $*" >> "$ARCHIE_TEST_CALLS"`)
|
||||
writeFakeCommand(t, fakeDir, "systemctl", `
|
||||
printf '%s\n' "systemctl $*" >> "$ARCHIE_TEST_CALLS"
|
||||
if [ "$2" = list-unit-files ]; then
|
||||
# The reference deployment runs exactly these five as units. A command with
|
||||
# no unit -- archie-playbooks, archie-agent -- has to look unitless, or the
|
||||
# coverage guard would mistake every cmd/ directory for a host service.
|
||||
present="${ARCHIE_TEST_PRESENT_UNITS:-archied.service archie-gateway.service archie-state-store.service archie-ui.service archie-messaging.service}"
|
||||
case " ${ARCHIE_TEST_ABSENT_UNITS:-} " in
|
||||
*" $3 "*) exit 0 ;;
|
||||
esac
|
||||
case " $present " in
|
||||
*" $3 "*) printf '%s enabled enabled\n' "$3" ;;
|
||||
esac
|
||||
fi
|
||||
`)
|
||||
writeFakeCommand(t, fakeDir, "install", `
|
||||
printf '%s\n' "install $*" >> "$ARCHIE_TEST_CALLS"
|
||||
/usr/bin/install "$@"
|
||||
`)
|
||||
writeFakeCommand(t, fakeDir, "cp", `
|
||||
printf '%s\n' "cp $*" >> "$ARCHIE_TEST_CALLS"
|
||||
/usr/bin/cp "$@"
|
||||
`)
|
||||
// The production adapter prepends /usr/local/go/bin. Run an otherwise
|
||||
// byte-for-byte copy with the harness PATH left first so fake go records
|
||||
// build intent without compiling or touching Docker/systemd.
|
||||
scriptData, err := os.ReadFile(filepath.Join(root, "scripts", "archie-update-install"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
script := string(scriptData)
|
||||
if edit != nil {
|
||||
script = edit(script)
|
||||
}
|
||||
scriptPath := filepath.Join(work, "archie-update-install")
|
||||
script = strings.Replace(script, `export PATH="/usr/local/go/bin:$PATH"`, `export PATH="$PATH"`, 1)
|
||||
if err := os.WriteFile(scriptPath, []byte(script), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cmd := exec.CommandContext(ctx, scriptPath)
|
||||
cmd.Env = append(
|
||||
os.Environ(),
|
||||
"PATH="+fakeDir+":"+os.Getenv("PATH"),
|
||||
"ARCHIE_SOURCE_URL=https://example.invalid/archie-core.git",
|
||||
"ARCHIE_TEST_SOURCE_DIR="+root,
|
||||
"ARCHIE_BIN_DIR="+binDir,
|
||||
"ARCHIE_CONFIG_PATH="+configPath,
|
||||
"ARCHIE_TEST_CALLS="+callsPath,
|
||||
)
|
||||
for key, value := range environment {
|
||||
cmd.Env = append(cmd.Env, key+"="+value)
|
||||
}
|
||||
output, err := cmd.CombinedOutput()
|
||||
switch {
|
||||
case wantErr && err == nil:
|
||||
t.Fatalf("archie-update-install succeeded, want refusal:\n%s", output)
|
||||
case !wantErr && err != nil:
|
||||
t.Fatalf("archie-update-install failed: %v\n%s", err, output)
|
||||
}
|
||||
callsData, err := os.ReadFile(callsPath)
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var calls []string
|
||||
if len(callsData) > 0 {
|
||||
calls = strings.Split(strings.TrimSpace(string(callsData)), "\n")
|
||||
}
|
||||
if wantErr {
|
||||
return Result{}, calls, string(output)
|
||||
}
|
||||
var result Result
|
||||
scanner := bufio.NewScanner(strings.NewReader(string(output)))
|
||||
found := false
|
||||
for scanner.Scan() {
|
||||
if payload, ok := strings.CutPrefix(scanner.Text(), updateResultSentinel); ok {
|
||||
found = true
|
||||
if err := json.Unmarshal([]byte(payload), &result); err != nil {
|
||||
t.Fatalf("decode result %q: %v", payload, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("installer output has no result sentinel:\n%s", output)
|
||||
}
|
||||
return result, calls, string(output)
|
||||
}
|
||||
|
||||
func writeFakeBinary(t *testing.T, dir, name, version string) {
|
||||
t.Helper()
|
||||
body := "#!/usr/bin/env bash\necho " + strconv.Quote(name+" "+version) + "\n"
|
||||
if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func writeFakeCommand(t *testing.T, dir, name, body string) {
|
||||
t.Helper()
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := filepath.Join(dir, name)
|
||||
if err := os.WriteFile(path, []byte("#!/usr/bin/env bash\nset -euo pipefail\n"+body), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// watchdogRun configures one end-to-end run of the watchdog script. curl is
|
||||
// the fake curl placed on PATH; leaving it empty keeps the real curl there,
|
||||
// which is what turns a health probe into a genuine test of the URL the
|
||||
// watchdog builds rather than of a stub that ignores it.
|
||||
type watchdogRun struct {
|
||||
components string
|
||||
curl string
|
||||
// systemctl replaces the fake systemctl on PATH, so a case can observe or
|
||||
// condition what the watchdog does between units. Empty keeps the inert
|
||||
// `exit 0` stub.
|
||||
systemctl string
|
||||
env map[string]string
|
||||
}
|
||||
|
||||
func runUpdateWatchdogFailure(t *testing.T, components string) (Report, string, []string) {
|
||||
t.Helper()
|
||||
return runUpdateWatchdog(t, watchdogRun{
|
||||
components: components,
|
||||
curl: `exit 1`,
|
||||
env: map[string]string{"ARCHIE_UPDATE_HEALTH_TIMEOUT": "0"},
|
||||
})
|
||||
}
|
||||
|
||||
func runUpdateWatchdog(t *testing.T, run watchdogRun) (Report, string, []string) {
|
||||
t.Helper()
|
||||
ctx := t.Context()
|
||||
|
||||
root, err := filepath.Abs(filepath.Join("..", ".."))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
work := t.TempDir()
|
||||
binDir := filepath.Join(work, "bin")
|
||||
fakeDir := filepath.Join(work, "fake-bin")
|
||||
reportPath := filepath.Join(work, "report.json")
|
||||
if err := os.MkdirAll(binDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
files := map[string]string{
|
||||
"archied": "new daemon", "archied.prev": "old daemon",
|
||||
"archie-agent-image.prev.tar": "saved old image",
|
||||
}
|
||||
for name, content := range files {
|
||||
if err := os.WriteFile(filepath.Join(binDir, name), []byte(content), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
systemctl := run.systemctl
|
||||
if systemctl == "" {
|
||||
systemctl = `exit 0`
|
||||
}
|
||||
writeFakeCommand(t, fakeDir, "systemctl", systemctl)
|
||||
if run.curl != "" {
|
||||
writeFakeCommand(t, fakeDir, "curl", run.curl)
|
||||
}
|
||||
writeFakeCommand(t, fakeDir, "docker", `printf '%s\n' "docker $*" >> "$ARCHIE_TEST_CALLS"`)
|
||||
callsPath := filepath.Join(work, "calls")
|
||||
|
||||
cmd := exec.CommandContext(ctx, filepath.Join(root, "scripts", "archie-update-watchdog"))
|
||||
cmd.Env = append(
|
||||
os.Environ(),
|
||||
"PATH="+fakeDir+":"+os.Getenv("PATH"),
|
||||
"ARCHIE_BIN_DIR="+binDir,
|
||||
"ARCHIE_TEST_CALLS="+callsPath,
|
||||
"ARCHIE_AGENT_IMAGE=registry.example/archie-agent:stable",
|
||||
"ARCHIE_UPDATE_REPORT_PATH="+reportPath,
|
||||
"ARCHIE_UPDATE_COMPONENTS="+run.components,
|
||||
"ARCHIE_UPDATE_PREVIOUS_GATEWAY=1.12.0",
|
||||
"ARCHIE_UPDATE_INSTALLED_GATEWAY=1.13.0",
|
||||
"ARCHIE_UPDATE_PREVIOUS_RUNTIME=1.9.9",
|
||||
"ARCHIE_UPDATE_INSTALLED_RUNTIME=1.10.0",
|
||||
)
|
||||
for key, value := range run.env {
|
||||
cmd.Env = append(cmd.Env, key+"="+value)
|
||||
}
|
||||
if output, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("watchdog failed: %v\n%s", err, output)
|
||||
}
|
||||
reportData, err := os.ReadFile(reportPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var report Report
|
||||
if err := json.Unmarshal(reportData, &report); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
daemon, err := os.ReadFile(filepath.Join(binDir, "archied"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
callsData, err := os.ReadFile(callsPath)
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var calls []string
|
||||
if len(callsData) > 0 {
|
||||
calls = strings.Split(strings.TrimSpace(string(callsData)), "\n")
|
||||
}
|
||||
return report, string(daemon), calls
|
||||
}
|
||||
|
||||
func assertCallContains(t *testing.T, calls []string, fragments ...string) {
|
||||
t.Helper()
|
||||
for _, call := range calls {
|
||||
matched := true
|
||||
for _, fragment := range fragments {
|
||||
matched = matched && strings.Contains(call, fragment)
|
||||
}
|
||||
if matched {
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatalf("calls %#v contain no call with fragments %#v", calls, fragments)
|
||||
}
|
||||
|
||||
func assertCallAbsent(t *testing.T, calls []string, fragment string) {
|
||||
t.Helper()
|
||||
for _, call := range calls {
|
||||
if strings.Contains(call, fragment) {
|
||||
t.Fatalf("calls unexpectedly contain %q: %#v", fragment, calls)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// An archied release is five processes. Installing the daemon binary alone
|
||||
// left the State Store, Gateway and UI on the previous release, so archied
|
||||
// came up against a State Store nothing had started, failed its health check
|
||||
// and rolled back (archie-core-hbqk).
|
||||
func TestUpdateInstallBuildsEveryReleaseBinary(t *testing.T) {
|
||||
_, calls := runUpdateInstallScript(t, map[string]string{
|
||||
"ARCHIE_UPDATE_DAEMON_PREVIOUS": "1.22.0",
|
||||
"ARCHIE_UPDATE_DAEMON_VERSION": "1.23.0",
|
||||
"ARCHIE_UPDATE_AGENT_PREVIOUS": "1.21.0",
|
||||
})
|
||||
|
||||
for _, cmd := range []string{"archied", "archie-gateway", "archie-state-store", "archie-ui", "archie-messaging", "archie-playbooks"} {
|
||||
assertCallContains(t, calls, "go build", "internal/app/archied.gatewayVersion=1.23.0", "./cmd/"+cmd)
|
||||
assertCallContains(t, calls, "install -m755", "/"+cmd)
|
||||
}
|
||||
assertCallAbsent(t, calls, "./cmd/archie-agent")
|
||||
// The watchdog cannot restart what it is not told about.
|
||||
assertCallContains(t, calls, "systemd-run",
|
||||
"--setenv=ARCHIE_UPDATE_UNITS=archie-state-store archie-gateway archied archie-ui archie-messaging")
|
||||
assertCallContains(t, calls, "systemd-run",
|
||||
"--setenv=ARCHIE_UPDATE_BINARIES=archie-state-store archie-gateway archied archie-ui archie-messaging archie-playbooks")
|
||||
}
|
||||
|
||||
// Installing binaries for processes the host has no unit for produces exactly
|
||||
// the failure this bug was: archied dials a State Store nothing starts. Refuse
|
||||
// before touching the host instead, and say what is missing.
|
||||
func TestUpdateInstallRefusesWhenAServiceUnitIsMissing(t *testing.T) {
|
||||
_, calls, output := runUpdateInstall(t, map[string]string{
|
||||
"ARCHIE_UPDATE_DAEMON_PREVIOUS": "1.22.0",
|
||||
"ARCHIE_UPDATE_DAEMON_VERSION": "1.23.0",
|
||||
"ARCHIE_UPDATE_AGENT_PREVIOUS": "1.21.0",
|
||||
"ARCHIE_TEST_ABSENT_UNITS": "archie-state-store.service",
|
||||
}, true)
|
||||
|
||||
if !strings.Contains(output, "archie-state-store.service") {
|
||||
t.Errorf("refusal must name the missing unit; output = %q", output)
|
||||
}
|
||||
t.Logf("refusal output:\n%s", strings.TrimSpace(output))
|
||||
// Nothing may be replaced on a host it would leave broken.
|
||||
assertCallAbsent(t, calls, "go build")
|
||||
assertCallAbsent(t, calls, "install -m755")
|
||||
}
|
||||
|
||||
// The other half of the same contract, and the failure that actually happened
|
||||
// (archie-core-1faq): the installed updater's GATEWAY_SERVICES predated
|
||||
// archie-messaging, so the update neither backed it up nor restarted it and a
|
||||
// hand-installed binary kept serving under an otherwise updated host. A unit
|
||||
// this host runs must be named by the list, or the update refuses and says which.
|
||||
func TestUpdateInstallRefusesWhenTheServiceListOmitsAHostUnit(t *testing.T) {
|
||||
_, calls, output := runUpdateInstallEdited(t, map[string]string{
|
||||
"ARCHIE_UPDATE_DAEMON_PREVIOUS": "1.22.0",
|
||||
"ARCHIE_UPDATE_DAEMON_VERSION": "1.23.0",
|
||||
"ARCHIE_UPDATE_AGENT_PREVIOUS": "1.21.0",
|
||||
}, "[containers]\nimage = 'registry.example/archie-agent:stable'\n", func(script string) string {
|
||||
// Drop archie-messaging from the list without touching its unit: the
|
||||
// stale installed updater's view of the host.
|
||||
return strings.Replace(script,
|
||||
`GATEWAY_SERVICES="archie-state-store archie-gateway archied archie-ui archie-messaging"`,
|
||||
`GATEWAY_SERVICES="archie-state-store archie-gateway archied archie-ui"`,
|
||||
1)
|
||||
}, true)
|
||||
|
||||
if !strings.Contains(output, "archie-messaging.service") {
|
||||
t.Errorf("refusal must name the unmanaged unit; output = %q", output)
|
||||
}
|
||||
t.Logf("refusal output:\n%s", strings.TrimSpace(output))
|
||||
// Nothing may be replaced on a host the update would leave partial.
|
||||
assertCallAbsent(t, calls, "go build")
|
||||
assertCallAbsent(t, calls, "install -m755")
|
||||
}
|
||||
|
||||
// Carina's actual pair (archie-core-k94o): archie-messaging 1.35.0 beside an
|
||||
// archie-state-store 1.30.0, the daemon at 1.30.0, and nothing approved to
|
||||
// install. The component-driven updater reported only "nothing to install"
|
||||
// while the two disagreed; now it reads each installed binary and names them.
|
||||
func TestUpdateInstallRefusesWhenInstalledBinariesDisagree(t *testing.T) {
|
||||
_, calls, output := runUpdateInstallFull(t, map[string]string{
|
||||
"ARCHIE_UPDATE_DAEMON_PREVIOUS": "1.30.0",
|
||||
"ARCHIE_UPDATE_AGENT_PREVIOUS": "1.30.0",
|
||||
}, "[containers]\nimage = 'registry.example/archie-agent:stable'\n", map[string]string{
|
||||
"archie-messaging": "1.35.0",
|
||||
"archie-state-store": "1.30.0",
|
||||
}, nil, true)
|
||||
|
||||
if !strings.Contains(output, "archie-messaging=1.35.0") {
|
||||
t.Errorf("refusal must name the skewed binary and its version; output = %q", output)
|
||||
}
|
||||
if strings.Contains(output, "archie-state-store=") {
|
||||
t.Errorf("refusal named a binary that agrees; output = %q", output)
|
||||
}
|
||||
assertCallAbsent(t, calls, "go build")
|
||||
assertCallAbsent(t, calls, "install -m755")
|
||||
t.Logf("refusal output:\n%s", strings.TrimSpace(output))
|
||||
}
|
||||
|
||||
// A binary built outside a release reports "dev"; on a released host that is
|
||||
// skew too, and it must be named rather than read as agreement.
|
||||
func TestUpdateInstallRefusesAnUnstampedBinary(t *testing.T) {
|
||||
_, _, output := runUpdateInstallFull(t, map[string]string{
|
||||
"ARCHIE_UPDATE_DAEMON_PREVIOUS": "1.30.0",
|
||||
"ARCHIE_UPDATE_AGENT_PREVIOUS": "1.30.0",
|
||||
}, "[containers]\nimage = 'registry.example/archie-agent:stable'\n", map[string]string{
|
||||
"archie-ui": "dev",
|
||||
}, nil, true)
|
||||
|
||||
if !strings.Contains(output, "archie-ui=dev") {
|
||||
t.Errorf("refusal must name the unstamped binary; output = %q", output)
|
||||
}
|
||||
}
|
||||
|
||||
// The deployment is several processes, so the watchdog must cycle all of them,
|
||||
// and in dependency order: the State Store owns archie.db and everything dials
|
||||
// it, so it starts first and stops last (archie-core-hbqk).
|
||||
func TestUpdateWatchdogCyclesEveryUnitInDependencyOrder(t *testing.T) {
|
||||
root, err := filepath.Abs(filepath.Join("..", ".."))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
work := t.TempDir()
|
||||
binDir, fakeDir := filepath.Join(work, "bin"), filepath.Join(work, "fake-bin")
|
||||
if err := os.MkdirAll(binDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// archie-ui is new in this release: it has no .prev, so rolling back must
|
||||
// remove it rather than leave a binary from a release that was withdrawn.
|
||||
for name, content := range map[string]string{
|
||||
"archied": "new", "archied.prev": "old",
|
||||
"archie-state-store": "new", "archie-state-store.prev": "old",
|
||||
"archie-ui": "new",
|
||||
} {
|
||||
if err := os.WriteFile(filepath.Join(binDir, name), []byte(content), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
callsPath := filepath.Join(work, "calls")
|
||||
writeFakeCommand(t, fakeDir, "systemctl", `printf '%s\n' "systemctl $*" >> "$ARCHIE_TEST_CALLS"`)
|
||||
writeFakeCommand(t, fakeDir, "curl", `exit 1`)
|
||||
cmd := exec.CommandContext(t.Context(), filepath.Join(root, "scripts", "archie-update-watchdog"))
|
||||
cmd.Env = append(os.Environ(), "PATH="+fakeDir+":"+os.Getenv("PATH"), "ARCHIE_BIN_DIR="+binDir,
|
||||
"ARCHIE_TEST_CALLS="+callsPath, "ARCHIE_UPDATE_HEALTH_TIMEOUT=0",
|
||||
"ARCHIE_UPDATE_COMPONENTS=daemon",
|
||||
"ARCHIE_UPDATE_UNITS=archie-state-store archied archie-ui",
|
||||
"ARCHIE_UPDATE_BINARIES=archie-state-store archied archie-ui",
|
||||
"ARCHIE_UPDATE_PREVIOUS_GATEWAY=1.22.0", "ARCHIE_UPDATE_INSTALLED_GATEWAY=1.23.0")
|
||||
if output, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("watchdog failed: %v\n%s", err, output)
|
||||
}
|
||||
calls, err := os.ReadFile(callsPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
indexOf := func(want string) int {
|
||||
for i, line := range strings.Split(strings.TrimSpace(string(calls)), "\n") {
|
||||
if line == want {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
startStore := indexOf("systemctl --user restart archie-state-store.service")
|
||||
startDaemon := indexOf("systemctl --user restart archied.service")
|
||||
stopUI := indexOf("systemctl --user stop archie-ui.service")
|
||||
stopStore := indexOf("systemctl --user stop archie-state-store.service")
|
||||
if startStore < 0 || startDaemon < 0 || startStore > startDaemon {
|
||||
t.Errorf("State Store must start before archied; calls =\n%s", calls)
|
||||
}
|
||||
if stopUI < 0 || stopStore < 0 || stopUI > stopStore {
|
||||
t.Errorf("UI must stop before the State Store; calls =\n%s", calls)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(binDir, "archie-ui")); !os.IsNotExist(err) {
|
||||
t.Errorf("archie-ui had no .prev and must be removed on rollback, stat err = %v", err)
|
||||
}
|
||||
for _, name := range []string{"archied", "archie-state-store"} {
|
||||
got, err := os.ReadFile(filepath.Join(binDir, name))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(got) != "old" {
|
||||
t.Errorf("%s = %q after rollback, want the previous binary", name, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The sidecar is the only record of the managed agent version, and
|
||||
// archie-update-check refuses anything but a bare release version, so a stray
|
||||
// escape in the write leaves the installed agent reported as unknown forever.
|
||||
func TestUpdateInstallWritesABareAgentVersionSidecar(t *testing.T) {
|
||||
versionFile := filepath.Join(t.TempDir(), "archie-agent.version")
|
||||
runUpdateInstallScript(t, map[string]string{
|
||||
"ARCHIE_UPDATE_DAEMON_PREVIOUS": "1.13.0",
|
||||
"ARCHIE_UPDATE_AGENT_PREVIOUS": "1.9.9",
|
||||
"ARCHIE_UPDATE_AGENT_VERSION": "1.10.0",
|
||||
"ARCHIE_AGENT_VERSION_FILE": versionFile,
|
||||
})
|
||||
|
||||
recorded, err := os.ReadFile(versionFile)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(recorded) != "1.10.0\n" {
|
||||
t.Fatalf("sidecar = %q, want %q", recorded, "1.10.0\n")
|
||||
}
|
||||
}
|
||||
|
||||
// freeAddress reserves a loopback address nothing is listening on and releases
|
||||
// it, so a case can hand the watchdog a State Store target whose port stays
|
||||
// closed until the fake State Store binds it.
|
||||
func freeAddress(t *testing.T) string {
|
||||
t.Helper()
|
||||
var listen net.ListenConfig
|
||||
listener, err := listen.Listen(t.Context(), "tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
address := listener.Addr().String()
|
||||
if err := listener.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return address
|
||||
}
|
||||
|
||||
// TestUpdateWatchdogWaitsForTheStateStoreBeforeStartingArchied pins why an
|
||||
// ordered start is not enough on its own.
|
||||
//
|
||||
// `systemctl --user start` returns once the process is forked, not once its port
|
||||
// accepts. On a real 1.37.1 -> 1.38.0 update the State Store's unit reported
|
||||
// started while it was still binding, archied started next, dialled a closed
|
||||
// port, exited 1, and was rescued only by systemd's Restart=on-failure seven
|
||||
// seconds later -- behind a "build and install succeeded" line, on a unit that
|
||||
// need not carry that restart policy at all.
|
||||
//
|
||||
// The fake State Store binds its port two seconds AFTER systemctl returns, which
|
||||
// is the race. The fake systemctl for archied records whether the port was open
|
||||
// at the moment it was asked to start, so a watchdog that starts archied without
|
||||
// waiting says so in the call log rather than passing quietly.
|
||||
func TestUpdateWatchdogWaitsForTheStateStoreBeforeStartingArchied(t *testing.T) {
|
||||
target := freeAddress(t)
|
||||
_, _, calls := runUpdateWatchdog(t, watchdogRun{
|
||||
components: "daemon",
|
||||
curl: `exit 1`,
|
||||
systemctl: `
|
||||
printf '%s\n' "systemctl $*" >> "$ARCHIE_TEST_CALLS"
|
||||
case "$*" in
|
||||
*"restart archie-state-store.service")
|
||||
# Bind two seconds late, then hold the port: the State Store's unit returning
|
||||
# before its listener exists is the whole failure being guarded against.
|
||||
( sleep 2; exec python3 -c "import os,socket,time; h,p=os.environ['ARCHIE_UPDATE_STATE_STORE_TARGET'].rsplit(':',1); s=socket.socket(); s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1); s.bind((h,int(p))); s.listen(8); time.sleep(30)" ) >/dev/null 2>&1 &
|
||||
;;
|
||||
*"restart archied.service")
|
||||
if ! (exec 3<>"/dev/tcp/${ARCHIE_UPDATE_STATE_STORE_TARGET%:*}/${ARCHIE_UPDATE_STATE_STORE_TARGET##*:}") 2>/dev/null; then
|
||||
printf '%s\n' 'archied started before the state store accepted' >> "$ARCHIE_TEST_CALLS"
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
exit 0`,
|
||||
env: map[string]string{
|
||||
"ARCHIE_UPDATE_HEALTH_TIMEOUT": "0",
|
||||
"ARCHIE_UPDATE_UNITS": "archie-state-store archie-gateway archied",
|
||||
"ARCHIE_UPDATE_STATE_STORE_TARGET": target,
|
||||
"ARCHIE_UPDATE_STATE_STORE_TIMEOUT": "15",
|
||||
},
|
||||
})
|
||||
|
||||
assertCallContains(t, calls, "restart archie-state-store.service")
|
||||
assertCallContains(t, calls, "restart archie-gateway.service")
|
||||
assertCallContains(t, calls, "restart archied.service")
|
||||
assertCallAbsent(t, calls, "archied started before the state store accepted")
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
package releaseupdate
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestPendingReportRoundTrip covers the cross-restart handoff: the watchdog
|
||||
// script decides the phase-2 outcome and writes it; whichever archied
|
||||
// process boots next reads it, relays it, and clears it so it is never
|
||||
// reported twice.
|
||||
func TestPendingReportRoundTrip(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "update-report.json")
|
||||
want := Report{
|
||||
Channel: "telegram",
|
||||
ChatID: 42,
|
||||
ThreadID: 7,
|
||||
Previous: map[string]string{"daemon": "1.0.0", "agent": "1.0.0"},
|
||||
Installed: map[string]string{"daemon": "1.1.0", "agent": "1.0.0"},
|
||||
HealthCheck: "passed",
|
||||
RolledBack: false,
|
||||
}
|
||||
|
||||
if err := WritePendingReport(path, want); err != nil {
|
||||
t.Fatalf("WritePendingReport() error = %v", err)
|
||||
}
|
||||
|
||||
got, found, err := ReadPendingReport(path)
|
||||
if err != nil {
|
||||
t.Fatalf("ReadPendingReport() error = %v", err)
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("ReadPendingReport() found = false, want true")
|
||||
}
|
||||
if got.Channel != want.Channel || got.ChatID != want.ChatID || got.ThreadID != want.ThreadID ||
|
||||
got.HealthCheck != want.HealthCheck || got.RolledBack != want.RolledBack ||
|
||||
got.Installed["daemon"] != want.Installed["daemon"] || got.Previous["daemon"] != want.Previous["daemon"] {
|
||||
t.Fatalf("ReadPendingReport() = %#v, want %#v", got, want)
|
||||
}
|
||||
|
||||
if err := ClearPendingReport(path); err != nil {
|
||||
t.Fatalf("ClearPendingReport() error = %v", err)
|
||||
}
|
||||
if _, err := os.Stat(path); !os.IsNotExist(err) {
|
||||
t.Fatalf("report file still exists after ClearPendingReport(): err = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReadPendingReportMissingFileReturnsNotFound: no update in flight is
|
||||
// the overwhelmingly common case (every normal startup), so it must be a
|
||||
// plain "not found", never an error a caller has to specially ignore.
|
||||
func TestReadPendingReportMissingFileReturnsNotFound(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "does-not-exist.json")
|
||||
_, found, err := ReadPendingReport(path)
|
||||
if err != nil {
|
||||
t.Fatalf("ReadPendingReport() error = %v, want nil", err)
|
||||
}
|
||||
if found {
|
||||
t.Fatal("ReadPendingReport() found = true, want false")
|
||||
}
|
||||
}
|
||||
|
||||
// TestClearPendingReportMissingFileIsNotAnError: startup may race a report
|
||||
// that was already cleared by a previous boot attempt; clearing twice must
|
||||
// be harmless.
|
||||
func TestClearPendingReportMissingFileIsNotAnError(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "does-not-exist.json")
|
||||
if err := ClearPendingReport(path); err != nil {
|
||||
t.Fatalf("ClearPendingReport() error = %v, want nil for a missing file", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWritePendingReportRejectsRolledBackWithoutHealthCheckFailure(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "update-report.json")
|
||||
bad := Report{Channel: "telegram", ChatID: 1, RolledBack: true, HealthCheck: "passed"}
|
||||
if err := WritePendingReport(path, bad); err == nil {
|
||||
t.Fatal("WritePendingReport() error = nil, want a validation error for rolled_back+passed")
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
package releaseupdate
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
)
|
||||
|
||||
// TestReportEventDistinguishesDriftFromConfirmed is the false-success
|
||||
// regression the whole verification mechanism exists to catch: a passed
|
||||
// health probe alone must never be worded as a confirmed version.
|
||||
func TestReportEventDistinguishesDriftFromConfirmed(t *testing.T) {
|
||||
report := Report{
|
||||
HealthCheck: "passed",
|
||||
Previous: map[string]string{ComponentDaemon: "1.0.0"},
|
||||
Installed: map[string]string{ComponentDaemon: "1.1.0"},
|
||||
}
|
||||
|
||||
drifted := ReportEvent(report, map[string]string{ComponentDaemon: "1.0.0"})
|
||||
if drifted.Kind != events.KindUpdateReport {
|
||||
t.Fatalf("kind = %q, want %q", drifted.Kind, events.KindUpdateReport)
|
||||
}
|
||||
if !strings.Contains(drifted.Detail, "did NOT take effect") {
|
||||
t.Errorf("summary = %q, want it to flag drift rather than claim success", drifted.Detail)
|
||||
}
|
||||
if strings.Contains(drifted.Detail, "confirmed running") {
|
||||
t.Errorf("summary = %q, must not claim confirmed running when drift was detected", drifted.Detail)
|
||||
}
|
||||
|
||||
confirmed := ReportEvent(report, map[string]string{ComponentDaemon: "1.1.0"})
|
||||
if !strings.Contains(confirmed.Detail, "confirmed running") {
|
||||
t.Errorf("summary = %q, want it to confirm the running version", confirmed.Detail)
|
||||
}
|
||||
ids, _ := confirmed.Data["confirmed"].([]string)
|
||||
if len(ids) != 1 || ids[0] != ComponentDaemon {
|
||||
t.Errorf("confirmed = %#v, want [%q]", confirmed.Data["confirmed"], ComponentDaemon)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReportEventRolledBackIsNeverWordedAsSuccess.
|
||||
func TestReportEventRolledBackIsNeverWordedAsSuccess(t *testing.T) {
|
||||
report := Report{
|
||||
HealthCheck: "failed",
|
||||
RolledBack: true,
|
||||
Previous: map[string]string{ComponentDaemon: "1.0.0"},
|
||||
Installed: map[string]string{ComponentDaemon: "1.1.0"},
|
||||
}
|
||||
|
||||
e := ReportEvent(report, map[string]string{ComponentDaemon: "1.0.0"})
|
||||
if !strings.Contains(e.Detail, "rolled back") {
|
||||
t.Errorf("summary = %q, want it to report the rollback", e.Detail)
|
||||
}
|
||||
if e.Data["rolled_back"] != true {
|
||||
t.Errorf("rolled_back = %v, want true", e.Data["rolled_back"])
|
||||
}
|
||||
}
|
||||
@@ -1,365 +0,0 @@
|
||||
package releaseupdate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/installtype"
|
||||
)
|
||||
|
||||
func TestServiceDefersOnlyTheVersionsShownToThatRecipient(t *testing.T) {
|
||||
catalog := &catalogStub{snapshot: Snapshot{Components: []Component{
|
||||
{ID: "gateway", Label: "THE GATEWAY", Installed: "v0.1.0", Available: "v0.1.1", Changelog: "- Clearer help"},
|
||||
{ID: "runtime", Label: "THE RUNTIME", Installed: "v0.1.0"},
|
||||
}}}
|
||||
service := Service{Catalog: catalog, StatePath: filepath.Join(t.TempDir(), "deferrals.json")}
|
||||
|
||||
first, err := service.Check(context.Background(), 42)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := len(first.Available()); got != 1 {
|
||||
t.Fatalf("available before defer = %d, want 1", got)
|
||||
}
|
||||
if err := service.Defer(context.Background(), 42, first); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
deferred, err := service.Check(context.Background(), 42)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := len(deferred.Available()); got != 0 {
|
||||
t.Fatalf("available after defer = %d, want 0", got)
|
||||
}
|
||||
if !deferred.Deferred {
|
||||
t.Error("Deferred = false, want true")
|
||||
}
|
||||
|
||||
catalog.snapshot.Components[0].Available = "v0.1.2"
|
||||
newer, err := service.Check(context.Background(), 42)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := len(newer.Available()); got != 1 {
|
||||
t.Fatalf("available for newer version = %d, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestServiceCheckNeverDeferredEmptyAvailable pins the empty-Available
|
||||
// combination: for a recipient who has never deferred a component (or a
|
||||
// component absent from the deferral map), deferred[component.ID] is the
|
||||
// empty string, and a component with no available update also has an empty
|
||||
// Available. "" == "" must not read as a deferral -- that tells an
|
||||
// up-to-date recipient their update is "deferred".
|
||||
func TestServiceCheckNeverDeferredEmptyAvailable(t *testing.T) {
|
||||
catalog := &catalogStub{snapshot: Snapshot{Components: []Component{
|
||||
{ID: ComponentDaemon, Label: "Gateway", Installed: "1.0.0", Available: ""},
|
||||
}}}
|
||||
service := Service{Catalog: catalog, StatePath: filepath.Join(t.TempDir(), "deferrals.json")}
|
||||
|
||||
snapshot, err := service.Check(context.Background(), 42)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if snapshot.Deferred {
|
||||
t.Error("Deferred = true for a never-deferred recipient with no available update")
|
||||
}
|
||||
if got := snapshot.Components[0].Available; got != "" {
|
||||
t.Errorf("Available = %q, want empty", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestServiceCheckEnrichesInstallTypeAndReference is the regression proof
|
||||
// for archie-core-1786751948782-3-837a8fd0 point 4: the external check
|
||||
// command reports what version exists, not how this instance was actually
|
||||
// deployed, so Service.Check must fill in InstallType/Reference from Enrich
|
||||
// rather than leaving every component's deployment shape unknown forever.
|
||||
func TestServiceCheckEnrichesInstallTypeAndReference(t *testing.T) {
|
||||
catalog := &catalogStub{snapshot: Snapshot{Components: []Component{
|
||||
{ID: ComponentDaemon, Label: "Gateway", Installed: "1.0.0"},
|
||||
{ID: ComponentNATS, Label: "NATS", Installed: "n/a"},
|
||||
}}}
|
||||
service := Service{Catalog: catalog, Enrich: func(id string) (string, string) {
|
||||
switch id {
|
||||
case ComponentDaemon:
|
||||
return "binary", ""
|
||||
case ComponentNATS:
|
||||
return "external", "nats://nats.internal:4222"
|
||||
default:
|
||||
return "", ""
|
||||
}
|
||||
}}
|
||||
|
||||
snapshot, err := service.Check(context.Background(), 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := snapshot.Components[0]; got.InstallType != "binary" || got.Reference != "" {
|
||||
t.Errorf("daemon component = %+v, want InstallType=binary, Reference=\"\"", got)
|
||||
}
|
||||
if got := snapshot.Components[1]; got.InstallType != "external" || got.Reference != "nats://nats.internal:4222" {
|
||||
t.Errorf("nats component = %+v, want InstallType=external, Reference=nats://nats.internal:4222", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestServiceCheckEnrichLeavesUnrecognisedComponentsUntouched: a component
|
||||
// ID Enrich has no source for (an operator's check command reporting
|
||||
// something this process cannot describe) must not have its InstallType
|
||||
// silently set to empty over whatever, if anything, the check command
|
||||
// itself already reported.
|
||||
func TestServiceCheckEnrichLeavesUnrecognisedComponentsUntouched(t *testing.T) {
|
||||
catalog := &catalogStub{snapshot: Snapshot{Components: []Component{
|
||||
{ID: "third-party-tool", Label: "Tool", Installed: "1.0.0", InstallType: "reported-by-check-command"},
|
||||
}}}
|
||||
service := Service{Catalog: catalog, Enrich: func(string) (string, string) { return "", "" }}
|
||||
|
||||
snapshot, err := service.Check(context.Background(), 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := snapshot.Components[0].InstallType; got != "reported-by-check-command" {
|
||||
t.Errorf("InstallType = %q, want the check command's own value untouched", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceCheckWithNilEnrichLeavesComponentsUnchanged(t *testing.T) {
|
||||
catalog := &catalogStub{snapshot: Snapshot{Components: []Component{
|
||||
{ID: ComponentDaemon, Installed: "1.0.0"},
|
||||
}}}
|
||||
service := Service{Catalog: catalog}
|
||||
|
||||
snapshot, err := service.Check(context.Background(), 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := snapshot.Components[0].InstallType; got != "" {
|
||||
t.Errorf("InstallType = %q, want empty with no Enrich configured", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceInstallForwardsProgressAndFailure(t *testing.T) {
|
||||
installer := &installerStub{}
|
||||
service := Service{Installer: installer, InstallType: "binary"}
|
||||
var progress []string
|
||||
meta := InstallMeta{Channel: "telegram", ChatID: 42}
|
||||
snapshot := Snapshot{Components: []Component{{ID: ComponentDaemon, Installed: "1.0.0", Available: "1.1.0"}}}
|
||||
result, err := service.Install(context.Background(), snapshot, meta, func(message string) { progress = append(progress, message) })
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !installer.called {
|
||||
t.Error("installer was not called")
|
||||
}
|
||||
if installer.gotMeta != meta {
|
||||
t.Errorf("installer received meta = %#v, want %#v", installer.gotMeta, meta)
|
||||
}
|
||||
if !SameAvailable(installer.gotSnapshot, snapshot) {
|
||||
t.Errorf("installer received snapshot = %#v, want %#v", installer.gotSnapshot, snapshot)
|
||||
}
|
||||
if len(progress) != 1 || progress[0] != "Pulling release..." {
|
||||
t.Errorf("progress = %#v", progress)
|
||||
}
|
||||
if result.Installed["daemon"] != "1.1.0" {
|
||||
t.Errorf("result = %#v", result)
|
||||
}
|
||||
}
|
||||
|
||||
// TestServiceInstallRefusesAnUnknownInstallType is the fail-closed guarantee
|
||||
// that makes InstallType worth having: a binary the release pipeline never
|
||||
// stamped (or a caller that never wired InstallType at all) must not run
|
||||
// whatever install command happens to be configured -- there is no way to
|
||||
// know, at that point, whether it is even the right kind of update for how
|
||||
// this instance was actually deployed.
|
||||
func TestServiceInstallRefusesAnUnknownInstallType(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
installType string
|
||||
}{
|
||||
{"unset InstallType", ""},
|
||||
{"explicit unknown", installtype.Unknown},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
installer := &installerStub{}
|
||||
service := Service{Installer: installer, InstallType: tt.installType}
|
||||
|
||||
_, err := service.Install(context.Background(), Snapshot{}, InstallMeta{}, func(string) {})
|
||||
|
||||
if err == nil {
|
||||
t.Fatal("Install() returned nil error, want a refusal")
|
||||
}
|
||||
if installer.called {
|
||||
t.Error("installer was called despite an unknown install type")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestServiceInstallSurvivesCallerContextCancellation: the caller's context
|
||||
// belongs to the request/handler that triggered the update (a Telegram
|
||||
// message handler cancelled by /restart, or an HTTP request cancelled by a
|
||||
// client disconnect) -- it must not reach into the install child process.
|
||||
// Killing that process mid-run can leave binaries half-overwritten with no
|
||||
// rollback ever attempted, which is exactly the failure mode this feature
|
||||
// exists to prevent.
|
||||
func TestServiceInstallSurvivesCallerContextCancellation(t *testing.T) {
|
||||
installer := newBlockingInstallerStub()
|
||||
service := Service{Installer: installer, InstallType: "binary"}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := service.Install(ctx, Snapshot{}, InstallMeta{}, func(string) {})
|
||||
done <- err
|
||||
}()
|
||||
|
||||
<-installer.started
|
||||
cancel() // simulate the triggering request/handler being torn down mid-install
|
||||
|
||||
// The installer must not observe cancellation. Assert it synchronously:
|
||||
// the stub records cancellation by closing a channel, and a channel that
|
||||
// nothing has closed is not ready. No sleep -- a 50ms guess is both a
|
||||
// flake and a weaker check than asking the channel directly.
|
||||
select {
|
||||
case <-installer.gotCancelled:
|
||||
t.Fatal("installer observed its context as cancelled after only the caller's context was cancelled")
|
||||
default:
|
||||
}
|
||||
close(installer.unblock)
|
||||
|
||||
if err := <-done; err != nil {
|
||||
t.Fatalf("Install() error = %v, want nil", err)
|
||||
}
|
||||
// After Install returns, the detached context is released, so the
|
||||
// cancellation observer must have fired. This is the positive half: the
|
||||
// check above is only meaningful if the channel can close at all.
|
||||
select {
|
||||
case <-installer.gotCancelled:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("installer never observed cancellation after Install returned")
|
||||
}
|
||||
}
|
||||
|
||||
// TestServiceInstallRefusesConcurrentInstalls: Telegram and the web
|
||||
// dashboard are two different callers of the same Service, each with its
|
||||
// own local "already in progress" flag -- neither knows about the other.
|
||||
// The authoritative guard against two installs racing the same binaries
|
||||
// and .prev backups has to live here, not duplicated per caller.
|
||||
func TestServiceInstallRefusesConcurrentInstalls(t *testing.T) {
|
||||
installer := newBlockingInstallerStub()
|
||||
service := Service{Installer: installer, InstallType: "binary"}
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := service.Install(context.Background(), Snapshot{}, InstallMeta{}, func(string) {})
|
||||
done <- err
|
||||
}()
|
||||
<-installer.started
|
||||
|
||||
if _, err := service.Install(context.Background(), Snapshot{}, InstallMeta{}, func(string) {}); !errors.Is(err, ErrInstallInProgress) {
|
||||
t.Fatalf("second Install() error = %v, want ErrInstallInProgress", err)
|
||||
}
|
||||
|
||||
close(installer.unblock)
|
||||
if err := <-done; err != nil {
|
||||
t.Fatalf("first Install() error = %v, want nil", err)
|
||||
}
|
||||
if installer.calls != 1 {
|
||||
t.Fatalf("installer.calls = %d, want exactly 1", installer.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNilServiceReturnsConfigurationErrors(t *testing.T) {
|
||||
var service *Service
|
||||
|
||||
if _, err := service.Check(context.Background(), 0); err == nil {
|
||||
t.Fatal("nil service check returned nil error")
|
||||
}
|
||||
if err := service.Defer(context.Background(), 0, Snapshot{}); err == nil {
|
||||
t.Fatal("nil service defer returned nil error")
|
||||
}
|
||||
if _, err := service.Install(context.Background(), Snapshot{}, InstallMeta{}, nil); err == nil {
|
||||
t.Fatal("nil service install returned nil error")
|
||||
}
|
||||
if service.CanInstall() {
|
||||
t.Fatal("nil service reports that installation is available")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatSnapshotReportsAvailableAndUnchangedComponents(t *testing.T) {
|
||||
got := FormatSnapshot(Snapshot{Components: []Component{
|
||||
{Label: "THE GATEWAY", Installed: "v1", Available: "v2", Changelog: "- safer updates"},
|
||||
{Label: "THE RUNTIME", Installed: "v1"},
|
||||
}})
|
||||
for _, want := range []string{"Archie has an update available", "v2 available", "safer updates", "No runtime changes"} {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Errorf("formatted snapshot missing %q: %s", want, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSameAvailableIgnoresMetadataAndDetectsVersionChanges(t *testing.T) {
|
||||
left := Snapshot{Components: []Component{{ID: "gateway", Installed: "v1", Available: "v2", Changelog: "old"}}}
|
||||
right := Snapshot{Components: []Component{{ID: "gateway", Installed: "v1", Available: "v2", Changelog: "new"}}}
|
||||
if !SameAvailable(left, right) {
|
||||
t.Fatal("matching available versions should be equal")
|
||||
}
|
||||
right.Components[0].Available = "v3"
|
||||
if SameAvailable(left, right) {
|
||||
t.Fatal("changed available versions should not be equal")
|
||||
}
|
||||
}
|
||||
|
||||
type catalogStub struct{ snapshot Snapshot }
|
||||
|
||||
func (s *catalogStub) Check(context.Context) (Snapshot, error) { return s.snapshot, nil }
|
||||
|
||||
// blockingInstallerStub lets a test hold Install() open until it chooses to
|
||||
// release it, and records whether the context it was given ever reported
|
||||
// cancellation. gotCancelled is built by the constructor, never lazily inside
|
||||
// Install: Install runs on the caller's goroutine while the test reads the
|
||||
// field, so assigning it there is a data race (found by -race).
|
||||
type blockingInstallerStub struct {
|
||||
unblock chan struct{}
|
||||
started chan struct{}
|
||||
gotCancelled chan struct{}
|
||||
calls int
|
||||
}
|
||||
|
||||
func newBlockingInstallerStub() *blockingInstallerStub {
|
||||
return &blockingInstallerStub{
|
||||
unblock: make(chan struct{}),
|
||||
started: make(chan struct{}),
|
||||
gotCancelled: make(chan struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *blockingInstallerStub) Install(ctx context.Context, _ Snapshot, _ InstallMeta, _ func(string)) (Result, error) {
|
||||
s.calls++
|
||||
close(s.started)
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
close(s.gotCancelled)
|
||||
}()
|
||||
<-s.unblock
|
||||
return Result{}, nil
|
||||
}
|
||||
|
||||
type installerStub struct {
|
||||
called bool
|
||||
gotMeta InstallMeta
|
||||
gotSnapshot Snapshot
|
||||
}
|
||||
|
||||
func (s *installerStub) Install(_ context.Context, snapshot Snapshot, meta InstallMeta, progress func(string)) (Result, error) {
|
||||
s.called = true
|
||||
s.gotMeta = meta
|
||||
s.gotSnapshot = snapshot
|
||||
progress("Pulling release...")
|
||||
return Result{Installed: map[string]string{"daemon": "1.1.0"}}, nil
|
||||
}
|
||||
@@ -1,237 +0,0 @@
|
||||
package releaseupdate_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/releaseupdate"
|
||||
)
|
||||
|
||||
const (
|
||||
daemon = releaseupdate.ComponentDaemon
|
||||
agent = releaseupdate.ComponentAgent
|
||||
)
|
||||
|
||||
// TestVerifyDetectsDrift covers the false-success bug this
|
||||
// verification exists for: an installer reports a version it never actually
|
||||
// managed to put into service, and nothing contradicts it because the health
|
||||
// check only proves *a* daemon is answering -- possibly the old one.
|
||||
func TestVerifyDetectsDrift(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
previous map[string]string
|
||||
installed map[string]string
|
||||
running map[string]string
|
||||
want []releaseupdate.VersionDrift
|
||||
}{
|
||||
{
|
||||
name: "claim matches running",
|
||||
installed: map[string]string{daemon: "1.9.0"},
|
||||
running: map[string]string{daemon: "1.9.0"},
|
||||
want: nil,
|
||||
},
|
||||
{
|
||||
name: "claim contradicted by the version it replaced",
|
||||
previous: map[string]string{daemon: "1.9.8"},
|
||||
installed: map[string]string{daemon: "1.9.0"},
|
||||
running: map[string]string{daemon: "1.9.8"},
|
||||
want: []releaseupdate.VersionDrift{
|
||||
{ID: daemon, Claimed: "1.9.0", Running: "1.9.8", RunningIsPrevious: true},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "running is neither installed nor previous",
|
||||
previous: map[string]string{daemon: "1.9.8"},
|
||||
installed: map[string]string{daemon: "1.9.0"},
|
||||
running: map[string]string{daemon: "1.2.3"},
|
||||
want: []releaseupdate.VersionDrift{
|
||||
{ID: daemon, Claimed: "1.9.0", Running: "1.2.3", RunningIsPrevious: false},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "unknown previous cannot make running the previous version",
|
||||
previous: map[string]string{daemon: releaseupdate.VersionUnknown},
|
||||
installed: map[string]string{daemon: "1.9.0"},
|
||||
running: map[string]string{daemon: "1.9.8"},
|
||||
want: []releaseupdate.VersionDrift{
|
||||
{ID: daemon, Claimed: "1.9.0", Running: "1.9.8", RunningIsPrevious: false},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "component with no running version is unverifiable, not wrong",
|
||||
installed: map[string]string{daemon: "1.9.0", agent: "1.9.0"},
|
||||
running: map[string]string{daemon: "1.9.0"},
|
||||
want: nil,
|
||||
},
|
||||
{
|
||||
name: "empty running version is unverifiable, not wrong",
|
||||
installed: map[string]string{daemon: "1.9.0"},
|
||||
running: map[string]string{daemon: ""},
|
||||
want: nil,
|
||||
},
|
||||
{
|
||||
name: "unknown running version is unverifiable, not wrong",
|
||||
installed: map[string]string{daemon: "1.9.0"},
|
||||
running: map[string]string{daemon: releaseupdate.VersionUnknown},
|
||||
want: nil,
|
||||
},
|
||||
{
|
||||
name: "unknown claim asserts nothing to contradict",
|
||||
installed: map[string]string{daemon: releaseupdate.VersionUnknown},
|
||||
running: map[string]string{daemon: "1.9.8"},
|
||||
want: nil,
|
||||
},
|
||||
{
|
||||
name: "empty claim asserts nothing to contradict",
|
||||
installed: map[string]string{daemon: ""},
|
||||
running: map[string]string{daemon: "1.9.8"},
|
||||
want: nil,
|
||||
},
|
||||
{
|
||||
name: "nothing running verifies nothing",
|
||||
installed: map[string]string{daemon: "1.9.0"},
|
||||
running: nil,
|
||||
want: nil,
|
||||
},
|
||||
{
|
||||
name: "an unstamped running build is unverifiable, not wrong",
|
||||
installed: map[string]string{daemon: "1.9.0"},
|
||||
running: map[string]string{daemon: releaseupdate.VersionDev},
|
||||
want: nil,
|
||||
},
|
||||
{
|
||||
name: "an unstamped claim asserts nothing to contradict",
|
||||
installed: map[string]string{daemon: releaseupdate.VersionDev},
|
||||
running: map[string]string{daemon: "1.9.0"},
|
||||
want: nil,
|
||||
},
|
||||
{
|
||||
name: "an upper-case tag prefix does not manufacture drift",
|
||||
installed: map[string]string{daemon: "V1.9.0"},
|
||||
running: map[string]string{daemon: "1.9.0"},
|
||||
want: nil,
|
||||
},
|
||||
{
|
||||
name: "a tag-shaped claim matches the stamped version it names",
|
||||
installed: map[string]string{daemon: "v1.9.0"},
|
||||
running: map[string]string{daemon: "1.9.0"},
|
||||
want: nil,
|
||||
},
|
||||
{
|
||||
name: "surrounding whitespace does not manufacture drift",
|
||||
installed: map[string]string{daemon: " 1.9.0\n"},
|
||||
running: map[string]string{daemon: "1.9.0"},
|
||||
want: nil,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
report := releaseupdate.Report{Previous: test.previous, Installed: test.installed}
|
||||
got := report.Verify(test.running).Drift
|
||||
if len(got) != len(test.want) {
|
||||
t.Fatalf("Verify().Drift = %#v, want %#v", got, test.want)
|
||||
}
|
||||
for i := range test.want {
|
||||
if got[i] != test.want[i] {
|
||||
t.Errorf("Verify().Drift[%d] = %#v, want %#v", i, got[i], test.want[i])
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestVerifyPartitionsEveryClaim proves each claimed component lands in
|
||||
// exactly one of Confirmed/Drift/Unverified. Callers word their message from
|
||||
// which set is non-empty, so a component silently falling into none of them
|
||||
// (or into two) is what would let an unchecked claim be reported as a
|
||||
// checked one.
|
||||
func TestVerifyPartitionsEveryClaim(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
claimed string
|
||||
running string
|
||||
wantConfirmed bool
|
||||
wantDrift bool
|
||||
wantUnverified bool
|
||||
}{
|
||||
{name: "agreeing versions confirm", claimed: "1.9.0", running: "1.9.0", wantConfirmed: true},
|
||||
{name: "disagreeing versions drift", claimed: "1.9.0", running: "1.9.8", wantDrift: true},
|
||||
{name: "unrecorded claim is unverified", claimed: releaseupdate.VersionUnknown, running: "1.9.8", wantUnverified: true},
|
||||
{name: "unstamped runner is unverified", claimed: "1.9.0", running: releaseupdate.VersionDev, wantUnverified: true},
|
||||
{name: "absent runner is unverified", claimed: "1.9.0", running: "", wantUnverified: true},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
report := releaseupdate.Report{Installed: map[string]string{daemon: test.claimed}}
|
||||
got := report.Verify(map[string]string{daemon: test.running})
|
||||
|
||||
total := len(got.Confirmed) + len(got.Drift) + len(got.Unverified)
|
||||
if total != 1 {
|
||||
t.Fatalf("claim landed in %d sets, want exactly 1: %#v", total, got)
|
||||
}
|
||||
if (len(got.Confirmed) == 1) != test.wantConfirmed {
|
||||
t.Errorf("Confirmed = %v, want confirmed=%v", got.Confirmed, test.wantConfirmed)
|
||||
}
|
||||
if (len(got.Drift) == 1) != test.wantDrift {
|
||||
t.Errorf("Drift = %#v, want drift=%v", got.Drift, test.wantDrift)
|
||||
}
|
||||
if (len(got.Unverified) == 1) != test.wantUnverified {
|
||||
t.Errorf("Unverified = %v, want unverified=%v", got.Unverified, test.wantUnverified)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestVerifyIgnoresUnclaimedRunningComponents proves a component
|
||||
// that is running but was never part of the update is not treated as drift:
|
||||
// the claim set is what is under test, not the inventory.
|
||||
func TestVerifyIgnoresUnclaimedRunningComponents(t *testing.T) {
|
||||
report := releaseupdate.Report{Installed: map[string]string{daemon: "1.9.0"}}
|
||||
running := map[string]string{daemon: "1.9.0", agent: "0.0.1"}
|
||||
|
||||
if got := report.Verify(running).Drift; len(got) != 0 {
|
||||
t.Fatalf("Verify().Drift = %#v, want no drift", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestVerifyOrdersDriftStably guards the sort, which callers rely on
|
||||
// to render a stable message.
|
||||
//
|
||||
// The component count is load-bearing and is NOT about permutations. Go
|
||||
// randomizes a small map's iteration start offset rather than its order, so
|
||||
// up to 8 keys in one bucket come out as a rotation -- an unsorted
|
||||
// implementation still emits sorted output about 1/n of the time, not 1/n!.
|
||||
// Measured against this code with the sort removed: 2 components pass 87% of
|
||||
// the time and 8 pass 12%, while 9 crosses into bucket-order randomization
|
||||
// and passes 0 times in 200,000. Nine is therefore the first count that
|
||||
// fails an unsorted implementation on a single attempt; the repeats are
|
||||
// belt-and-braces. Do not reduce either number.
|
||||
func TestVerifyOrdersDriftStably(t *testing.T) {
|
||||
const components = 9
|
||||
installed := make(map[string]string, components)
|
||||
running := make(map[string]string, components)
|
||||
want := make([]string, 0, components)
|
||||
for i := range components {
|
||||
id := fmt.Sprintf("component-%d", i)
|
||||
installed[id] = "2.0.0"
|
||||
running[id] = "1.0.0"
|
||||
want = append(want, id)
|
||||
}
|
||||
sort.Strings(want)
|
||||
report := releaseupdate.Report{Installed: installed}
|
||||
|
||||
for attempt := range 25 {
|
||||
drift := report.Verify(running).Drift
|
||||
if len(drift) != components {
|
||||
t.Fatalf("attempt %d: Verify().Drift returned %d drifts, want %d", attempt, len(drift), components)
|
||||
}
|
||||
for i, id := range want {
|
||||
if drift[i].ID != id {
|
||||
t.Fatalf("attempt %d: drift[%d].ID = %q, want %q (order is not stable)", attempt, i, drift[i].ID, id)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user