carlos / platform Public

registry: ActivatorOwned and Resident predicates over routes.runtime; rootfs hibernation fixed in Upsert and SetHibernate; ResidentInstances

Rootfs apps plan 3, Task 2. Route.Rootfs, ActivatorOwned, Resident and
ActivatorLeased are the shared predicates. Upsert keeps a rootfs row's
hibernation unless the host is re-tenanted, and its replication arm keys on
the effective runtime, so a resident keeps its rung. SetHibernate refuses a
row with a runtime (ErrRuntimeFixed, carried across the remote registry).
ResidentInstances lists the always-awake rootfs instances the activator may
start. carlos add refuses an existing rootfs host before its Upsert.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev cda4db654ce8da02ad31eb21392be8f722b85577 parent 40c7e25
8 files changed, +552 −10
  • cli.go +16 −0
  • cli_add_rootfs_test.go +80 −0
  • internal/registry/registry.go +74 −9
  • internal/registry/remote.go +1 −1
  • internal/registry/remote_dispatch.go +2 −0
  • internal/registry/remote_test.go +9 −0
  • internal/registry/runtime.go +34 −0
  • internal/registry/runtime_test.go +336 −0
diff --git a/cli.go b/cli.go
index 087bae4d5..a53174ebb 100644
--- a/cli.go
+++ b/cli.go
@@ -66,6 +66,19 @@ func reservedSlugs() map[string]bool {
return out
}
+// refuseAddRootfs stops a re-add of a host whose row runs a rootfs image.
+// Such a row comes from its record: its runtime and hibernation are fixed
+// at mint, and this verb's full-row Upsert would rewrite its socket,
+// database path and flags from box defaults. Checked before
+// refuseAddNested, so a rootfs row at the nested paths gets this reason.
+// A diagnostic (log), not copy.
+func refuseAddRootfs(host string, existing *registry.Route) error {
+ if existing != nil && existing.Runtime != "" {
+ return fmt.Errorf("add %s: the row runs a rootfs image (runtime %q); a rootfs row comes from its record, not this verb. nothing was changed", host, existing.Runtime)
+ }
+ return nil
+}
+
// refuseAddNested stops a re-add of a host whose row is on the nested
// layout. Upsert overwrites the socket, database path and hibernate flag
// with this verb's flat defaults, which would leave the row pointing at
@@ -270,6 +283,9 @@ func runAdd(args []string) {
if err != nil {
log.Fatal(err)
}
+ if err := refuseAddRootfs(host, existing); err != nil {
+ log.Fatalf("%v", err)
+ }
if err := refuseAddNested(host, existing, dataDir()); err != nil {
log.Fatalf("%v", err)
}
diff --git a/cli_add_rootfs_test.go b/cli_add_rootfs_test.go
new file mode 100644
index 000000000..2f7d9a958
--- /dev/null
+++ b/cli_add_rootfs_test.go
@@ -0,0 +1,80 @@
+package main
+
+import (
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// A rootfs row comes from its record: its runtime and hibernation are fixed
+// at mint, and this box verb's full-row Upsert would rewrite its socket,
+// database path and flags. So `carlos add` over an existing rootfs host is
+// refused before any write; a binary row re-adds as it always has.
+func TestAddRefusesAnExistingRootfsHost(t *testing.T) {
+ bin := buildCarlos(t)
+ regPath := filepath.Join(t.TempDir(), "registry.db")
+ scratch := t.TempDir()
+ run := func(args ...string) (string, error) {
+ t.Helper()
+ cmd := exec.Command(bin, args...)
+ cmd.Env = carlosTestEnv(t)
+ // pick() walks cwd ancestors for .carlos/config, so the subprocess must not run from the real checkout.
+ cmd.Dir = scratch
+ out, err := cmd.CombinedOutput()
+ return string(out), err
+ }
+
+ reg, err := registry.Open(regPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer reg.Close()
+
+ const host = "shop.example.com"
+ if err := reg.Upsert(registry.Route{Host: host, Kind: "instance", App: "shop", Account: "ops",
+ Socket: provision.NestedSocket(host), Runtime: registry.RuntimeRootfsV1, Status: "ready"}); err != nil {
+ t.Fatal(err)
+ }
+ before, err := reg.Get(host)
+ if err != nil || before == nil {
+ t.Fatalf("Get before = %+v, %v", before, err)
+ }
+ for _, args := range [][]string{
+ {"add", "-registry", regPath, "-app", "shop", host},
+ {"add", "-registry", regPath, "-app", "shop", "-hibernate", host},
+ } {
+ out, err := run(args...)
+ if err == nil {
+ t.Fatalf("carlos %v over a rootfs row: want non-zero exit, got 0\n%s", args, out)
+ }
+ if !strings.Contains(out, host) || !strings.Contains(out, "rootfs") || !strings.Contains(out, "record") {
+ t.Errorf("refusal does not name the host and the record:\n%s", out)
+ }
+ after, err := reg.Get(host)
+ if err != nil || after == nil {
+ t.Fatalf("Get after = %+v, %v", after, err)
+ }
+ if *after != *before {
+ t.Fatalf("a refused add changed the rootfs row:\n before %+v\n after %+v", *before, *after)
+ }
+ }
+
+ const blog = "blog.example.com"
+ if out, err := run("add", "-registry", regPath, "-app", "blog", blog); err != nil {
+ t.Fatalf("add a binary row: %v\n%s", err, out)
+ }
+ out, err := run("add", "-registry", regPath, "-app", "blog", "-hibernate", blog)
+ if err != nil {
+ t.Fatalf("re-add a binary row: %v\n%s", err, out)
+ }
+ if !strings.Contains(out, "updated") {
+ t.Errorf("re-add of a binary row did not report an update:\n%s", out)
+ }
+ if got, err := reg.Get(blog); err != nil || got == nil || !got.Hibernate || got.Runtime != "" {
+ t.Fatalf("binary row after a re-add = %+v, %v, want it hibernating and binary", got, err)
+ }
+}
diff --git a/internal/registry/registry.go b/internal/registry/registry.go
index e40be77a8..9c7ed3c96 100644
--- a/internal/registry/registry.go
+++ b/internal/registry/registry.go
@@ -1153,7 +1153,15 @@ func (r *Registry) Delete(host string) error {
// because a rung is read only on the activator's wake path and describes
// nothing on a route that no longer sleeps. This statement's own
// `excluded.hibernate = 0` arm is that same rule reaching the full-row
-// callers. See SetHibernate for the whole of it.
+// callers. See SetHibernate for the whole of it. Both clear only a binary
+// row's rung, keyed on the row's effective runtime (the incoming one on a
+// re-tenanted host, else the stored one): a rootfs row's database is the
+// activator's to replicate awake or asleep.
+//
+// `hibernate` is a plain overwrite except on a rootfs row (stored runtime
+// not ""), whose hibernation is fixed at mint like its runtime: the stored
+// value stays unless the host is re-tenanted, which is a new life and takes
+// the incoming value, as `runtime` does.
//
// `addrs` and `health` (multi-upstream routing, issue #152) are, by
// contrast, PLAIN overwrites — see their ON CONFLICT clause below — same as
@@ -1270,14 +1278,16 @@ ON CONFLICT(host) DO UPDATE SET
db_path=excluded.db_path, version=excluded.version,
prev_version=excluded.prev_version, app=excluded.app, pool=excluded.pool,
region=excluded.region, channel=excluded.channel,
- hibernate=excluded.hibernate, canary=excluded.canary,
+ hibernate=CASE WHEN routes.runtime != '' AND NOT (`+tenantChangedSQL+`) THEN routes.hibernate ELSE excluded.hibernate END,
+ canary=excluded.canary,
next_due=excluded.next_due,
backing=excluded.backing, status_named=excluded.status_named,
platform=excluded.platform, dns_status=excluded.dns_status,
dns_checked_at=excluded.dns_checked_at,
cert_expires_at=excluded.cert_expires_at, account=excluded.account,
environment=CASE WHEN excluded.environment = '' THEN routes.environment ELSE excluded.environment END,
- replication=CASE WHEN excluded.hibernate = 0 THEN '' WHEN excluded.replication = '' THEN routes.replication ELSE excluded.replication END,
+ replication=CASE WHEN excluded.hibernate = 0 AND (CASE WHEN `+tenantChangedSQL+` THEN excluded.runtime ELSE routes.runtime END) = '' THEN ''
+ WHEN excluded.replication = '' THEN routes.replication ELSE excluded.replication END,
caps=CASE WHEN excluded.caps = '' THEN routes.caps ELSE excluded.caps END,
tunnel=CASE WHEN excluded.tunnel = '' THEN routes.tunnel ELSE excluded.tunnel END,
provisioned=CASE WHEN excluded.provisioned = 0 THEN routes.provisioned ELSE excluded.provisioned END,
@@ -1334,8 +1344,12 @@ func normalizeRoute(t Route) Route {
// the activator's wake path is its only reader, and box-wide
// /etc/litestream.yml covers every non-hibernating database at its own
// interval — so a stored `daily` would be reported by `carlos routes`
- // while the database was streamed every second. See SetHibernate.
- if !t.Hibernate {
+ // while the database was streamed every second. See SetHibernate. That
+ // holds for a binary row only. A rung means the activator replicates,
+ // and a rootfs row (any non-empty Runtime) keeps its rung awake or
+ // asleep: the activator holds a resident's lease and replication
+ // (Route.Resident).
+ if !t.Hibernate && t.Runtime == "" {
t.Replication = ""
}
// #162's replica invariant, its clean form: a replica SET on a row that
@@ -2715,7 +2729,13 @@ func (r *Registry) SetServingVersion(host, ver string) error {
// and any door added later will too. The third writer, a full-row Upsert
// carrying hibernate=0 (`carlos add` with no --hibernate), is covered by the
// matching arm of that statement's ON CONFLICT clause. Between them the
-// invariant is total: a non-empty `replication` implies a hibernating row.
+// invariant is total: a non-empty `replication` implies a row whose database
+// the activator replicates, a hibernating row or a rootfs one.
+//
+// A row whose Runtime is not "" is refused with ErrRuntimeFixed and nothing
+// changes: a rootfs row's hibernation is fixed when it is minted, like its
+// runtime (spec §5.0), so this door cannot reach it, and neither can the
+// rung-clearing above.
//
// Clearing rather than preserving-for-later is deliberate. A preserved class
// is invisible state that changes behaviour weeks after it was typed, and
@@ -2728,12 +2748,28 @@ func (r *Registry) SetHibernate(host string, on bool) error {
return err
}
+ var res sql.Result
+ var err error
if !on {
- _, err := r.sql.Exec(`UPDATE routes SET hibernate = 0, replication = '' WHERE host = ?`, host)
+ res, err = r.sql.Exec(`UPDATE routes SET hibernate = 0, replication = '' WHERE host = ? AND runtime = ''`, host)
+ } else {
+ res, err = r.sql.Exec(`UPDATE routes SET hibernate = 1 WHERE host = ? AND runtime = ''`, host)
+ }
+ if err != nil {
return err
}
- _, err := r.sql.Exec(`UPDATE routes SET hibernate = 1 WHERE host = ?`, host)
- return err
+ if n, err := res.RowsAffected(); err != nil || n != 0 {
+ return err
+ }
+ // Nothing matched: no row (today's silent no-op), or a rootfs row.
+ rt, err := r.Get(host)
+ if err != nil {
+ return err
+ }
+ if rt != nil && rt.Runtime != "" {
+ return ErrRuntimeFixed
+ }
+ return nil
}
// SetNextDue records the earliest server-side scheduled work for a host, so
@@ -2809,6 +2845,35 @@ WHERE kind = 'sidecar' AND hibernate = 0 AND (status = '' OR status = 'ready') O
return out, rows.Err()
}
+// ResidentInstances returns every row Route.Resident names that the
+// activator may start on its own: an always-awake rootfs instance in a
+// runnable status ("ready" or the legacy ""), with no hold, no uncommitted
+// import, a socket to serve on, and neither a unit nor a tunnel behind it.
+// The residency sweep asks it, as AlwaysOnWorkers' sweep does for sidecars.
+func (r *Registry) ResidentInstances() ([]Route, error) {
+ if r.remote != nil {
+ out, err := r.remote.call(nil, remoteRequest{Method: "ResidentInstances"}, nil)
+ return out.Routes, err
+ }
+
+ rows, err := r.sql.Query(`SELECT ` + routeCols + ` FROM routes
+WHERE kind = 'instance' AND runtime = '` + RuntimeRootfsV1 + `' AND hibernate = 0 AND (status = '' OR status = 'ready')
+AND hold_op = '' AND import_gate = '' AND socket != '' AND backing = '' AND tunnel = '' ORDER BY host`)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []Route
+ for rows.Next() {
+ t, err := scanRoute(rows.Scan)
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, t)
+ }
+ return out, rows.Err()
+}
+
// SetSeed stamps a route's first-boot init argv as a narrow UPDATE — same
// rationale as SetAccount (a read-modify-write Upsert racing a deploy's
// SetVersions or the activator's SetNextDue would clobber it). Unlike
diff --git a/internal/registry/remote.go b/internal/registry/remote.go
index 2dd340353..1c6c7b81e 100644
--- a/internal/registry/remote.go
+++ b/internal/registry/remote.go
@@ -14,7 +14,7 @@ import (
var errRemoteMethod = errors.New("registry: unsupported remote operation")
-var remoteErrors = []error{os.ErrNotExist, os.ErrPermission, sql.ErrNoRows, ErrClaimOwnership, ErrTimerChanged, ErrTimerKind, ErrPathsChanged, ErrFleetBoxActive, context.Canceled, context.DeadlineExceeded, ErrGoodBuildChanged}
+var remoteErrors = []error{os.ErrNotExist, os.ErrPermission, sql.ErrNoRows, ErrClaimOwnership, ErrTimerChanged, ErrTimerKind, ErrPathsChanged, ErrFleetBoxActive, context.Canceled, context.DeadlineExceeded, ErrGoodBuildChanged, ErrRuntimeFixed}
func responseError(out remoteResponse) error {
if !out.Failed {
diff --git a/internal/registry/remote_dispatch.go b/internal/registry/remote_dispatch.go
index 0ee717064..d4e9530e9 100644
--- a/internal/registry/remote_dispatch.go
+++ b/internal/registry/remote_dispatch.go
@@ -298,6 +298,8 @@ func (r *Registry) dispatchRemote(ctx context.Context, q remoteRequest, callback
err = r.ClearNextDueIf(q.Host, q.Due)
case "AlwaysOnWorkers":
out.Routes, err = r.AlwaysOnWorkers()
+ case "ResidentInstances":
+ out.Routes, err = r.ResidentInstances()
case "SetSeed":
err = r.SetSeed(q.Host, q.Seed)
case "SetArgs":
diff --git a/internal/registry/remote_test.go b/internal/registry/remote_test.go
index 66bdd7380..8d6cf021a 100644
--- a/internal/registry/remote_test.go
+++ b/internal/registry/remote_test.go
@@ -48,6 +48,15 @@ func TestRemoteRegistryRoundTrip(t *testing.T) {
if err != nil || got == nil || got.Version != "v2" || got.PrevVersion != "v1" {
t.Fatalf("route = %+v, %v", got, err)
}
+ resident := Route{Host: "resident.example.com", Kind: "instance", Socket: "/run/carlos/instances/resident.example.com/app.sock",
+ Runtime: RuntimeRootfsV1, Status: "ready"}
+ if err := r.Upsert(resident); err != nil {
+ t.Fatal(err)
+ }
+ residents, err := r.ResidentInstances()
+ if err != nil || len(residents) != 1 || residents[0].Host != resident.Host || !residents[0].Resident() {
+ t.Fatalf("ResidentInstances = %+v, %v", residents, err)
+ }
timer, err := r.UpsertTimerRegistration(Timer{Host: route.Host, Name: "tick", Kind: "cron", Spec: "* * * * *"}, "")
if err != nil {
t.Fatal(err)
diff --git a/internal/registry/runtime.go b/internal/registry/runtime.go
new file mode 100644
index 000000000..c6bc39bc7
--- /dev/null
+++ b/internal/registry/runtime.go
@@ -0,0 +1,34 @@
+package registry
+
+import "errors"
+
+// ErrRuntimeFixed is SetHibernate's refusal of a row whose Runtime is not
+// "": a rootfs row's hibernation is fixed when the row is minted, like its
+// runtime (spec §5.0). It is one of remoteErrors, so errors.Is holds across
+// the service-user child that root's `carlos route hibernate` writes through.
+var ErrRuntimeFixed = errors.New("registry: a rootfs row's hibernation is fixed when it is minted")
+
+// Rootfs reports whether t runs a rootfs image (Runtime RuntimeRootfsV1).
+// An unknown runtime is not rootfs: it refuses before any start (Plan 2).
+func (t Route) Rootfs() bool { return t.Runtime == RuntimeRootfsV1 }
+
+// ActivatorOwned reports whether the activator starts and stops t's
+// process: a hibernating instance, or any rootfs instance, resident or not.
+// A sidecar is never owned here; its worker path is separate.
+func (t Route) ActivatorOwned() bool {
+ return t.Kind == "instance" && (t.Hibernate || t.Rootfs())
+}
+
+// Resident reports whether t is an always-awake rootfs instance: the
+// activator owns it and keeps it running without waiting for a request.
+func (t Route) Resident() bool {
+ return t.Kind == "instance" && t.Rootfs() && !t.Hibernate
+}
+
+// ActivatorLeased reports whether the activator holds t's lease and
+// replication: every hibernating row, binary sidecars included (they
+// hibernate: provision's sidecarRouteFor), and every resident. Box-wide
+// litestream covers the rest.
+func (t Route) ActivatorLeased() bool {
+ return t.Hibernate || t.Resident()
+}
diff --git a/internal/registry/runtime_test.go b/internal/registry/runtime_test.go
new file mode 100644
index 000000000..7ee35bfd8
--- /dev/null
+++ b/internal/registry/runtime_test.go
@@ -0,0 +1,336 @@
+package registry
+
+import (
+ "errors"
+ "path/filepath"
+ "reflect"
+ "testing"
+)
+
+func openRuntimeTestRegistry(t *testing.T) *Registry {
+ t.Helper()
+ reg, err := Open(filepath.Join(t.TempDir(), "r.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { reg.Close() })
+ return reg
+}
+
+func mustGet(t *testing.T, reg *Registry, host string) Route {
+ t.Helper()
+ got, err := reg.Get(host)
+ if err != nil || got == nil {
+ t.Fatalf("Get(%s) = %+v, %v", host, got, err)
+ }
+ return *got
+}
+
+func sockFor(host string) string { return "/run/carlos/instances/" + host + "/app.sock" }
+
+// The predicates are asked of stored rows, so each case goes through Upsert
+// and Get as well as being asked of the literal.
+func TestRoutePredicates(t *testing.T) {
+ reg := openRuntimeTestRegistry(t)
+ cases := []struct {
+ name string
+ rt Route
+ rootfs, owned, resident, leased bool
+ }{
+ {name: "binary hibernating", rt: Route{Kind: "instance", Hibernate: true},
+ owned: true, leased: true},
+ {name: "binary awake", rt: Route{Kind: "instance"}},
+ {name: "binary hibernating sidecar", rt: Route{Kind: "sidecar", Hibernate: true},
+ leased: true},
+ {name: "binary awake sidecar", rt: Route{Kind: "sidecar"}},
+ {name: "rootfs hibernating", rt: Route{Kind: "instance", Runtime: RuntimeRootfsV1, Hibernate: true},
+ rootfs: true, owned: true, leased: true},
+ {name: "rootfs resident", rt: Route{Kind: "instance", Runtime: RuntimeRootfsV1},
+ rootfs: true, owned: true, resident: true, leased: true},
+ {name: "rootfs static", rt: Route{Kind: "static", Runtime: RuntimeRootfsV1},
+ rootfs: true},
+ {name: "unknown runtime hibernating", rt: Route{Kind: "instance", Runtime: "rootfs-v2", Hibernate: true},
+ owned: true, leased: true},
+ {name: "unknown runtime awake", rt: Route{Kind: "instance", Runtime: "rootfs-v2"}},
+ }
+ for i, c := range cases {
+ c.rt.Host = "p" + string(rune('a'+i)) + ".example.com"
+ c.rt.Socket = sockFor(c.rt.Host)
+ if err := reg.Upsert(c.rt); err != nil {
+ t.Fatalf("%s: Upsert: %v", c.name, err)
+ }
+ for _, rt := range []Route{c.rt, mustGet(t, reg, c.rt.Host)} {
+ if got := rt.Rootfs(); got != c.rootfs {
+ t.Errorf("%s: Rootfs() = %v, want %v", c.name, got, c.rootfs)
+ }
+ if got := rt.ActivatorOwned(); got != c.owned {
+ t.Errorf("%s: ActivatorOwned() = %v, want %v", c.name, got, c.owned)
+ }
+ if got := rt.Resident(); got != c.resident {
+ t.Errorf("%s: Resident() = %v, want %v", c.name, got, c.resident)
+ }
+ if got := rt.ActivatorLeased(); got != c.leased {
+ t.Errorf("%s: ActivatorLeased() = %v, want %v", c.name, got, c.leased)
+ }
+ }
+ }
+}
+
+// A rung means the activator replicates. A resident's database is the
+// activator's to replicate, so its rung survives both halves of Upsert's
+// invariant; a binary awake row's is still cleared.
+func TestResidentKeepsItsReplicationRung(t *testing.T) {
+ reg := openRuntimeTestRegistry(t)
+ res := Route{Host: "shop.example.com", Kind: "instance", Socket: sockFor("shop.example.com"),
+ Runtime: RuntimeRootfsV1, Replication: ReplicationDaily}
+ if err := reg.Upsert(res); err != nil {
+ t.Fatal(err)
+ }
+ if got := mustGet(t, reg, res.Host); got.Replication != ReplicationDaily {
+ t.Fatalf("resident after insert: Replication = %q, want %q", got.Replication, ReplicationDaily)
+ }
+ res.Replication = ""
+ if err := reg.Upsert(res); err != nil {
+ t.Fatal(err)
+ }
+ if got := mustGet(t, reg, res.Host); got.Replication != ReplicationDaily {
+ t.Fatalf("resident after a re-Upsert with no rung: Replication = %q, want %q", got.Replication, ReplicationDaily)
+ }
+ // A re-Upsert carrying no runtime (carlos add's shape) keys on the
+ // stored runtime, so the rung stays too.
+ res.Runtime = ""
+ if err := reg.Upsert(res); err != nil {
+ t.Fatal(err)
+ }
+ if got := mustGet(t, reg, res.Host); got.Replication != ReplicationDaily || got.Runtime != RuntimeRootfsV1 {
+ t.Fatalf("resident after a runtime-less re-Upsert = runtime %q replication %q, want %q %q",
+ got.Runtime, got.Replication, RuntimeRootfsV1, ReplicationDaily)
+ }
+
+ bin := Route{Host: "blog.example.com", Kind: "instance", Socket: sockFor("blog.example.com"), Replication: ReplicationDaily}
+ if err := reg.Upsert(bin); err != nil {
+ t.Fatal(err)
+ }
+ if got := mustGet(t, reg, bin.Host); got.Replication != "" {
+ t.Fatalf("binary awake row after insert: Replication = %q, want it cleared", got.Replication)
+ }
+ // The conflict half: a hibernating binary row with a rung, re-Upserted
+ // awake, loses it.
+ bin.Hibernate = true
+ if err := reg.Upsert(bin); err != nil {
+ t.Fatal(err)
+ }
+ if got := mustGet(t, reg, bin.Host); got.Replication != ReplicationDaily {
+ t.Fatalf("binary hibernating row: Replication = %q, want %q", got.Replication, ReplicationDaily)
+ }
+ bin.Hibernate = false
+ if err := reg.Upsert(bin); err != nil {
+ t.Fatal(err)
+ }
+ if got := mustGet(t, reg, bin.Host); got.Replication != "" || got.Hibernate {
+ t.Fatalf("binary row re-Upserted awake = hibernate %v replication %q, want false and cleared", got.Hibernate, got.Replication)
+ }
+}
+
+// A rootfs row's hibernation is fixed at mint: a full-row Upsert with the
+// flag flipped (carlos add's shape, with or without the runtime) leaves it.
+// A binary row's flip through Upsert still lands.
+func TestUpsertKeepsRootfsHibernation(t *testing.T) {
+ reg := openRuntimeTestRegistry(t)
+ for _, hib := range []bool{false, true} {
+ for _, incomingRuntime := range []string{RuntimeRootfsV1, ""} {
+ host := "shop.example.com"
+ if hib {
+ host = "bab.example.com"
+ }
+ rt := Route{Host: host, Kind: "instance", Socket: sockFor(host), Runtime: RuntimeRootfsV1,
+ Hibernate: hib, Replication: ReplicationDaily}
+ if err := reg.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ before := mustGet(t, reg, host)
+ flipped := rt
+ flipped.Hibernate = !hib
+ flipped.Runtime = incomingRuntime
+ flipped.Replication = ""
+ if err := reg.Upsert(flipped); err != nil {
+ t.Fatal(err)
+ }
+ after := mustGet(t, reg, host)
+ if after.Hibernate != hib || after.Runtime != RuntimeRootfsV1 || after.Replication != ReplicationDaily {
+ t.Errorf("rootfs hibernate=%v re-Upserted flipped (incoming runtime %q) = hibernate %v runtime %q replication %q, want %v %q %q",
+ hib, incomingRuntime, after.Hibernate, after.Runtime, after.Replication, hib, RuntimeRootfsV1, ReplicationDaily)
+ }
+ if after != before {
+ t.Errorf("rootfs hibernate=%v: row changed under a same-content flipped Upsert:\n before %+v\n after %+v", hib, before, after)
+ }
+ }
+ }
+
+ bin := Route{Host: "blog.example.com", Kind: "instance", Socket: sockFor("blog.example.com")}
+ for _, want := range []bool{true, false, true} {
+ bin.Hibernate = want
+ if err := reg.Upsert(bin); err != nil {
+ t.Fatal(err)
+ }
+ if got := mustGet(t, reg, bin.Host); got.Hibernate != want {
+ t.Fatalf("binary row Upserted hibernate=%v: stored %v", want, got.Hibernate)
+ }
+ }
+}
+
+// A re-tenanted host is a new life: it takes the incoming runtime and
+// hibernation, and its replication follows the rule for the incoming
+// runtime, not the stored one.
+func TestRetenantedHostTakesRuntimeAndHibernation(t *testing.T) {
+ reg := openRuntimeTestRegistry(t)
+ const host = "shop.example.com"
+ up := func(rt Route) Route {
+ t.Helper()
+ rt.Host, rt.Kind, rt.Socket = host, "instance", sockFor(host)
+ if err := reg.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ return mustGet(t, reg, host)
+ }
+
+ // A resident to a hibernating binary: both taken, and the binary rule
+ // for a hibernating row keeps the stored rung.
+ up(Route{Account: "acctone", App: "shop", Runtime: RuntimeRootfsV1, Replication: ReplicationDaily})
+ got := up(Route{Account: "accttwo", App: "shop", Runtime: "", Hibernate: true})
+ if got.Runtime != "" || !got.Hibernate || got.Replication != ReplicationDaily {
+ t.Fatalf("resident re-tenanted as a hibernating binary = runtime %q hibernate %v replication %q, want \"\" true %q",
+ got.Runtime, got.Hibernate, got.Replication, ReplicationDaily)
+ }
+
+ // A resident to an awake binary: the rung goes, keyed on the incoming
+ // runtime (the stored one is rootfs).
+ up(Route{Account: "acctthree", App: "shop", Runtime: RuntimeRootfsV1, Replication: ReplicationDaily})
+ got = up(Route{Account: "acctfour", App: "shop"})
+ if got.Runtime != "" || got.Hibernate || got.Replication != "" {
+ t.Fatalf("resident re-tenanted as an awake binary = runtime %q hibernate %v replication %q, want \"\" false \"\"",
+ got.Runtime, got.Hibernate, got.Replication)
+ }
+
+ // An awake binary to a resident under another app: the incoming rung is
+ // kept, keyed on the incoming runtime (the stored one is binary).
+ got = up(Route{Account: "acctfour", App: "blog", Runtime: RuntimeRootfsV1, Replication: ReplicationDaily})
+ if got.Runtime != RuntimeRootfsV1 || got.Hibernate || got.Replication != ReplicationDaily {
+ t.Fatalf("binary re-tenanted as a resident = runtime %q hibernate %v replication %q, want %q false %q",
+ got.Runtime, got.Hibernate, got.Replication, RuntimeRootfsV1, ReplicationDaily)
+ }
+
+ // A hibernating rootfs row re-tenanted as a resident takes the flip.
+ up(Route{Account: "acctfive", App: "shop", Runtime: RuntimeRootfsV1, Hibernate: true})
+ got = up(Route{Account: "acctsix", App: "shop", Runtime: RuntimeRootfsV1})
+ if got.Hibernate {
+ t.Fatalf("hibernating rootfs row re-tenanted as a resident kept hibernate")
+ }
+}
+
+func TestSetHibernateRefusesRootfsRows(t *testing.T) {
+ reg := openRuntimeTestRegistry(t)
+ assertSetHibernateRefusesRootfs(t, reg)
+}
+
+func TestRemoteSetHibernateRefusesRootfsRows(t *testing.T) {
+ reg, _ := remoteTestRegistry(t)
+ assertSetHibernateRefusesRootfs(t, reg)
+}
+
+func assertSetHibernateRefusesRootfs(t *testing.T, reg *Registry) {
+ t.Helper()
+ for _, hib := range []bool{false, true} {
+ host := "shop.example.com"
+ if hib {
+ host = "bab.example.com"
+ }
+ if err := reg.Upsert(Route{Host: host, Kind: "instance", Socket: sockFor(host), Runtime: RuntimeRootfsV1,
+ Hibernate: hib, Replication: ReplicationDaily}); err != nil {
+ t.Fatal(err)
+ }
+ before := mustGet(t, reg, host)
+ for _, on := range []bool{!hib, hib} {
+ if err := reg.SetHibernate(host, on); !errors.Is(err, ErrRuntimeFixed) {
+ t.Errorf("SetHibernate(%s hibernate=%v, %v) = %v, want ErrRuntimeFixed", host, hib, on, err)
+ }
+ if after := mustGet(t, reg, host); !reflect.DeepEqual(after, before) {
+ t.Errorf("SetHibernate(%s, %v) changed a rootfs row:\n before %+v\n after %+v", host, on, before, after)
+ }
+ }
+ }
+
+ bin := Route{Host: "blog.example.com", Kind: "instance", Socket: sockFor("blog.example.com"), Hibernate: true}
+ if err := reg.Upsert(bin); err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.SetHibernate(bin.Host, false); err != nil {
+ t.Fatalf("SetHibernate on a binary row: %v", err)
+ }
+ if got := mustGet(t, reg, bin.Host); got.Hibernate {
+ t.Fatal("a binary row's SetHibernate(false) did not land")
+ }
+ if err := reg.SetHibernate(bin.Host, true); err != nil {
+ t.Fatalf("SetHibernate on a binary row: %v", err)
+ }
+ if got := mustGet(t, reg, bin.Host); !got.Hibernate {
+ t.Fatal("a binary row's SetHibernate(true) did not land")
+ }
+ // No row is not a rootfs row: today's silent no-op.
+ if err := reg.SetHibernate("missing.example.com", true); err != nil {
+ t.Fatalf("SetHibernate on a missing host = %v, want nil", err)
+ }
+}
+
+func TestResidentInstancesSelects(t *testing.T) {
+ reg := openRuntimeTestRegistry(t)
+ resident := func(host string) Route {
+ return Route{Host: host, Kind: "instance", Socket: sockFor(host), Runtime: RuntimeRootfsV1}
+ }
+ in := []Route{resident("ready.example.com"), resident("blank.example.com")}
+ hib := resident("hibernating.example.com")
+ hib.Hibernate = true
+ failed := resident("failed.example.com")
+ failed.Status = "failed"
+ gated := resident("gated.example.com")
+ gated.ImportGate = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
+ sidecar := resident("sidecar.example.com")
+ sidecar.Kind = "sidecar"
+ unit := resident("unit.example.com")
+ unit.Backing = BackingUnit
+ nosock := resident("nosock.example.com")
+ nosock.Socket, nosock.Addr = "", "127.0.0.1:9001"
+ tunnelled := resident("tunnel.example.com")
+ tunnelled.Tunnel = "bab"
+ out := []Route{hib, resident("held.example.com"), failed, gated, sidecar, unit, nosock, tunnelled,
+ {Host: "binary.example.com", Kind: "instance", Socket: sockFor("binary.example.com")}}
+ for _, rt := range append(append([]Route{}, in...), out...) {
+ if err := reg.Upsert(rt); err != nil {
+ t.Fatalf("Upsert %s: %v", rt.Host, err)
+ }
+ }
+ // Upsert writes status "ready" for "", and a hold always names a hold
+ // status: set the legacy blank status and a bare hold_op directly, so
+ // each filter is tested on its own.
+ if _, err := reg.sql.Exec(`UPDATE routes SET status = '' WHERE host = ?`, "blank.example.com"); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := reg.sql.Exec(`UPDATE routes SET hold_op = 'move' WHERE host = ?`, "held.example.com"); err != nil {
+ t.Fatal(err)
+ }
+
+ got, err := reg.ResidentInstances()
+ if err != nil {
+ t.Fatal(err)
+ }
+ var hosts []string
+ for _, rt := range got {
+ hosts = append(hosts, rt.Host)
+ if want := mustGet(t, reg, rt.Host); !reflect.DeepEqual(rt, want) {
+ t.Errorf("ResidentInstances row %s differs from Get:\n got %+v\n want %+v", rt.Host, rt, want)
+ }
+ }
+ if want := []string{"blank.example.com", "ready.example.com"}; !reflect.DeepEqual(hosts, want) {
+ t.Fatalf("ResidentInstances = %v, want %v (ordered by host)", hosts, want)
+ }
+}