feat(archied): recovery commands on PostgreSQL; fail-closed pre-update snapshot, no automatic schema rollback
Without -db, backup/restore/validate/rollback resolve database_url from the config and work on the whole PostgreSQL database. Restore claims every service role; rollback claims the State Store role; validate refuses a schema newer than the binary. The installer refuses a daemon update it cannot snapshot first; the watchdog never restores the database and prints the explicit offline restore instead.
This commit is contained in:
1 parent
b39f7c682f
commit
fe819d489a
11 files changed
+588
-48
No files matched your search
@@ -5,12 +5,12 @@
|
||||
// State Store is up -- is unavailable in exactly the case that needs it
|
||||
// (docs/architecture/safe-change-and-recovery.md).
|
||||
//
|
||||
// Every operation works on the task database file directly, with the State
|
||||
// Store stopped, and the ones that write refuse when another process owns the
|
||||
// file. Backup is the exception and deliberately so: the update installer
|
||||
// cannot stop the process that runs it, so the snapshot that makes a failed
|
||||
// update reversible is taken against a serving store through SQLite's own
|
||||
// consistent copy.
|
||||
// With -db an operation works on the legacy SQLite task file; without it, on
|
||||
// the PostgreSQL database database_url names (state_store_recovery_postgres.go).
|
||||
// The ones that write refuse while a serving process owns the store. Backup is
|
||||
// the exception and deliberately so: the update installer cannot stop the
|
||||
// process that runs it, so the snapshot that makes a failed update recoverable
|
||||
// is taken against a serving store through a consistent copy.
|
||||
//
|
||||
// The control-plane server both validate and rollback read through is built by
|
||||
// openStateStoreControlPlane -- the same root helper the served path uses -- so
|
||||
@@ -25,6 +25,7 @@ import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/app/controlplane"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
|
||||
@@ -76,31 +77,33 @@ type StateStoreRecoveryOptions struct {
|
||||
// RunStateStoreRecovery performs one offline operation on the task database and
|
||||
// returns the line the command reports on stdout.
|
||||
func RunStateStoreRecovery(ctx context.Context, options StateStoreRecoveryOptions) (string, error) {
|
||||
// -db names the legacy SQLite task file; without it the command works on
|
||||
// the PostgreSQL database the configuration names.
|
||||
if options.DB == "" {
|
||||
return runPostgresRecovery(ctx, options)
|
||||
}
|
||||
switch options.Operation {
|
||||
case RecoveryBackup:
|
||||
if options.DB == "" || options.Out == "" {
|
||||
return "", errors.New("backup requires -db and -out")
|
||||
if options.Out == "" {
|
||||
return "", errors.New("backup requires -out")
|
||||
}
|
||||
if err := store.Backup(ctx, options.DB, options.Out); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return fmt.Sprintf("backed up %s to %s", options.DB, options.Out), nil
|
||||
case RecoveryRestore:
|
||||
if options.DB == "" || options.From == "" {
|
||||
return "", errors.New("restore requires -db and -from")
|
||||
if options.From == "" {
|
||||
return "", errors.New("restore requires -from")
|
||||
}
|
||||
if err := store.Restore(ctx, options.DB, options.From); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return fmt.Sprintf("restored %s from %s; start the State Store again", options.DB, options.From), nil
|
||||
case RecoveryValidate:
|
||||
if options.DB == "" {
|
||||
return "", errors.New("validate requires -db")
|
||||
}
|
||||
return validateStore(ctx, options)
|
||||
case RecoveryRollback:
|
||||
if options.DB == "" || options.Kind == "" {
|
||||
return "", errors.New("rollback requires -db and -kind")
|
||||
if options.Kind == "" {
|
||||
return "", errors.New("rollback requires -kind")
|
||||
}
|
||||
return rollbackResource(ctx, options)
|
||||
default:
|
||||
@@ -146,34 +149,45 @@ func validateStore(ctx context.Context, options StateStoreRecoveryOptions) (stri
|
||||
// with the writer's validator, and boot's gate is the config check alone.
|
||||
// That is the same stance the layering takes for a kind the table is missing:
|
||||
// what the daemon reads for a kind nothing was ever stored for is the seed.
|
||||
checked := 0
|
||||
stored, err := st.StoresResources(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if stored {
|
||||
if checked, err = server.ValidateStored(ctx); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
|
||||
base, err := bootConfig(ctx, options)
|
||||
checked, err := checkBootGate(ctx, server, stored, options)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return fmt.Sprintf("%s is a valid store at schema version %d; %d stored resources validate", options.DB, version, checked), nil
|
||||
}
|
||||
|
||||
// checkBootGate runs the writer's per-resource validation over what is stored,
|
||||
// then boot's gate over the file config with the stored resources layered on,
|
||||
// and returns how many stored resources validated.
|
||||
func checkBootGate(ctx context.Context, server *controlplane.Server, stored bool, options StateStoreRecoveryOptions) (int, error) {
|
||||
checked := 0
|
||||
if stored {
|
||||
var err error
|
||||
if checked, err = server.ValidateStored(ctx); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
base, err := bootConfig(ctx, options)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
document := base
|
||||
if stored {
|
||||
document, _, err = server.StoredRuntimeConfig(ctx, base)
|
||||
if err != nil {
|
||||
return "", err
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
if err := configuration.Validate(&document); err != nil {
|
||||
// The daemon's own wording, so an operator can match this failure to the
|
||||
// one that stopped archied starting.
|
||||
return "", fmt.Errorf("validate database settings: %w", err)
|
||||
return 0, fmt.Errorf("validate database settings: %w", err)
|
||||
}
|
||||
return fmt.Sprintf("%s is a valid store at schema version %d; %d stored resources validate", options.DB, version, checked), nil
|
||||
return checked, nil
|
||||
}
|
||||
|
||||
// bootConfig resolves the configuration the daemon would boot with. validate is
|
||||
@@ -217,22 +231,27 @@ func rollbackResource(ctx context.Context, options StateStoreRecoveryOptions) (s
|
||||
return "", err
|
||||
}
|
||||
defer func() { _ = st.Close() }()
|
||||
return replayRevision(ctx, st, options)
|
||||
}
|
||||
|
||||
server, err := openStateStoreControlPlane(st)
|
||||
// replayRevision puts back the revision options names through the control
|
||||
// plane's ordinary replace. The caller holds the store's ownership claim.
|
||||
func replayRevision(ctx context.Context, resources controlplane.ResourceStore, options StateStoreRecoveryOptions) (string, error) {
|
||||
server, err := openStateStoreControlPlane(resources)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !server.Owns(options.Kind) {
|
||||
return "", fmt.Errorf("unknown resource kind %q", options.Kind)
|
||||
}
|
||||
current, err := st.Resource(ctx, options.Kind)
|
||||
current, err := resources.Resource(ctx, options.Kind)
|
||||
if errors.Is(err, store.ErrResourceNotFound) {
|
||||
return "", fmt.Errorf("%s has no stored value to roll back", options.Kind)
|
||||
}
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read %s: %w", options.Kind, err)
|
||||
}
|
||||
revision, err := revisionToReplay(ctx, st, options.Kind, current.Version, options.Revision)
|
||||
revision, err := revisionToReplay(ctx, resources, options.Kind, current.Version, options.Revision)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -254,7 +273,7 @@ func rollbackResource(ctx context.Context, options StateStoreRecoveryOptions) (s
|
||||
|
||||
// revisionToReplay picks the value to put back: the revision the operator
|
||||
// named, or the newest one older than the value the resource carries now.
|
||||
func revisionToReplay(ctx context.Context, st *store.Store, kind string, current, requested int64) (store.Resource, error) {
|
||||
func revisionToReplay(ctx context.Context, st controlplane.ResourceStore, kind string, current, requested int64) (store.Resource, error) {
|
||||
history, err := st.ResourceHistory(ctx, kind, 0)
|
||||
if err != nil {
|
||||
return store.Resource{}, fmt.Errorf("read %s history: %w", kind, err)
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
)
|
||||
|
||||
// runPostgresRecovery performs one recovery operation on the PostgreSQL
|
||||
// database the configuration names. There is no automatic schema rollback:
|
||||
// goose Down drops tables, so the way back from a migration is restoring the
|
||||
// snapshot taken before it, which loses every write made after that snapshot.
|
||||
func runPostgresRecovery(ctx context.Context, options StateStoreRecoveryOptions) (string, error) {
|
||||
cfg, err := bootConfig(ctx, options)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
url := cfg.DatabaseURL
|
||||
if url == "" {
|
||||
return "", errors.New("database_url is required: the configuration names no PostgreSQL database (pass -db for a legacy SQLite task file)")
|
||||
}
|
||||
switch options.Operation {
|
||||
case RecoveryBackup:
|
||||
if options.Out == "" {
|
||||
return "", errors.New("backup requires -out")
|
||||
}
|
||||
if err := postgres.Backup(ctx, url, options.Out); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return "backed up the whole database to " + options.Out, nil
|
||||
case RecoveryRestore:
|
||||
if options.From == "" {
|
||||
return "", errors.New("restore requires -from")
|
||||
}
|
||||
if err := postgres.Restore(ctx, url, options.From); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return fmt.Sprintf("restored the whole database from %s; every write made after the snapshot is gone; start the archie services again", options.From), nil
|
||||
case RecoveryValidate:
|
||||
return validatePostgres(ctx, url, options)
|
||||
case RecoveryRollback:
|
||||
if options.Kind == "" {
|
||||
return "", errors.New("rollback requires -kind")
|
||||
}
|
||||
return rollbackPostgres(ctx, url, options)
|
||||
default:
|
||||
return "", fmt.Errorf("unknown recovery command %q", options.Operation)
|
||||
}
|
||||
}
|
||||
|
||||
// openRecoveryPool opens the database without migrating it: recovery inspects
|
||||
// or repairs the schema it finds, and refuses one newer than this binary.
|
||||
func openRecoveryPool(ctx context.Context, url string) (*pgxpool.Pool, int64, error) {
|
||||
pool, err := postgres.Open(ctx, url)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
version, err := postgres.SchemaVersion(ctx, pool)
|
||||
if err == nil {
|
||||
err = postgres.CheckSchemaVersion(version)
|
||||
}
|
||||
if err != nil {
|
||||
pool.Close()
|
||||
return nil, 0, err
|
||||
}
|
||||
return pool, version, nil
|
||||
}
|
||||
|
||||
// validatePostgres is validateStore for the PostgreSQL database. An
|
||||
// unmigrated database holds nothing to check; the State Store migrates and
|
||||
// seeds it on its next start, so only boot's config gate applies.
|
||||
func validatePostgres(ctx context.Context, url string, options StateStoreRecoveryOptions) (string, error) {
|
||||
pool, version, err := openRecoveryPool(ctx, url)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer pool.Close()
|
||||
server, err := openStateStoreControlPlane(postgres.NewResources(pool))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
checked, err := checkBootGate(ctx, server, version > 0, options)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return fmt.Sprintf("the database is valid at schema version %d; %d stored resources validate", version, checked), nil
|
||||
}
|
||||
|
||||
// rollbackPostgres replays an earlier revision holding the State Store's
|
||||
// ownership claim, so it refuses while a State Store serves and none can
|
||||
// start until it finishes.
|
||||
func rollbackPostgres(ctx context.Context, url string, options StateStoreRecoveryOptions) (string, error) {
|
||||
pool, _, err := openRecoveryPool(ctx, url)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer pool.Close()
|
||||
claim, err := postgres.AcquireOwnership(ctx, pool, postgres.OwnerStateStore)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("rollback refused, stop the State Store first: %w", err)
|
||||
}
|
||||
defer func() { _ = claim.Release(context.WithoutCancel(ctx)) }()
|
||||
return replayRevision(ctx, postgres.NewResources(pool), options)
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/app/controlplane"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
)
|
||||
|
||||
// pgRecoveryFixture is a migrated database and the config file naming it,
|
||||
// which is all the Postgres recovery path is given: it resolves database_url
|
||||
// from the configuration exactly as the State Store does.
|
||||
func pgRecoveryFixture(t *testing.T) (configPath string, pool *pgxpool.Pool, url string) {
|
||||
t.Helper()
|
||||
url = pgtest.URL(t)
|
||||
dir := t.TempDir()
|
||||
configPath = filepath.Join(dir, "config.toml")
|
||||
body := fmt.Sprintf("bot_user = 'archie'\ndb_path = %q\ndatabase_url = %q\n[forge]\ntype = 'github'\nhost = 'https://github.example.com'\n",
|
||||
filepath.Join(dir, "archie.db"), url)
|
||||
if err := os.WriteFile(configPath, []byte(body), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pool, err := postgres.Open(t.Context(), url)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(pool.Close)
|
||||
if err := postgres.Migrate(t.Context(), pool, postgres.Migrations()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return configPath, pool, url
|
||||
}
|
||||
|
||||
func requirePGTools(t *testing.T) {
|
||||
t.Helper()
|
||||
for _, tool := range []string{"pg_dump", "pg_restore"} {
|
||||
if _, err := exec.LookPath(tool); err != nil {
|
||||
t.Skipf("%s is not on PATH; this test needs the PostgreSQL 18 client tools", tool)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func putResource(t *testing.T, pool *pgxpool.Pool, kind, value, label string) {
|
||||
t.Helper()
|
||||
resources := postgres.NewResources(pool)
|
||||
expected := int64(0)
|
||||
if current, err := resources.Resource(t.Context(), kind); err == nil {
|
||||
expected = current.Version
|
||||
}
|
||||
if _, err := resources.PutResource(t.Context(), storecontract.ResourceWrite{
|
||||
Kind: kind, Value: []byte(value), Actor: label, Source: "test",
|
||||
RequestID: fmt.Sprintf("%s-%d", label, expected+1), ExpectedVersion: expected,
|
||||
}); err != nil {
|
||||
t.Fatalf("put %s: %v", kind, err)
|
||||
}
|
||||
}
|
||||
|
||||
func holdRole(t *testing.T, url, role string) {
|
||||
t.Helper()
|
||||
pool, err := postgres.Open(t.Context(), url)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(pool.Close)
|
||||
claim, err := postgres.AcquireOwnership(t.Context(), pool, role)
|
||||
if err != nil {
|
||||
t.Fatalf("hold %s: %v", role, err)
|
||||
}
|
||||
t.Cleanup(func() { _ = claim.Release(t.Context()) })
|
||||
}
|
||||
|
||||
func TestPostgresRecoveryRequiresADatabaseURL(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
configPath := filepath.Join(dir, "config.toml")
|
||||
if err := os.WriteFile(configPath, []byte("bot_user = 'archie'\n[forge]\ntype = 'github'\nhost = 'https://github.example.com'\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, op := range []string{RecoveryBackup, RecoveryRestore, RecoveryValidate, RecoveryRollback} {
|
||||
t.Run(op, func(t *testing.T) {
|
||||
_, err := RunStateStoreRecovery(t.Context(), StateStoreRecoveryOptions{
|
||||
Operation: op, Config: configPath, Out: filepath.Join(dir, "o"), From: filepath.Join(dir, "f"), Kind: "k",
|
||||
})
|
||||
if err == nil || !strings.Contains(err.Error(), "database_url") {
|
||||
t.Fatalf("%s without database_url = %v, want a refusal naming database_url", op, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostgresRecoveryBackupAndRestore(t *testing.T) {
|
||||
requirePGTools(t)
|
||||
configPath, pool, url := pgRecoveryFixture(t)
|
||||
putResource(t, pool, controlplane.ModelRoleAssignmentsKind, `{"implement":"anthropic/claude"}`, "snapshot")
|
||||
snapshot := filepath.Join(t.TempDir(), "snapshot.dump")
|
||||
|
||||
if _, err := RunStateStoreRecovery(t.Context(), StateStoreRecoveryOptions{Operation: RecoveryBackup, Config: configPath, Out: snapshot}); err != nil {
|
||||
t.Fatalf("backup: %v", err)
|
||||
}
|
||||
putResource(t, pool, controlplane.ModelRoleAssignmentsKind, `{"implement":"openai/gpt"}`, "later")
|
||||
|
||||
for _, role := range postgres.ServiceOwners {
|
||||
t.Run("refused while "+role+" serves", func(t *testing.T) {
|
||||
holdRole(t, url, role)
|
||||
_, err := RunStateStoreRecovery(t.Context(), StateStoreRecoveryOptions{Operation: RecoveryRestore, Config: configPath, From: snapshot})
|
||||
if !errors.Is(err, postgres.ErrOwned) {
|
||||
t.Fatalf("restore with %s serving = %v, want ErrOwned", role, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
summary, err := RunStateStoreRecovery(t.Context(), StateStoreRecoveryOptions{Operation: RecoveryRestore, Config: configPath, From: snapshot})
|
||||
if err != nil {
|
||||
t.Fatalf("restore: %v", err)
|
||||
}
|
||||
if !strings.Contains(summary, "after the snapshot") {
|
||||
t.Errorf("restore must say writes after the snapshot are lost; summary = %q", summary)
|
||||
}
|
||||
current, err := postgres.NewResources(pool).Resource(t.Context(), controlplane.ModelRoleAssignmentsKind)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if current.Version != 1 {
|
||||
t.Errorf("restored version = %d, want the snapshot's 1", current.Version)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostgresRecoveryValidate(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
setup func(t *testing.T, pool *pgxpool.Pool)
|
||||
wantErr string
|
||||
}{
|
||||
{name: "healthy store", setup: func(*testing.T, *pgxpool.Pool) {}},
|
||||
{name: "schema newer than this binary", wantErr: "newer than this binary", setup: func(t *testing.T, pool *pgxpool.Pool) {
|
||||
if _, err := pool.Exec(t.Context(), "INSERT INTO goose_db_version (version_id, is_applied) VALUES ($1, true)", postgres.SupportedSchemaVersion()+1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}},
|
||||
{name: "stored value boot refuses", wantErr: "dispatch.trigger", setup: func(t *testing.T, pool *pgxpool.Pool) {
|
||||
putResource(t, pool, "scheduling-policy", `{"poll_interval":"1m","max_retries":3,"dispatch":{"trigger":"bogus"}}`, "bad")
|
||||
}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
configPath, pool, _ := pgRecoveryFixture(t)
|
||||
tt.setup(t, pool)
|
||||
summary, err := RunStateStoreRecovery(t.Context(), StateStoreRecoveryOptions{Operation: RecoveryValidate, Config: configPath})
|
||||
if tt.wantErr == "" {
|
||||
if err != nil {
|
||||
t.Fatalf("validate: %v", err)
|
||||
}
|
||||
if !strings.Contains(summary, fmt.Sprintf("schema version %d", postgres.SupportedSchemaVersion())) {
|
||||
t.Errorf("summary = %q, want the schema version", summary)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
|
||||
t.Fatalf("validate = %v, want refusal containing %q", err, tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostgresRecoveryRollback(t *testing.T) {
|
||||
configPath, pool, url := pgRecoveryFixture(t)
|
||||
kind := controlplane.ModelRoleAssignmentsKind
|
||||
putResource(t, pool, kind, `{"implement":"anthropic/claude"}`, "first")
|
||||
putResource(t, pool, kind, `{"implement":"openai/gpt"}`, "second")
|
||||
options := StateStoreRecoveryOptions{Operation: RecoveryRollback, Config: configPath, Kind: kind}
|
||||
|
||||
t.Run("refused while the State Store serves", func(t *testing.T) {
|
||||
holdRole(t, url, postgres.OwnerStateStore)
|
||||
if _, err := RunStateStoreRecovery(t.Context(), options); !errors.Is(err, postgres.ErrOwned) {
|
||||
t.Fatalf("rollback with the State Store serving = %v, want ErrOwned", err)
|
||||
}
|
||||
})
|
||||
|
||||
if _, err := RunStateStoreRecovery(t.Context(), options); err != nil {
|
||||
t.Fatalf("rollback: %v", err)
|
||||
}
|
||||
current, err := postgres.NewResources(pool).Resource(t.Context(), kind)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(current.Value) != `{"implement": "anthropic/claude"}` && string(current.Value) != `{"implement":"anthropic/claude"}` {
|
||||
t.Errorf("value = %s, want the first revision's", current.Value)
|
||||
}
|
||||
if current.Version != 3 {
|
||||
t.Errorf("version = %d, want the rollback recorded as revision 3", current.Version)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -411,6 +411,8 @@ printf '%s\n' "go $*" >> "$ARCHIE_TEST_CALLS"
|
||||
# must refuse the update.
|
||||
if [ "$1" = "run" ]; then
|
||||
[ "${ARCHIE_TEST_GO_FAILS_RUN:-}" = "1" ] && exit 1
|
||||
# The PostgreSQL snapshot is the backup run that names no -db file.
|
||||
[ "${ARCHIE_TEST_GO_FAILS_SNAPSHOT:-}" = "1" ] && [[ " $* " != *" -db "* ]] && exit 1
|
||||
exit 0
|
||||
fi
|
||||
out=""
|
||||
|
||||
Reference in new issue
Block a user