ha: enforce configured pool membership at acquisition
Require configured pool membership before legacy or HA acquisition, adoption, spawn and duty admission. Share normalization with pool publication and prove refusals and release retries with regression and mutation tests.
Co-Authored-By: GPT-6 Astra <noreply@openai.com>
99 files changed,
+666
−237
docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md+4 −2internal/activator/activator_test.go+7 −3internal/activator/agentowned_moves_test.go+6 −6internal/activator/backend_exec.go+10 −0internal/activator/backend_exec_test.go+8 −8internal/activator/backend_unit.go+16 −0internal/activator/claim_instancekey_test.go+3 −3internal/activator/claim_shape_rev2_shape_test.go+1 −1internal/activator/claim_shape_rev4_sidecar_error_test.go+6 −6internal/activator/claim_snapshot_test.go+1 −1internal/activator/claimspawn_kernel_linux_test.go+2 −2internal/activator/cmdunit_test.go+1 −1internal/activator/config_gate_test.go+2 −2internal/activator/coordinator_test.go+2 −2internal/activator/demo_durability_test.go+2 −2internal/activator/genbackend_test.go+1 −1internal/activator/genparent_kernel_linux_test.go+1 −1internal/activator/group_admission_test.go+2 −2internal/activator/haadopt.go+8 −2internal/activator/haduties.go+8 −1internal/activator/haduties_test.go+2 −2internal/activator/hasuspectholder_test.go+6 −6internal/activator/hatakeover_page_test.go+1 −1internal/activator/hawake.go+4 −1internal/activator/instancekey_delivery_test.go+5 −5internal/activator/instancekey_test.go+5 −5internal/activator/keyadoption_test.go+1 −1internal/activator/leaseidentity_test.go+2 −2internal/activator/pools_test.go+132 −0internal/activator/replica_instancekey_test.go+2 −2internal/activator/replicakey_race_test.go+1 −1internal/activator/replicaretirement_test.go+2 −2internal/activator/rootfs_worker_unit_test.go+2 −2internal/activator/rootfsworkers_backend_test.go+1 −1internal/activator/size_identical_test.go+3 −3internal/activator/size_pending_test.go+1 −1internal/activator/startrule_test.go+1 −1internal/activator/stateless_assignment_test.go+1 −1internal/activator/stateless_fix1_test.go+1 −1internal/activator/stateless_fix2_linux_test.go+1 −1internal/activator/stateless_test.go+2 −2internal/activator/wakerecord_recheck_test.go+1 −1internal/edge/forwardha_wiring_test.go+2 −1internal/edge/haplacement_wiring_test.go+5 −4internal/hafresh/acquire.go+14 −8internal/hafresh/acquire_test.go+18 −18internal/hafresh/pools_test.go+31 −0internal/host/agent.go+4 −3internal/host/booting_publication_test.go+1 −1internal/host/claim_first_wake_linux_test.go+1 −1internal/host/claimproduction.go+1 −1internal/host/claimproduction_admintoken_test.go+1 −1internal/host/claimunit_inputs_test.go+1 −1internal/host/declinedgate_identity_test.go+1 −1internal/host/edgesfile.go+5 −17internal/host/fleettwobox_e2e_test.go+1 −1internal/host/group_admission_fix_test.go+5 −5internal/host/group_admission_test.go+2 −2internal/host/hadepartures_production_test.go+5 −1internal/host/hadepartures_proof_followups_test.go+1 −1internal/host/hadepartures_wiring_test.go+3 −3internal/host/haduties_wiring_test.go+1 −1internal/host/haforward_wiring_test.go+1 −1internal/host/haplacement_budget_test.go+2 −2internal/host/haplacement_root_linux_test.go+1 −1internal/host/haplacement_wiring_test.go+1 −1internal/host/instancekey_adoption_test.go+1 −1internal/host/interactive_rootrunner_linux_test.go+3 −3internal/host/interactive_test.go+1 −1internal/host/lifetime_gating_test.go+1 −1internal/host/movesenvskew_test.go+1 −1internal/host/moveshome_target_test.go+3 −3internal/host/movesoffline_e2e_test.go+4 −4internal/host/movesoffline_land_test.go+3 −3internal/host/movesoffline_seal_test.go+1 −1internal/host/movesparks_test.go+1 −1internal/host/movesphase1_harness_test.go+1 −1internal/host/movesphase1_test.go+1 −1internal/host/plan14_generation_backend_root_linux_test.go+1 −1internal/host/pools_test.go+53 −0internal/host/rawsecretpage_test.go+1 −1internal/host/rollout_test.go+4 −4internal/host/rolloutdeclined_test.go+3 −3internal/host/rootfsstart_test.go+1 −1internal/host/schedule_wiring_test.go+1 −1internal/host/seedwiring_test.go+7 −7internal/host/stateless_failed_release_test.go+1 −1internal/host/stateless_runtime_test.go+1 −1internal/host/suspects_test.go+2 −2internal/lease/ha.go+8 −0internal/lease/ha_test.go+15 −15internal/lease/haduty_test.go+4 −4internal/lease/pools_test.go+102 −0internal/lease/release_test.go+2 −2internal/lease/termination_proof_test.go+4 −4internal/provision/pools_test.go+39 −0internal/provision/reconcile.go+18 −3internal/sim/regionha/actions_test.go+1 −1internal/sim/regionha/duties_model_test.go+1 −1
diff --git a/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md b/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md| index 922d518c1..3f9ccad53 100644 |
| --- a/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md |
| +++ b/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md |
| @@ -116,7 +116,7 @@ Each is the author's or the coordinator's. Paul can overturn any of them. |
| ## 3. Model |
| -Every box in a region adopts every tenant host record of its region, as today (`internal/provision/reconcile.go:443-457`), except records the serving boxes must not run (§6.1). An instance has no home box. It runs on whichever box holds its Litestream lease, and only there. A box that receives a request for a host it is not running either takes the lease and wakes the host, or forwards the request once to the box that holds it. A cold wake goes where the release marker proves a reusable copy, or else to the roomiest eligible box. A graceful sleep leaves a release marker in the lease object, naming the box and the exact state it released. Only that box, with that state untouched, may reuse its local copy. Every other wake restores from S3 into a clean tree. Another box may take a lease only from a release marker, or from an owner EC2 has confirmed terminated. Expiry alone is never enough. A hung box therefore keeps its instances down until its group terminates it. A sleeping instance's timers stay in the local registry of the box that released it, as today. When that box leaves, one scan of the region's locks imports them elsewhere from the wake state in S3. |
| +Every box in a region adopts the tenant host records of its region whose pools the box serves, as today (`internal/provision/reconcile.go:443-457`), except records the serving boxes must not run (§6.1). An instance has no home box. It runs on whichever box holds its Litestream lease, and only there. A box that receives a request for a host it is not running either takes the lease and wakes the host, or forwards the request once to the box that holds it. A cold wake goes where the release marker proves a reusable copy, or else to the roomiest eligible box. A graceful sleep leaves a release marker in the lease object, naming the box and the exact state it released. Only that box, with that state untouched, may reuse its local copy. Every other wake restores from S3 into a clean tree. Another box may take a lease only from a release marker, or from an owner EC2 has confirmed terminated. Expiry alone is never enough. A hung box therefore keeps its instances down until its group terminates it. A sleeping instance's timers stay in the local registry of the box that released it, as today. When that box leaves, one scan of the region's locks imports them elsewhere from the wake state in S3. |
| ### 3.1 Invariants |
| @@ -124,7 +124,7 @@ Each invariant is enforced in one place and checked by the seeded N-box simulati |
| | # | Invariant | Enforced only in | Checked by | |
| |---|---|---|---| |
| -| I1 | **Single writer.** At most one box runs an instance. Another box acquires its lease only from a release marker written by the previous holder, or after EC2 confirms the owner terminated. A box re-takes its own expired lease only with a cgroup-empty proof. | The HA acquire, one function (§9.4). | Sim I1 and I3. Mutations: expiry authorizes; `shutting-down` accepted; same-box without proof. | |
| +| I1 | **Single writer.** At most one box runs an instance. A box must serve the instance's pool before it may acquire its lease; §6.2 and §6.3 apply within this precondition. Another box acquires its lease only from a release marker written by the previous holder, or after EC2 confirms the owner terminated. A box re-takes its own expired lease only with a cgroup-empty proof. | The HA acquire, one function (§9.4). | Sim I1 and I3. Mutations: expiry authorizes; `shutting-down` accepted; same-box without proof. | |
| | I2 | **Positive-proof local copy.** A box uses a local DB or files only when a clean release marker names it, its lifetime matches, the publish was complete, and the local state is unchanged since. The only other path that publishes local state is the one-time migration (§8.4), under its own three conditions. | The keep decision, one function (§5.3), and the migration gate (§8.4). | Sim I2 and I8. Mutations: keep without a marker; keep after an incomplete publish; migrate with two copies. | |
| | I3 | **Duty coverage.** An instance's duties run from the local registry of the box that holds its lease, or of the box that released or adopted it. When a box leaves, every host it held or released has its wake state imported by a live box. The loss is bounded by the ~1 s wake-state sync (N-HA5), as H3 states it for files. | The import function, one place, called by the termination scan and by drain completion (§7.4). | Sim I6. Mutations: skip the scan; match owners but not releasers; delete the edges file before the scan finishes. Witness: a box dies before any wake-state sync of a new timer. | |
| | I4 | **Failover bound.** A terminated or hung box's instances serve again within §9.8's bound. | Not by prose: the drills are G2's acceptance gate (§19, §21.2). | Dev drills, timed. Sim I5 for the logic. Witness: a hang just after first service reached by direct backhaul. | |
| @@ -227,6 +227,8 @@ The batched and daily classes keep their 5-minute and 24-hour sync intervals (`a |
| ### 6.1 What serving boxes run (astra-1.11) |
| +Pool membership is a tenancy boundary: a box may host only instances in pools it serves. An ingress box outside the host's pool forwards to an eligible peer or refuses the request; it never hosts the instance. The decisions in §6.2 and §6.3 apply within this boundary, including A20's low-headroom fallback and N-HA7's switch-off fallback. Local configuration supplies this membership through `ReconcileConfig.ServedPools()` and `PoolEvidence.Serves`: unconfigured pools mean only the shared pool (`""`), while invalid-only configuration means no pools. Missing or malformed remote pool evidence does not grant membership. |
| + |
| A box with role `serve` in an HA region never routes locally: |
| - a record carrying `Unit` (copied by `RouteFor`, `reconcile.go:478-483`); |
| - a platform record; |
diff --git a/internal/activator/activator_test.go b/internal/activator/activator_test.go| index 3a3c2fe55..015d28034 100644 |
| --- a/internal/activator/activator_test.go |
| +++ b/internal/activator/activator_test.go |
| @@ -37,6 +37,7 @@ import ( |
| "github.com/carlosframework/platform/internal/cgroup" |
| "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/edgesfile" |
| "github.com/carlosframework/platform/internal/lease" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/registry" |
| @@ -4670,9 +4671,10 @@ func TestConfigFromEnv(t *testing.T) { |
| func testExecBackend(t *testing.T) *ExecBackend { |
| t.Helper() |
| return &ExecBackend{ |
| - Cfg: Config{Bucket: "test-bucket", Idle: time.Minute}, |
| - OptDir: t.TempDir(), |
| - DataDir: t.TempDir(), |
| + ServedPools: func() edgesfile.PoolEvidence { return edgesfile.PoolEvidence(`[""]`) }, |
| + Cfg: Config{Bucket: "test-bucket", Idle: time.Minute}, |
| + OptDir: t.TempDir(), |
| + DataDir: t.TempDir(), |
| } |
| } |
| @@ -7347,3 +7349,5 @@ func TestAPendingFlagOffStopProvesTheHostCgroupBeforeTheLeaseGoes(t *testing.T) |
| return rep.isClosed() && a.entryCount() == 0 |
| }) |
| } |
| + |
| +func (b *fakeBackend) poolEligible(registry.Route) bool { return true } |
diff --git a/internal/activator/agentowned_moves_test.go b/internal/activator/agentowned_moves_test.go| index f865edf4a..c48a66e89 100644 |
| --- a/internal/activator/agentowned_moves_test.go |
| +++ b/internal/activator/agentowned_moves_test.go |
| @@ -41,15 +41,15 @@ func TestAgentOwnedVarsAreMovesBoxOwned(t *testing.T) { |
| control bool |
| want map[string]string |
| }{ |
| - {"everything on", &ExecBackend{Region: "uk", Cache: cache}, true, |
| + {"everything on", &ExecBackend{ServedPools: eligibleSharedPools, Region: "uk", Cache: cache}, true, |
| map[string]string{"CARLOS_CONTROL_SOCKET": control, "CARLOS_PURGE": "header", "CARLOS_REGION": "uk", "CARLOS_HOST": rt.Host}}, |
| - {"everything off", &ExecBackend{}, false, |
| + {"everything off", &ExecBackend{ServedPools: eligibleSharedPools}, false, |
| map[string]string{"CARLOS_CONTROL_SOCKET": absent, "CARLOS_PURGE": absent, "CARLOS_REGION": absent, "CARLOS_HOST": rt.Host}}, |
| - {"no control channel", &ExecBackend{Region: "uk", Cache: cache}, false, |
| + {"no control channel", &ExecBackend{ServedPools: eligibleSharedPools, Region: "uk", Cache: cache}, false, |
| map[string]string{"CARLOS_CONTROL_SOCKET": absent, "CARLOS_PURGE": "header", "CARLOS_REGION": "uk", "CARLOS_HOST": rt.Host}}, |
| - {"no cache", &ExecBackend{Region: "uk"}, true, |
| + {"no cache", &ExecBackend{ServedPools: eligibleSharedPools, Region: "uk"}, true, |
| map[string]string{"CARLOS_CONTROL_SOCKET": control, "CARLOS_PURGE": absent, "CARLOS_REGION": "uk", "CARLOS_HOST": rt.Host}}, |
| - {"a home box, no region", &ExecBackend{Cache: cache}, true, |
| + {"a home box, no region", &ExecBackend{ServedPools: eligibleSharedPools, Cache: cache}, true, |
| map[string]string{"CARLOS_CONTROL_SOCKET": control, "CARLOS_PURGE": "header", "CARLOS_REGION": absent, "CARLOS_HOST": rt.Host}}, |
| } { |
| t.Run(c.name, func(t *testing.T) { |
| @@ -97,7 +97,7 @@ func TestAgentOwnedVarsAreMovesBoxOwned(t *testing.T) { |
| // instance file sets is one of them; one inherited from the agent's |
| // process is not, and neither is anything the agent adds. |
| func TestLaunchLayersNamesTheInstanceLayers(t *testing.T) { |
| - b := &ExecBackend{DataDir: t.TempDir(), Region: "ie"} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, DataDir: t.TempDir(), Region: "ie"} |
| rt := registry.Route{Host: "a.go.example.com", Socket: filepath.Join(b.DataDir, "a.sock")} |
| t.Setenv("PWD", "/inherited") |
| if err := os.WriteFile(filepath.Join(b.DataDir, rt.Host+".env"), []byte("MINE=1\nHOSTNAME=instance\nCARLOS_REGION=fake\n"), 0o600); err != nil { |
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go| index c8ac364cc..683b37833 100644 |
| --- a/internal/activator/backend_exec.go |
| +++ b/internal/activator/backend_exec.go |
| @@ -27,6 +27,7 @@ import ( |
| "github.com/carlosframework/platform/internal/applog" |
| "github.com/carlosframework/platform/internal/cgroup" |
| "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/edgesfile" |
| "github.com/carlosframework/platform/internal/hafresh" |
| "github.com/carlosframework/platform/internal/instancectl" |
| "github.com/carlosframework/platform/internal/instancekey" |
| @@ -76,6 +77,7 @@ const quarantineSuffix = ".corrupt" |
| // binary a systemd unit would run — `<OptDir>/live/<host>` with the |
| // `<DataDir>/<host>.env` EnvironmentFile. |
| type ExecBackend struct { |
| + ServedPools func() edgesfile.PoolEvidence |
| TenantStartAllowed func(registry.Route) bool |
| workerAPI http.Handler |
| // Coordination is the agent-owned client; serving never acquires through it. |
| @@ -815,6 +817,9 @@ func (b *ExecBackend) Acquire(ctx context.Context, rt registry.Route) (Lease, er |
| if err := b.tenantStartRefusal(rt); err != nil { |
| return nil, err |
| } |
| + if !b.poolEligible(rt) { |
| + return nil, &errLeaseRefused{reason: hafresh.ReasonPoolIneligible} |
| + } |
| // Admission before the lease: the instance's config has to be |
| // providable from THIS box, or it must not be the one that starts it. |
| // Here, not in doWake, because this is the only place an instance or |
| @@ -3910,3 +3915,8 @@ func dropWorkers(m lease.MirrorStore, n int) int { |
| } |
| return min(w, n) |
| } |
| + |
| +// poolEligible reads local configuration, never a published peer snapshot. |
| +func (b *ExecBackend) poolEligible(rt registry.Route) bool { |
| + return b.ServedPools != nil && b.ServedPools().Serves(rt.Pool) |
| +} |
diff --git a/internal/activator/backend_exec_test.go b/internal/activator/backend_exec_test.go| index 908535fc4..b57119831 100644 |
| --- a/internal/activator/backend_exec_test.go |
| +++ b/internal/activator/backend_exec_test.go |
| @@ -44,7 +44,7 @@ func TestExecBackendTierSeam(t *testing.T) { |
| // before, and a name this box does not know falls back to the build's tier. |
| func TestTierSeamPrefersTheSizeColumn(t *testing.T) { |
| t.Parallel() |
| - b := &ExecBackend{Tier: func(registry.Route) cgroup.Limit { return cgroup.TierChildren }} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, Tier: func(registry.Route) cgroup.Limit { return cgroup.TierChildren }} |
| for _, c := range []struct { |
| size string |
| want int64 |
| @@ -64,7 +64,7 @@ func TestTierSeamPrefersTheSizeColumn(t *testing.T) { |
| } |
| } |
| // With no Tier seam the fallback is the default tier. |
| - if got := (&ExecBackend{}).tier(registry.Route{Host: "tierseam-size.example.com", Size: "large"}); got != cgroup.TierChildren { |
| + if got := (&ExecBackend{ServedPools: eligibleSharedPools}).tier(registry.Route{Host: "tierseam-size.example.com", Size: "large"}); got != cgroup.TierChildren { |
| t.Fatalf("nil Tier, size large: %+v, want large", got) |
| } |
| } |
| @@ -118,7 +118,7 @@ func (f writerFunc) Write(p []byte) (int, error) { return f(p) } |
| // delegates an exec row and answers TierDefault for a unit-backed row. |
| func TestEffectiveSizeThroughExecAndSplitBackends(t *testing.T) { |
| t.Parallel() |
| - eb := &ExecBackend{ |
| + eb := &ExecBackend{ServedPools: eligibleSharedPools, |
| Tier: func(registry.Route) cgroup.Limit { return cgroup.TierDefault }, |
| TierOf: func(registry.Route, string) cgroup.Limit { return cgroup.TierChildren }, |
| } |
| @@ -175,7 +175,7 @@ func TestSpawnInCgroupAppliesTheTier(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - b := ExecBackend{Cgroups: m, Tier: func(registry.Route) cgroup.Limit { return cgroup.TierChildren }} |
| + b := ExecBackend{ServedPools: eligibleSharedPools, Cgroups: m, Tier: func(registry.Route) cgroup.Limit { return cgroup.TierChildren }} |
| rt := registry.Route{Host: "h.example.com"} |
| cmd, _, err := b.spawnInCgroup(rt, func() *exec.Cmd { return exec.Command("/bin/true") }) |
| if err != nil { |
| @@ -492,7 +492,7 @@ func writeMinimalSQLite(dbPath string) error { |
| } |
| func TestLaunchEnvironmentComposesTheSpawnEnvironment(t *testing.T) { |
| - b := &ExecBackend{DataDir: t.TempDir(), Region: "ie"} // Cache nil: no purge channel on this box |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, DataDir: t.TempDir(), Region: "ie"} // Cache nil: no purge channel on this box |
| rt := registry.Route{Host: "a.go.example.com", Socket: filepath.Join(b.DataDir, "a.sock")} |
| if err := os.WriteFile(filepath.Join(b.DataDir, rt.Host+".env"), []byte("MINE=1\nCARLOS_ADMIN_TOKEN=t\nCARLOS_PURGE=header\nCARLOS_REGION=fake\n"), 0o600); err != nil { |
| t.Fatal(err) |
| @@ -549,7 +549,7 @@ func TestEmptyOwnInstanceKeyShadowsNothing(t *testing.T) { |
| if got := mergeEnv(cfg, map[string]string{"CARLOS_INSTANCE_KEY": ""}); got["CARLOS_INSTANCE_KEY"] != "cfg" { |
| t.Fatalf("mergeEnv with an empty own key: CARLOS_INSTANCE_KEY = %q, want the configured key", got["CARLOS_INSTANCE_KEY"]) |
| } |
| - b := &ExecBackend{DataDir: t.TempDir(), Region: "ie"} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, DataDir: t.TempDir(), Region: "ie"} |
| rt := registry.Route{Host: "k.go.example.com", Socket: filepath.Join(b.DataDir, "k.sock")} |
| write := func(name, body string) { |
| t.Helper() |
| @@ -575,7 +575,7 @@ func TestEmptyOwnInstanceKeyShadowsNothing(t *testing.T) { |
| // With neither file present the composition is the agent-owned layer over |
| // the agent's own environment, no error and nothing shadowed. |
| func TestLaunchEnvironmentNoFiles(t *testing.T) { |
| - b := &ExecBackend{DataDir: t.TempDir(), Region: "ie"} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, DataDir: t.TempDir(), Region: "ie"} |
| rt := registry.Route{Host: "b.go.example.com", Socket: filepath.Join(b.DataDir, "b.sock")} |
| env, shadowed, err := b.LaunchEnvironment(rt) |
| if err != nil || len(shadowed) != 0 || env["CARLOS_REGION"] != "ie" { |
| @@ -797,7 +797,7 @@ func TestNextSpawnStrict(t *testing.T) { |
| if tc.preflight == nil && runtime.GOOS != "linux" { |
| t.Skip("the real preflight answers unsupported off Linux") |
| } |
| - b := &ExecBackend{Strict: tc.strict, Cgroups: tc.cg, strictPreflight: tc.preflight} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, Strict: tc.strict, Cgroups: tc.cg, strictPreflight: tc.preflight} |
| c := b.NextSpawnStrict(host) |
| if c.OK != tc.ok || (!c.OK && !strings.Contains(c.Reason, tc.inWords)) || (c.OK && c.Reason != "") { |
| t.Fatalf("NextSpawnStrict = %+v, want ok=%v naming %q", c, tc.ok, tc.inWords) |
diff --git a/internal/activator/backend_unit.go b/internal/activator/backend_unit.go| index 10e13bec3..ea175b16c 100644 |
| --- a/internal/activator/backend_unit.go |
| +++ b/internal/activator/backend_unit.go |
| @@ -303,6 +303,9 @@ func (b *SplitBackend) pick(rt registry.Route) Backend { |
| } |
| func (b *SplitBackend) Acquire(ctx context.Context, rt registry.Route) (Lease, error) { |
| + if !b.poolEligible(rt) { |
| + return nil, &errLeaseRefused{reason: hafresh.ReasonPoolIneligible} |
| + } |
| // A unit-backed row never reaches ExecBackend.Acquire, where the region |
| // HA classification lives: a born-HA host there is refused (it is not |
| // contained), asked of the exec half before the unit's own acquire. |
| @@ -470,6 +473,9 @@ func (b *SplitBackend) Seed(ctx context.Context, rt registry.Route) error { |
| return b.pick(rt).Seed(ctx, rt) |
| } |
| func (b *SplitBackend) Start(ctx context.Context, rt registry.Route) (Proc, string, error) { |
| + if !b.poolEligible(rt) { |
| + return nil, "", &errLeaseRefused{reason: hafresh.ReasonPoolIneligible} |
| + } |
| return b.pick(rt).Start(ctx, rt) |
| } |
| func (b *SplitBackend) NextDue(ctx context.Context, rt registry.Route) (int64, error) { |
| @@ -481,6 +487,9 @@ func (b *SplitBackend) HasSidecar(rt registry.Route) bool { return b.pick(rt).Ha |
| // unit side: systemd binds a unit tenant's canonical socket) is started |
| // with Start and gets the canonical handle. |
| func (b *SplitBackend) StartGen(ctx context.Context, rt registry.Route, n uint64, perGen bool) (Proc, Gen, error) { |
| + if !b.poolEligible(rt) { |
| + return nil, Gen{}, &errLeaseRefused{reason: hafresh.ReasonPoolIneligible} |
| + } |
| if g, ok := b.pick(rt).(GenBackend); ok { |
| return g.StartGen(ctx, rt, n, perGen) |
| } |
| @@ -603,3 +612,10 @@ func (b *SplitBackend) LiveVersion(host string) (string, error) { |
| } |
| return "", nil |
| } |
| + |
| +func (b *SplitBackend) poolEligible(rt registry.Route) bool { |
| + if gate, ok := b.Exec.(interface{ poolEligible(registry.Route) bool }); ok { |
| + return gate.poolEligible(rt) |
| + } |
| + return false |
| +} |
diff --git a/internal/activator/claim_instancekey_test.go b/internal/activator/claim_instancekey_test.go| index 22011e68a..e360055f6 100644 |
| --- a/internal/activator/claim_instancekey_test.go |
| +++ b/internal/activator/claim_instancekey_test.go |
| @@ -19,7 +19,7 @@ import ( |
| func TestEnsureClaimAdminTokenSyncsAPresentKeyBeforeItAnswers(t *testing.T) { |
| probe := probeInstanceKeySync(t) |
| const host = "claim-key.example" |
| - b := &ExecBackend{DataDir: t.TempDir()} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, DataDir: t.TempDir()} |
| rt := registry.Route{Host: host, Socket: "/run/carlos/claim-key.sock", DBPath: "/data/claim-key.db"} |
| envPath := filepath.Join(b.DataDir, host+".env") |
| body := "CARLOS_ADMIN_TOKEN=" + strings.Repeat("d", 64) + "\n" + InstanceKeyVar + "=" + strings.Repeat("A", 43) + "=\n" |
| @@ -64,7 +64,7 @@ func TestEnsureClaimAdminTokenSyncsAPresentKeyBeforeItAnswers(t *testing.T) { |
| // authorizer, and no file created. |
| func TestEnsureClaimAdminTokenProceedsWithNoOwnEnvFileWhenConfigSuppliesBoth(t *testing.T) { |
| const host = "claim-cfg.example" |
| - b := &ExecBackend{DataDir: t.TempDir()} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, DataDir: t.TempDir()} |
| rt := registry.Route{Host: host, Socket: "/run/carlos/claim-cfg.sock", DBPath: "/data/claim-cfg.db"} |
| cfg := "CARLOS_ADMIN_TOKEN=" + strings.Repeat("d", 64) + "\n" + InstanceKeyVar + "=configured\n" |
| if err := os.WriteFile(filepath.Join(b.DataDir, host+".config.env"), []byte(cfg), 0o600); err != nil { |
| @@ -87,7 +87,7 @@ func TestEnsureClaimAdminTokenProceedsWithNoOwnEnvFileWhenConfigSuppliesBoth(t * |
| // function has always promised. |
| func TestEnsureClaimAdminTokenMintsOnlyTheKeyWhenConfigSuppliesTheToken(t *testing.T) { |
| const host = "claim-cfgtok.example" |
| - b := &ExecBackend{DataDir: t.TempDir()} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, DataDir: t.TempDir()} |
| rt := registry.Route{Host: host, Socket: "/run/carlos/claim-cfgtok.sock", DBPath: "/data/claim-cfgtok.db"} |
| tok := strings.Repeat("d", 64) |
| if err := os.WriteFile(filepath.Join(b.DataDir, host+".config.env"), []byte("CARLOS_ADMIN_TOKEN="+tok+"\n"), 0o600); err != nil { |
diff --git a/internal/activator/claim_shape_rev2_shape_test.go b/internal/activator/claim_shape_rev2_shape_test.go| index 346ef479d..71b44c5b0 100644 |
| --- a/internal/activator/claim_shape_rev2_shape_test.go |
| +++ b/internal/activator/claim_shape_rev2_shape_test.go |
| @@ -39,7 +39,7 @@ func TestRev2ShapeIsolatedArgv(t *testing.T) { |
| } |
| func TestRev2ShapeClaimLaunchRoles(t *testing.T) { |
| - b := &ExecBackend{DataDir: t.TempDir()} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, DataDir: t.TempDir()} |
| if got, err := b.ClaimLaunchRoles(registry.Route{Host: "h.example"}); err != nil || len(got) != 1 || got[0] != "main" { |
| t.Fatalf("roles=%v err=%v", got, err) |
| } |
diff --git a/internal/activator/claim_shape_rev4_sidecar_error_test.go b/internal/activator/claim_shape_rev4_sidecar_error_test.go| index d3e8a617c..b8028a453 100644 |
| --- a/internal/activator/claim_shape_rev4_sidecar_error_test.go |
| +++ b/internal/activator/claim_shape_rev4_sidecar_error_test.go |
| @@ -17,14 +17,14 @@ func TestClaimLaunchShapeSidecarInspection(t *testing.T) { |
| rt := registry.Route{Host: host} |
| t.Run("proven absent", func(t *testing.T) { |
| - b := &ExecBackend{DataDir: t.TempDir()} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, DataDir: t.TempDir()} |
| if err := b.claimLaunchShape(rt); err != nil { |
| t.Fatalf("claimLaunchShape: %v", err) |
| } |
| }) |
| t.Run("present", func(t *testing.T) { |
| - b := &ExecBackend{DataDir: t.TempDir()} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, DataDir: t.TempDir()} |
| if err := os.WriteFile(filepath.Join(b.DataDir, host+"-sidecar.env"), nil, 0o600); err != nil { |
| t.Fatal(err) |
| } |
| @@ -34,7 +34,7 @@ func TestClaimLaunchShapeSidecarInspection(t *testing.T) { |
| }) |
| t.Run("symlink loop", func(t *testing.T) { |
| - b := &ExecBackend{DataDir: t.TempDir()} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, DataDir: t.TempDir()} |
| path := filepath.Join(b.DataDir, host+"-sidecar.env") |
| if err := os.Symlink(filepath.Base(path), path); err != nil { |
| t.Fatal(err) |
| @@ -61,7 +61,7 @@ func TestClaimLaunchShapeSidecarInspection(t *testing.T) { |
| if _, err := os.Stat(path); !errors.Is(err, syscall.EACCES) { |
| t.Skipf("fixture cannot produce EACCES: %v", err) |
| } |
| - b := &ExecBackend{DataDir: dataDir} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, DataDir: dataDir} |
| if err := b.claimLaunchShape(rt); !errors.Is(err, syscall.EACCES) { |
| t.Fatalf("claimLaunchShape error = %v, want EACCES", err) |
| } |
| @@ -69,7 +69,7 @@ func TestClaimLaunchShapeSidecarInspection(t *testing.T) { |
| } |
| func TestClaimLaunchRolesPropagatesInjectedInspectionErrors(t *testing.T) { |
| - b := &ExecBackend{DataDir: t.TempDir()} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, DataDir: t.TempDir()} |
| for _, want := range []error{syscall.EACCES, syscall.EIO, syscall.ELOOP} { |
| t.Run(want.Error(), func(t *testing.T) { |
| roles, err := b.claimLaunchRoles(registry.Route{Host: "claim-sidecar.example"}, func(string) (os.FileInfo, error) { |
| @@ -84,7 +84,7 @@ func TestClaimLaunchRolesPropagatesInjectedInspectionErrors(t *testing.T) { |
| func TestEnsureClaimAdminTokenInspectsSidecarBeforeAuthorize(t *testing.T) { |
| const host = "claim-sidecar.example" |
| - b := &ExecBackend{DataDir: t.TempDir()} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, DataDir: t.TempDir()} |
| path := filepath.Join(b.DataDir, host+"-sidecar.env") |
| if err := os.Symlink(filepath.Base(path), path); err != nil { |
| t.Fatal(err) |
diff --git a/internal/activator/claim_snapshot_test.go b/internal/activator/claim_snapshot_test.go| index 779e002ef..feed11bb8 100644 |
| --- a/internal/activator/claim_snapshot_test.go |
| +++ b/internal/activator/claim_snapshot_test.go |
| @@ -16,7 +16,7 @@ func TestClaimSnapshotCarriesTheEffectiveSize(t *testing.T) { |
| t.Parallel() |
| const host = "snapshot-size.example.com" |
| data, opt := t.TempDir(), t.TempDir() |
| - b := &ExecBackend{DataDir: data, OptDir: opt, Tier: func(registry.Route) cgroup.Limit { return cgroup.TierChildren }} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, DataDir: data, OptDir: opt, Tier: func(registry.Route) cgroup.Limit { return cgroup.TierChildren }} |
| stageLiveUnderAccount(t, opt, host, "bab", "v1", "jam") |
| if err := os.WriteFile(filepath.Join(data, host+".env"), []byte("CARLOS_ADMIN_TOKEN="+strings.Repeat("ab", 32)+"\n"), 0o600); err != nil { |
| t.Fatal(err) |
diff --git a/internal/activator/claimspawn_kernel_linux_test.go b/internal/activator/claimspawn_kernel_linux_test.go| index 65bf09bee..28754a35d 100644 |
| --- a/internal/activator/claimspawn_kernel_linux_test.go |
| +++ b/internal/activator/claimspawn_kernel_linux_test.go |
| @@ -151,7 +151,7 @@ func cgroupInode(t *testing.T, path string) uint64 { |
| // the tier written again, and stays up. |
| func killHostRespawn(t *testing.T, manager *cgroup.Manager, build func() *exec.Cmd) { |
| const host = "killhost.claimspawn.example" |
| - b := &ExecBackend{Cgroups: manager} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, Cgroups: manager} |
| rt := registry.Route{Host: host} |
| dir := filepath.Join(manager.Root(), cgroup.ExecName(host)) |
| var last uint64 |
| @@ -191,7 +191,7 @@ func killHostRespawn(t *testing.T, manager *cgroup.Manager, build func() *exec.C |
| // delegated, and g1 is untouched by every kill. |
| func killSidecarRespawn(t *testing.T, manager *cgroup.Manager, build func() *exec.Cmd) { |
| const host = "killsidecar.claimspawn.example" |
| - b := &ExecBackend{Cgroups: manager, GenContainment: true, DataDir: t.TempDir(), OptDir: t.TempDir()} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, Cgroups: manager, GenContainment: true, DataDir: t.TempDir(), OptDir: t.TempDir()} |
| rt := registry.Route{Host: host, Kind: "instance", DBPath: provision.DefaultDBPath(b.DataDir, host), |
| Socket: filepath.Join(provision.SocketDir, host+".sock")} |
| parent := filepath.Join(manager.Root(), cgroup.ExecName(host)) |
diff --git a/internal/activator/cmdunit_test.go b/internal/activator/cmdunit_test.go| index 60479b81b..55a271952 100644 |
| --- a/internal/activator/cmdunit_test.go |
| +++ b/internal/activator/cmdunit_test.go |
| @@ -32,7 +32,7 @@ func (s *syncBuffer) Write(p []byte) (int, error) { |
| func (s *syncBuffer) String() string { s.mu.Lock(); defer s.mu.Unlock(); return s.b.String() } |
| func TestCmdVarsComposeTheRunEnvironment(t *testing.T) { |
| - b := &ExecBackend{Region: "ie"} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, Region: "ie"} |
| rt := registry.Route{Host: "h.example.com"} |
| file := map[string]string{ |
| "APP_KEY": "k", "CARLOS_ADMIN_TOKEN": "tok", "CARLOS_CONTROL_SOCKET": "/x", "CARLOS_PURGE": "header", |
diff --git a/internal/activator/config_gate_test.go b/internal/activator/config_gate_test.go| index c07c6ed62..a3d382190 100644 |
| --- a/internal/activator/config_gate_test.go |
| +++ b/internal/activator/config_gate_test.go |
| @@ -22,7 +22,7 @@ import ( |
| func TestExecBackendAcquireRefusesBeforeTheLease(t *testing.T) { |
| var asked []registry.Route |
| boom := errors.New("cannot open sealed config") |
| - b := &ExecBackend{ConfigGate: func(_ context.Context, rt registry.Route) error { |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, ConfigGate: func(_ context.Context, rt registry.Route) error { |
| asked = append(asked, rt) |
| return boom |
| }} |
| @@ -197,7 +197,7 @@ func TestWorkerRespawnProceedsWhenTheConfigGateAllows(t *testing.T) { |
| // is exempt. |
| func TestSplitBackendGatesWhatDispatchSendsToExec(t *testing.T) { |
| var asked []string |
| - exec := &ExecBackend{ConfigGate: func(_ context.Context, rt registry.Route) error { |
| + exec := &ExecBackend{ServedPools: eligibleSharedPools, ConfigGate: func(_ context.Context, rt registry.Route) error { |
| asked = append(asked, rt.Host) |
| return errors.New("no key") |
| }} |
diff --git a/internal/activator/coordinator_test.go b/internal/activator/coordinator_test.go| index 10d7ca048..4859795fb 100644 |
| --- a/internal/activator/coordinator_test.go |
| +++ b/internal/activator/coordinator_test.go |
| @@ -324,7 +324,7 @@ func TestCoordinatorHeldAuthorityLookup(t *testing.T) { |
| return replicas.CoordinatorReply{Lease: replicas.Coordinator{Term: "term", Box: "box", BootID: "boot"}, RemainingMS: replicas.CoordinatorTTL.Milliseconds()}, nil |
| }, nil) |
| c.now = func() time.Time { return now } |
| - b := &ExecBackend{Coordination: c} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, Coordination: c} |
| id := replicas.Identity{Account: "a", App: "shop", Host: "shop.example.com", Incarnation: "one"} |
| if c.Held(id) != nil || b.coordinationAuthority(id.Host) != nil || calls != 0 { |
| t.Fatal("lookup acquired authority") |
| @@ -363,7 +363,7 @@ func TestCoordinatorHeldAuthorityLookup(t *testing.T) { |
| if c.Held(id) != nil || b.coordinationAuthority(id.Host) != nil { |
| t.Fatal("closed client handed off authority") |
| } |
| - if (&ExecBackend{}).coordinationAuthority(id.Host) != nil { |
| + if (&ExecBackend{ServedPools: eligibleSharedPools}).coordinationAuthority(id.Host) != nil { |
| t.Fatal("unwired backend granted authority") |
| } |
| } |
diff --git a/internal/activator/demo_durability_test.go b/internal/activator/demo_durability_test.go| index 5998f4e88..00a7ca53b 100644 |
| --- a/internal/activator/demo_durability_test.go |
| +++ b/internal/activator/demo_durability_test.go |
| @@ -85,7 +85,7 @@ func TestDemoDatabaseSurvivesLocalRestart(t *testing.T) { |
| } |
| // Separate backends model sleep/wake, an agent restart and a binary update. |
| for i := 0; i < 3; i++ { |
| - next := &ExecBackend{Cfg: b.Cfg, DataDir: b.DataDir, OptDir: b.OptDir, FilesStore: spy} |
| + next := &ExecBackend{ServedPools: eligibleSharedPools, Cfg: b.Cfg, DataDir: b.DataDir, OptDir: b.OptDir, FilesStore: spy} |
| rt.Version = "v2" |
| if fresh, err = next.Restore(ctx, rt); err != nil || fresh { |
| t.Fatalf("restart %d: fresh=%v err=%v", i, fresh, err) |
| @@ -608,7 +608,7 @@ func TestDemoDatabaseInitializationRetry(t *testing.T) { |
| t.Errorf("pending initialization lost: %v", err) |
| } |
| // A new backend has no attempt-local memory from the failed boot. |
| - next := &ExecBackend{Cfg: b.Cfg, DataDir: b.DataDir, OptDir: b.OptDir, FilesStore: store} |
| + next := &ExecBackend{ServedPools: eligibleSharedPools, Cfg: b.Cfg, DataDir: b.DataDir, OptDir: b.OptDir, FilesStore: store} |
| fresh, err := next.Restore(ctx, rt) |
| if err != nil || !fresh { |
| t.Fatalf("retry: fresh=%v err=%v", fresh, err) |
diff --git a/internal/activator/genbackend_test.go b/internal/activator/genbackend_test.go| index ade597785..dba255ec7 100644 |
| --- a/internal/activator/genbackend_test.go |
| +++ b/internal/activator/genbackend_test.go |
| @@ -241,7 +241,7 @@ func TestExecBackendStartStagedClearsALeftoverCanonicalLink(t *testing.T) { |
| // the column still wins over the live tier. |
| func TestGenTierPrefersTheSizeColumnOverTheBuild(t *testing.T) { |
| t.Parallel() |
| - b := &ExecBackend{ |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, |
| Tier: func(registry.Route) cgroup.Limit { return cgroup.TierChildren }, |
| TierOf: func(registry.Route, string) cgroup.Limit { return cgroup.TierDefault }, |
| } |
diff --git a/internal/activator/genparent_kernel_linux_test.go b/internal/activator/genparent_kernel_linux_test.go| index 57e7437e5..bb60b642a 100644 |
| --- a/internal/activator/genparent_kernel_linux_test.go |
| +++ b/internal/activator/genparent_kernel_linux_test.go |
| @@ -148,7 +148,7 @@ func expectCappedGen(t *testing.T, host, parent, child string, cmd *exec.Cmd) { |
| // raised, as a swap's overlap does. |
| func genParentSiblingControl(t *testing.T, manager *cgroup.Manager) { |
| const host = "genparent-ok.example" |
| - b := &ExecBackend{Cgroups: manager, GenContainment: true, DataDir: t.TempDir(), OptDir: t.TempDir()} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, Cgroups: manager, GenContainment: true, DataDir: t.TempDir(), OptDir: t.TempDir()} |
| rt := registry.Route{Host: host, Kind: "instance", DBPath: provision.DefaultDBPath(b.DataDir, host), |
| Socket: filepath.Join(provision.SocketDir, host+".sock")} |
| parent := filepath.Join(manager.Root(), cgroup.ExecName(host)) |
diff --git a/internal/activator/group_admission_test.go b/internal/activator/group_admission_test.go| index 0c1109ba6..375cc9015 100644 |
| --- a/internal/activator/group_admission_test.go |
| +++ b/internal/activator/group_admission_test.go |
| @@ -46,7 +46,7 @@ func TestPreAdmissionNonHTTP(t *testing.T) { |
| if b.acquires != 0 || b.restores != 0 || len(b.events()) != 0 { |
| t.Fatalf("work happened: %+v", b.events()) |
| } |
| - eb := &ExecBackend{TenantStartAllowed: func(registry.Route) bool { return false }, ConfigGate: func(context.Context, registry.Route) error { return errors.New("unexpected config access") }} |
| + eb := &ExecBackend{ServedPools: eligibleSharedPools, TenantStartAllowed: func(registry.Route) bool { return false }, ConfigGate: func(context.Context, registry.Route) error { return errors.New("unexpected config access") }} |
| if _, err := eb.Acquire(t.Context(), rt); !errors.Is(err, ErrTenantAdmission) { |
| t.Fatalf("backend acquire %v", err) |
| } |
| @@ -111,7 +111,7 @@ func TestDrainHealthHeldReuse(t *testing.T) { |
| func TestAdmissionLaunchRecheck(t *testing.T) { |
| allowed := true |
| - b := &ExecBackend{TenantStartAllowed: func(registry.Route) bool { return allowed }} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, TenantStartAllowed: func(registry.Route) bool { return allowed }} |
| rt := testRoute("shop.example.com") |
| ctx := withTenantAdmission(t.Context(), func() error { return b.tenantStartRefusal(rt) }) |
| g := b.launchGate(ctx, rt.Host) |
diff --git a/internal/activator/haadopt.go b/internal/activator/haadopt.go| index a0311d723..2790e9169 100644 |
| --- a/internal/activator/haadopt.go |
| +++ b/internal/activator/haadopt.go |
| @@ -40,11 +40,14 @@ func adoptionPair(rt registry.Route) registry.Pair { |
| } |
| func (b *ExecBackend) adoptionCurrent(ctx context.Context, rt registry.Route, req Adoption) error { |
| + if !b.poolEligible(rt) { |
| + return &errLeaseRefused{reason: hafresh.ReasonPoolIneligible} |
| + } |
| cur, err := b.Registry.Get(rt.Host) |
| if err != nil { |
| return err |
| } |
| - if cur == nil || adoptionPair(*cur) != req.Pair || cur.Account != rt.Account || cur.App != rt.App || cur.DBPath != rt.DBPath || cur.Kind != rt.Kind || cur.HoldOp != "" || cur.ImportGate != "" || cur.Replica || cur.Tunnel != "" || cur.Status != "ready" { |
| + if cur == nil || adoptionPair(*cur) != req.Pair || cur.Account != rt.Account || cur.Pool != rt.Pool || cur.App != rt.App || cur.DBPath != rt.DBPath || cur.Kind != rt.Kind || cur.HoldOp != "" || cur.ImportGate != "" || cur.Replica || cur.Tunnel != "" || cur.Status != "ready" { |
| return registry.ErrHAChanged |
| } |
| e, ha, err := b.isHA(ctx, *cur) |
| @@ -113,6 +116,9 @@ func (b *ExecBackend) adoptionWake(ctx context.Context, host string, cached ...r |
| // ordinary wakes; no activator mutex is held during registry or object I/O. |
| func (a *Service) AdoptHost(ctx context.Context, rt registry.Route, req Adoption) (AdoptResult, error) { |
| b := adoptionBackend(a.backend, rt) |
| + if b != nil && !b.poolEligible(rt) { |
| + return Deferred, &errLeaseRefused{reason: hafresh.ReasonPoolIneligible} |
| + } |
| if b == nil || b.Registry == nil || haLegacyRoute(rt) || req.Departure == "" || req.Lifetime == "" || req.Ref == "" || req.IID == "" || !b.self().Complete() { |
| return Deferred, registry.ErrHAChanged |
| } |
| @@ -297,7 +303,7 @@ func (a *Service) AdoptHost(ctx context.Context, rt registry.Route, req Adoption |
| return Deferred, err |
| } |
| ctx = context.WithValue(ctx, adoptionCauseKey{}, req.Ref) |
| - proofs := hafresh.Proofs{SameBoxEmpty: b.sameBoxEmpty(ctx, rt), OwnerTerminated: b.ownerTerminated(ctx, rt)} |
| + proofs := hafresh.Proofs{LocalEligible: func() bool { return b.poolEligible(rt) }, SameBoxEmpty: b.sameBoxEmpty(ctx, rt), OwnerTerminated: b.ownerTerminated(ctx, rt)} |
| if b.TerminationProofs != nil { |
| adapter := *b.TerminationProofs |
| adapter.Observe = func(iid string, gone bool, err error) { b.reportTakeover(ctx, rt, iid, gone, err) } |
diff --git a/internal/activator/haduties.go b/internal/activator/haduties.go| index f6af19d9d..91a0bb2ff 100644 |
| --- a/internal/activator/haduties.go |
| +++ b/internal/activator/haduties.go |
| @@ -44,13 +44,16 @@ type DutyInput struct { |
| } |
| func DecideDuty(i DutyInput) DutyDecision { |
| + if i.LocalDenied { |
| + return Defer |
| + } |
| if !i.HA { |
| return DutyAttempt |
| } |
| if i.OwnedAwake { |
| return DutyAttempt |
| } |
| - if i.LocalDenied || i.Lifetime == "" || i.Self.Ref == "" || i.Self.IID == "" { |
| + if i.Lifetime == "" || i.Self.Ref == "" || i.Self.IID == "" { |
| return Defer |
| } |
| if i.Suppressed { |
| @@ -195,6 +198,10 @@ func (a *Service) saveDuty(ctx context.Context, host, life string, old DutyState |
| func (a *Service) dutyInput(ctx context.Context, rt registry.Route) (DutyInput, DutyState, error) { |
| i := DutyInput{Host: rt.Host} |
| + if gate, ok := a.backend.(interface{ poolEligible(registry.Route) bool }); ok && !gate.poolEligible(rt) { |
| + i.LocalDenied = true |
| + return i, DutyState{}, nil |
| + } |
| if haLegacyRoute(rt) { |
| return i, DutyState{}, nil |
| } |
diff --git a/internal/activator/haduties_test.go b/internal/activator/haduties_test.go| index 70435f69f..626730bc7 100644 |
| --- a/internal/activator/haduties_test.go |
| +++ b/internal/activator/haduties_test.go |
| @@ -41,7 +41,7 @@ func TestHADutyOwnerTable(t *testing.T) { |
| {"peer suppressed", func(i *DutyInput) { i.Suppressed = true }, Defer}, |
| {"HA switch off", func(i *DutyInput) { i.ViewKnown = false; i.Basis = DutyAdopted }, DutyAttempt}, |
| {"missing lifetime", func(i *DutyInput) { i.Lifetime = "" }, Defer}, |
| - {"legacy", func(i *DutyInput) { i.HA = false; i.LocalDenied = true }, DutyAttempt}, |
| + {"legacy local denied", func(i *DutyInput) { i.HA = false; i.LocalDenied = true }, Defer}, |
| } { |
| t.Run(tc.name, func(t *testing.T) { |
| in := base |
| @@ -392,7 +392,7 @@ func TestDutyAcquireRestrictionOnlyExpiryEquality(t *testing.T) { |
| life := haFixOf(s.b).lifetime |
| putLockFor(t, s.b, s.rt, leaseBody(t, hafresh.OwnerFor(hafresh.Self{Ref: "a", IID: "i-a"}, 1, true), now)) |
| proofs, calls := 0, 0 |
| - p := hafresh.Proofs{SameBoxEmpty: func() (bool, error) { proofs++; return true, nil }} |
| + p := hafresh.Proofs{LocalEligible: func() bool { return true }, SameBoxEmpty: func() (bool, error) { proofs++; return true, nil }} |
| acquire := func() (*lease.Held, error) { |
| return lease.AcquireHAForDuty(context.Background(), s.fx.Bucket, s.b.Cfg.hibernatePrefix(s.rt.Host), "", hafresh.Marker{Lifetime: life}, p, func(v hafresh.View) error { |
| calls++ |
diff --git a/internal/activator/hasuspectholder_test.go b/internal/activator/hasuspectholder_test.go| index 1d871f68b..28a1fe4f2 100644 |
| --- a/internal/activator/hasuspectholder_test.go |
| +++ b/internal/activator/hasuspectholder_test.go |
| @@ -108,7 +108,7 @@ func TestSuspectHolderThresholdAndHourly(t *testing.T) { |
| } |
| func TestSuspectHolderGroupingAndLimit(t *testing.T) { |
| - b := &ExecBackend{} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools} |
| now := time.Now() |
| start := now |
| b.suspectHolders.now = func() time.Time { return now } |
| @@ -182,7 +182,7 @@ func TestSuspectHolderRecoveryClears(t *testing.T) { |
| func TestSuspectHolderResetOwnerAndGap(t *testing.T) { |
| for _, changeOwner := range []bool{false, true} { |
| t.Run(fmt.Sprint(changeOwner), func(t *testing.T) { |
| - b := &ExecBackend{} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools} |
| now := time.Now() |
| start := now |
| b.suspectHolders.now = func() time.Time { return now } |
| @@ -212,7 +212,7 @@ func TestSuspectHolderResetOwnerAndGap(t *testing.T) { |
| } |
| func TestSuspectHolderFinalizerExcludedAndConfirmedClear(t *testing.T) { |
| - b := &ExecBackend{} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools} |
| now := time.Now() |
| b.suspectHolders.now = func() time.Time { return now } |
| var pages suspectTestPages |
| @@ -267,7 +267,7 @@ func TestSuspectHolderSameBox(t *testing.T) { |
| } |
| func TestSuspectHolderConcurrentSpentContext(t *testing.T) { |
| - b := &ExecBackend{} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools} |
| now := time.Now() |
| b.suspectHolders.now = func() time.Time { return now } |
| var pages suspectTestPages |
| @@ -288,7 +288,7 @@ func TestSuspectHolderConcurrentSpentContext(t *testing.T) { |
| } |
| func TestSuspectHolderNilPageStillCounts(t *testing.T) { |
| - b := &ExecBackend{} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools} |
| now := time.Now() |
| b.suspectHolders.now = func() time.Time { return now } |
| rt := registry.Route{Host: "host.example.com"} |
| @@ -340,7 +340,7 @@ func TestSuspectHolderAcquireBetweenRefusals(t *testing.T) { |
| } |
| func TestSuspectHolderPageListsOnlySustainedRecentRefusals(t *testing.T) { |
| - b := &ExecBackend{} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools} |
| now := time.Now() |
| start := now |
| b.suspectHolders.now = func() time.Time { return now } |
diff --git a/internal/activator/hatakeover_page_test.go b/internal/activator/hatakeover_page_test.go| index d3c6bc4cc..de4f0ae77 100644 |
| --- a/internal/activator/hatakeover_page_test.go |
| +++ b/internal/activator/hatakeover_page_test.go |
| @@ -41,7 +41,7 @@ func TestTakeoverPageHourlyPerHost(t *testing.T) { |
| // send gets a fresh, bounded context of its own. |
| func TestTakeoverPageSurvivesSpentScanContext(t *testing.T) { |
| var got []string |
| - b := &ExecBackend{Page: func(ctx context.Context, level, subject, body string) error { |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, Page: func(ctx context.Context, level, subject, body string) error { |
| if err := ctx.Err(); err != nil { |
| return err |
| } |
diff --git a/internal/activator/hawake.go b/internal/activator/hawake.go| index beec9d69a..5026c4ae7 100644 |
| --- a/internal/activator/hawake.go |
| +++ b/internal/activator/hawake.go |
| @@ -399,7 +399,7 @@ func (b *ExecBackend) acquireClassified(ctx context.Context, rt registry.Route) |
| } |
| } |
| - proofs := hafresh.Proofs{SameBoxEmpty: b.sameBoxEmpty(ctx, rt), OwnerTerminated: b.ownerTerminated(ctx, rt)} |
| + proofs := hafresh.Proofs{LocalEligible: func() bool { return b.poolEligible(rt) }, SameBoxEmpty: b.sameBoxEmpty(ctx, rt), OwnerTerminated: b.ownerTerminated(ctx, rt)} |
| if b.TerminationProofs != nil { |
| adapter := *b.TerminationProofs |
| adapter.Observe = func(iid string, gone bool, err error) { b.reportTakeover(ctx, rt, iid, gone, err) } |
| @@ -436,6 +436,9 @@ func (b *ExecBackend) haAcquired(host string) (haWake, bool) { |
| // co-spawned sidecar, a seed): a layout change mid-life refuses the next |
| // spawn instead of running it uncontained. |
| func (b *ExecBackend) haSpawnGate(rt registry.Route) error { |
| + if !b.poolEligible(rt) { |
| + return &errLeaseRefused{reason: hafresh.ReasonPoolIneligible} |
| + } |
| if err := b.tenantStartRefusal(rt); err != nil { |
| return err |
| } |
diff --git a/internal/activator/instancekey_delivery_test.go b/internal/activator/instancekey_delivery_test.go| index 627a0724f..778c3177b 100644 |
| --- a/internal/activator/instancekey_delivery_test.go |
| +++ b/internal/activator/instancekey_delivery_test.go |
| @@ -58,7 +58,7 @@ func TestEnsureInstanceKeyAsksTheBucketBeforeItMints(t *testing.T) { |
| {"an own key: present, nothing asked", tok + InstanceKeyVar + "=" + strings.Repeat("K", 43) + "=\n", "", &bucketKey{key: "key-A"}, InstanceKeyPresent, false, 0}, |
| } { |
| t.Run(tc.name, func(t *testing.T) { |
| - b := &ExecBackend{DataDir: t.TempDir()} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, DataDir: t.TempDir()} |
| if tc.bucket != nil { |
| b.ConfiguredKey = tc.bucket.read |
| } |
| @@ -104,7 +104,7 @@ func TestEnsureInstanceKeyAsksTheBucketBeforeItMints(t *testing.T) { |
| // The mint's bucket read is bounded by configReadTimeout and by the |
| // launch's own context, whichever ends first. |
| func TestEnsureInstanceKeyBoundsTheBucketRead(t *testing.T) { |
| - b := &ExecBackend{DataDir: t.TempDir()} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, DataDir: t.TempDir()} |
| var deadline time.Time |
| b.ConfiguredKey = func(ctx context.Context, _ registry.Route) (string, error) { |
| deadline, _ = ctx.Deadline() |
| @@ -190,7 +190,7 @@ func TestFirstStartWaitsForTheConfiguredKey(t *testing.T) { |
| // lock every other row's mint waits on. Host A's read blocks until the |
| // test releases it; host B mints meanwhile; A then mints too. |
| func TestASlowBucketReadForOneHostDoesNotBlockAnothersMint(t *testing.T) { |
| - b := &ExecBackend{DataDir: t.TempDir()} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, DataDir: t.TempDir()} |
| release := make(chan struct{}) |
| entered := make(chan struct{}) |
| b.ConfiguredKey = func(ctx context.Context, rt registry.Route) (string, error) { |
| @@ -283,7 +283,7 @@ func TestAKeyThatAppearsDuringTheBucketReadIsKept(t *testing.T) { |
| }, InstanceKeyFromConfig}, |
| } { |
| t.Run(tc.name, func(t *testing.T) { |
| - b := &ExecBackend{DataDir: t.TempDir()} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, DataDir: t.TempDir()} |
| rt := registry.Route{Host: "shop.example.com", Kind: "instance"} |
| own := filepath.Join(b.DataDir, rt.Host+".env") |
| if err := os.WriteFile(own, []byte("X=1\n"), 0o600); err != nil { |
| @@ -329,7 +329,7 @@ func TestAMintThatLooksNextOnlyUnderTheLockDefers(t *testing.T) { |
| {"a keyless file appears after the backfill's first read", "", "X=1\n", false}, |
| } { |
| t.Run(tc.name, func(t *testing.T) { |
| - b := &ExecBackend{DataDir: t.TempDir()} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, DataDir: t.TempDir()} |
| bucket := &bucketKey{} |
| b.ConfiguredKey = bucket.read |
| rt := registry.Route{Host: "shop.example.com", Kind: "instance"} |
diff --git a/internal/activator/instancekey_test.go b/internal/activator/instancekey_test.go| index 3f9d64f0e..6cccc2469 100644 |
| --- a/internal/activator/instancekey_test.go |
| +++ b/internal/activator/instancekey_test.go |
| @@ -175,7 +175,7 @@ func TestEnsureInstanceKeyDefersToTheRenderedConfiguration(t *testing.T) { |
| } |
| func TestBackfillInstanceKeyAppendsOnlyToAnExistingEnvFile(t *testing.T) { |
| - b := &ExecBackend{DataDir: t.TempDir()} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, DataDir: t.TempDir()} |
| fresh := registry.Route{Host: "new.example.com", Socket: "/run/carlos/new.sock"} |
| got, err := b.BackfillInstanceKey(t.Context(), fresh) |
| if err != nil || got != InstanceKeyNoEnvFile { |
| @@ -324,7 +324,7 @@ func TestEnsureInstanceKeyRedoesAFailedSyncBeforeReportingSuccess(t *testing.T) |
| // Ruling 26: a replica row is never minted a key, on any path; the only |
| // key it may hold is its home's (replicaKeyGate). |
| func TestReplicaRowsGetNoPlatformKey(t *testing.T) { |
| - b := &ExecBackend{DataDir: t.TempDir()} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, DataDir: t.TempDir()} |
| rt := registry.Route{Host: "shop-au.example.com", Kind: "instance", Socket: "/run/carlos/shop-au.sock", Replica: true} |
| envPath := filepath.Join(b.DataDir, rt.Host+".env") |
| if err := os.WriteFile(envPath, []byte("CARLOS_ADMIN_TOKEN=t\n"), 0o600); err != nil { |
| @@ -374,7 +374,7 @@ func TestEnsureInstanceKeyRefusesToFollowASymlink(t *testing.T) { |
| }}, |
| } { |
| t.Run(tc.name, func(t *testing.T) { |
| - b := &ExecBackend{DataDir: t.TempDir()} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, DataDir: t.TempDir()} |
| rt := registry.Route{Host: "shop.example.com", Socket: "/run/carlos/shop.sock"} |
| target := filepath.Join(t.TempDir(), "someone-elses-file") |
| if err := os.WriteFile(target, []byte(tc.target), tc.mode); err != nil { |
| @@ -577,7 +577,7 @@ func TestEnsureInstanceKeyOpenRefusesALinkSwappedInAfterTheRead(t *testing.T) { |
| }}, |
| } { |
| t.Run(tc.name, func(t *testing.T) { |
| - b := &ExecBackend{DataDir: t.TempDir()} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, DataDir: t.TempDir()} |
| rt := registry.Route{Host: "shop.example.com", Socket: "/run/carlos/shop.sock"} |
| path := filepath.Join(b.DataDir, rt.Host+".env") |
| if err := os.WriteFile(path, []byte(tc.own), 0o600); err != nil { |
| @@ -1013,7 +1013,7 @@ func TestBackfillAndAStartsMintRacingOnOneHostWriteOneKey(t *testing.T) { |
| const rounds = 40 |
| tok := "CARLOS_ADMIN_TOKEN=" + strings.Repeat("b", 64) + "\n" |
| for i := range rounds { |
| - b := &ExecBackend{DataDir: t.TempDir()} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, DataDir: t.TempDir()} |
| b.ConfiguredKey = func(ctx context.Context, _ registry.Route) (string, error) { |
| select { |
| case <-time.After(5 * time.Millisecond): // a slow bucket that sets no key |
diff --git a/internal/activator/keyadoption_test.go b/internal/activator/keyadoption_test.go| index e4388ae98..3a00a4221 100644 |
| --- a/internal/activator/keyadoption_test.go |
| +++ b/internal/activator/keyadoption_test.go |
| @@ -30,7 +30,7 @@ func newAdoptionFixture(t *testing.T, rt registry.Route, tok, key, source string |
| Publish: func(rec []byte) { f.published = append(f.published, rec) }, |
| } |
| f.mux = http.NewServeMux() |
| - (&ExecBackend{}).MountInstanceKeyAdoption(f.mux, rt, func() (string, error) { return tok, nil }, |
| + (&ExecBackend{ServedPools: eligibleSharedPools}).MountInstanceKeyAdoption(f.mux, rt, func() (string, error) { return tok, nil }, |
| func() (AdoptionLaunch, bool) { return f.launch, f.hasLaunch }) |
| return f |
| } |
diff --git a/internal/activator/leaseidentity_test.go b/internal/activator/leaseidentity_test.go| index a1abb184f..d058e1e56 100644 |
| --- a/internal/activator/leaseidentity_test.go |
| +++ b/internal/activator/leaseidentity_test.go |
| @@ -44,7 +44,7 @@ func TestExecBackendLeaseIdentityDefaultsToTheProcess(t *testing.T) { |
| defer ref.Release(ctx) |
| wantOwner, refExpiry := lockOf(t, fx, "ref.example.com") |
| - plain := &ExecBackend{Cfg: cfg, DataDir: t.TempDir(), OptDir: t.TempDir()} |
| + plain := &ExecBackend{ServedPools: eligibleSharedPools, Cfg: cfg, DataDir: t.TempDir(), OptDir: t.TempDir()} |
| l, err := plain.Acquire(ctx, registry.Route{Host: "shop.example.com", Kind: "instance"}) |
| if err != nil { |
| t.Fatal(err) |
| @@ -62,7 +62,7 @@ func TestExecBackendLeaseIdentityDefaultsToTheProcess(t *testing.T) { |
| } |
| id := hafresh.Self{Ref: "pi-1", IID: "i-pi-1", Account: "123456789012", Region: "eu-west-1", Boot: "boot-pi-1"} |
| - named := &ExecBackend{Cfg: cfg, DataDir: t.TempDir(), OptDir: t.TempDir(), LeaseIdentity: &id, LeaseTTL: 30 * time.Second} |
| + named := &ExecBackend{ServedPools: eligibleSharedPools, Cfg: cfg, DataDir: t.TempDir(), OptDir: t.TempDir(), LeaseIdentity: &id, LeaseTTL: 30 * time.Second} |
| before := time.Now() |
| l2, err := named.Acquire(ctx, registry.Route{Host: "cafe.example.com", Kind: "instance"}) |
| if err != nil { |
diff --git a/internal/activator/pools_test.go b/internal/activator/pools_test.go| new file mode 100644 |
| index 000000000..f7e3dfe5d |
| --- /dev/null |
| +++ b/internal/activator/pools_test.go |
| @@ -0,0 +1,132 @@ |
| +package activator |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/edgesfile" |
| + "github.com/carlosframework/platform/internal/hafresh" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +func TestAcquireHAPoolEligibility(t *testing.T) { |
| + for _, state := range []string{"absent", "clean", "unclean", "lifted", "own expired", "foreign terminated", "unexpired", "stale non-HA", "legacy row"} { |
| + t.Run(state, func(t *testing.T) { |
| + makeBackend := haBackend |
| + if state == "stale non-HA" { |
| + makeBackend = haBackendIndexed |
| + } |
| + b, rt := makeBackend(t, "shop.example.com") |
| + rt.Pool = "ha" |
| + b.ServedPools = func() edgesfile.PoolEvidence { return edgesfile.PoolEvidence(`["cohort1"]`) } |
| + switch state { |
| + case "clean", "unclean": |
| + putLockFor(t, b, rt, markerBody(t, "b", "i-b", haFixOf(b).lifetime, 0, state == "clean")) |
| + case "lifted": |
| + putLockFor(t, b, rt, leaseBody(t, "moved:lifted", time.Unix(0, 0))) |
| + case "own expired": |
| + putLockFor(t, b, rt, leaseBody(t, hafresh.OwnerFor(hafresh.Self{Ref: "a", IID: "i-a"}, 1, true), time.Now().Add(-time.Hour))) |
| + case "foreign terminated", "unexpired": |
| + expires := time.Now().Add(-time.Hour) |
| + if state == "unexpired" { |
| + expires = time.Now().Add(time.Hour) |
| + } |
| + putLockFor(t, b, rt, leaseBody(t, hafresh.OwnerFor(hafresh.Self{Ref: "b", IID: "i-b"}, 1, true), expires)) |
| + case "legacy row": |
| + rt.Provisioned = false |
| + } |
| + terms := 0 |
| + b.OwnerTerminated = func(context.Context, string) (bool, error) { terms++; return true, nil } |
| + l, err := b.Acquire(context.Background(), rt) |
| + if l != nil { |
| + l.Release(context.Background()) |
| + } |
| + var refused *errLeaseRefused |
| + if !errors.As(err, &refused) || refused.reason != hafresh.ReasonPoolIneligible { |
| + t.Errorf("acquire: %v", err) |
| + } |
| + if lockRequests(t, b, rt) != 0 || terms != 0 || haFixOf(b).restores != 0 || spawns(b) != 0 || recordGets(b) != 0 { |
| + t.Fatalf("refusal did work: requests=%v terms=%d restores=%d spawns=%d records=%d", haFixOf(b).fx.Requests(), terms, haFixOf(b).restores, spawns(b), recordGets(b)) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestPoolSpawnAndDutyAdmission(t *testing.T) { |
| + b, rt := haBackend(t, "shop.example.com") |
| + b.ServedPools = func() edgesfile.PoolEvidence { return edgesfile.PoolEvidence(`[]`) } |
| + if err := b.haSpawnGate(rt); err == nil { |
| + t.Fatal("spawn allowed after withdrawal") |
| + } |
| + for _, ha := range []bool{false, true} { |
| + if DecideDuty(DutyInput{HA: ha, OwnedAwake: true, LocalDenied: true}) != Defer { |
| + t.Errorf("awake duty allowed: HA=%v", ha) |
| + } |
| + } |
| + split := &SplitBackend{Exec: b, Unit: &UnitBackend{}} |
| + rt.Backing = registry.BackingUnit |
| + if _, err := split.Acquire(context.Background(), rt); err == nil { |
| + t.Fatal("unit acquire allowed") |
| + } |
| + if _, _, err := split.Start(context.Background(), rt); err == nil { |
| + t.Fatal("unit spawn allowed") |
| + } |
| + if _, _, err := split.StartGen(context.Background(), rt, 1, false); err == nil { |
| + t.Fatal("unit generation spawn allowed") |
| + } |
| +} |
| + |
| +func TestPoolAdoptRefusesBeforeImport(t *testing.T) { |
| + s, req := haAdoptionFixture(t) |
| + before := len(s.fx.Requests()) |
| + s.b.ServedPools = func() edgesfile.PoolEvidence { return edgesfile.PoolEvidence(`[]`) } |
| + result, _ := s.a.AdoptHost(context.Background(), s.rt, req) |
| + if result != Deferred { |
| + t.Fatalf("result %v", result) |
| + } |
| + if _, exists, err := s.b.Registry.HAAdoption(context.Background(), s.rt.Host, req.Lifetime, req.Departure); err != nil || exists { |
| + t.Fatalf("adoption progress: exists=%v err=%v", exists, err) |
| + } |
| + if len(s.fx.Requests()) != before || haFixOf(s.b).restores != 0 || spawns(s.b) != 0 { |
| + t.Fatalf("adoption did work: %v", s.fx.Requests()[before:]) |
| + } |
| +} |
| + |
| +func eligibleSharedPools() edgesfile.PoolEvidence { return edgesfile.PoolEvidence(`[""]`) } |
| + |
| +func TestPoolEvidenceBackend(t *testing.T) { |
| + rt := registry.Route{Pool: "ha"} |
| + b := &ExecBackend{} |
| + if b.poolEligible(rt) { |
| + t.Fatal("nil pool provider allowed") |
| + } |
| + for _, evidence := range []string{"", "null", "[]", `{}`, `["ha",null]`, `["ha","ha"]`, `["other"]`, `[""]`} { |
| + b.ServedPools = func() edgesfile.PoolEvidence { return edgesfile.PoolEvidence(evidence) } |
| + if b.poolEligible(rt) { |
| + t.Errorf("evidence %s allowed named pool", evidence) |
| + } |
| + } |
| + b.ServedPools = func() edgesfile.PoolEvidence { return edgesfile.PoolEvidence(`["ha"]`) } |
| + if !b.poolEligible(rt) { |
| + t.Fatal("configured pool refused") |
| + } |
| +} |
| + |
| +func TestPoolWithdrawalDefersAwakeDuty(t *testing.T) { |
| + s, _ := haServiceEntry(t, "shop.example.com") |
| + if !s.a.HoldsAwake(s.rt.Host) { |
| + t.Fatal("fixture is not awake") |
| + } |
| + s.b.ServedPools = func() edgesfile.PoolEvidence { return edgesfile.PoolEvidence(`[]`) } |
| + d, err := s.a.Duty(context.Background(), s.rt) |
| + if err != nil || d != Defer { |
| + t.Fatalf("duty=%v err=%v", d, err) |
| + } |
| + called := false |
| + err = s.a.WithDuty(context.Background(), s.rt, func(context.Context) error { called = true; return nil }) |
| + if !errors.Is(err, ErrDutyDeferred) || called { |
| + t.Fatalf("err=%v duty called=%v", err, called) |
| + } |
| +} |
diff --git a/internal/activator/replica_instancekey_test.go b/internal/activator/replica_instancekey_test.go| index ab5c47d86..711aac36c 100644 |
| --- a/internal/activator/replica_instancekey_test.go |
| +++ b/internal/activator/replica_instancekey_test.go |
| @@ -401,7 +401,7 @@ func TestReplicaGateNamesWhyItRefused(t *testing.T) { |
| }, "the bucket's configuration could not be read: bucket unreachable"}, |
| } { |
| t.Run(tc.name, func(t *testing.T) { |
| - b := &ExecBackend{DataDir: t.TempDir(), ReplicaHomeKeys: tc.homes, ConfiguredKey: tc.bucket} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, DataDir: t.TempDir(), ReplicaHomeKeys: tc.homes, ConfiguredKey: tc.bucket} |
| err := b.replicaKeyGate(rt, env, instancekey.LayerConfig, false) |
| if !errors.Is(err, ErrReplicaKey) || !strings.Contains(err.Error(), tc.want) { |
| t.Fatalf("gate = %v; want ErrReplicaKey naming %q", err, tc.want) |
| @@ -417,7 +417,7 @@ func TestReplicaGateNamesWhyItRefused(t *testing.T) { |
| // fixed reason. |
| func TestReplicaGateLogsARefusalOncePerHostAndReason(t *testing.T) { |
| buf := captureLog(t) |
| - b := &ExecBackend{DataDir: t.TempDir()} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, DataDir: t.TempDir()} |
| rt := registry.Route{Host: "ratelimit-au.example.com", Kind: "instance", Replica: true} |
| for i := 0; i < 3; i++ { |
| if err := b.replicaKeyGate(rt, map[string]string{}, instancekey.LayerNone, false); !errors.Is(err, ErrReplicaKey) { |
diff --git a/internal/activator/replicakey_race_test.go b/internal/activator/replicakey_race_test.go| index 49ccec0f8..c3f82593b 100644 |
| --- a/internal/activator/replicakey_race_test.go |
| +++ b/internal/activator/replicakey_race_test.go |
| @@ -61,7 +61,7 @@ func TestReplicaGateDecidesOnTheLaunchesOwnRead(t *testing.T) { |
| // captured, it decides the same with the files gone. |
| func TestReplicaGateReadsNoEnvFile(t *testing.T) { |
| keyA := strings.Repeat("A", 43) + "=" |
| - b := &ExecBackend{DataDir: t.TempDir()} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, DataDir: t.TempDir()} |
| rt := registry.Route{Host: "shop-au.example.com", Kind: "instance", Replica: true} |
| if err := os.WriteFile(filepath.Join(b.DataDir, rt.Host+".config.env"), []byte(InstanceKeyVar+"="+keyA+"\n"), 0o600); err != nil { |
| t.Fatal(err) |
diff --git a/internal/activator/replicaretirement_test.go b/internal/activator/replicaretirement_test.go| index 96556ecde..9bbd1d3f4 100644 |
| --- a/internal/activator/replicaretirement_test.go |
| +++ b/internal/activator/replicaretirement_test.go |
| @@ -19,7 +19,7 @@ func TestReplicaRetirementRequiresBothLayoutsEmpty(t *testing.T) { |
| {name: "empty", ok: true}, {name: "nested-process", nested: true}, {name: "flat-process", flat: true}, {name: "unreadable", readErr: errors.New("unreadable")}, |
| } { |
| t.Run(runtime+"/"+tc.name, func(t *testing.T) { |
| - b := &ExecBackend{CgroupEvents: func(string, string) (bool, bool, error) { return true, tc.nested, tc.readErr }} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, CgroupEvents: func(string, string) (bool, bool, error) { return true, tc.nested, tc.readErr }} |
| b.openHostCleanup = func(string) (hostCleanup, error) { return &goldenHostCgroup{populated: tc.flat}, nil } |
| err := b.ReplicaRetirementEmpty(registry.Route{Host: "shop.example.com", Kind: "instance", Runtime: runtime}) |
| if (err == nil) != tc.ok { |
| @@ -28,7 +28,7 @@ func TestReplicaRetirementRequiresBothLayoutsEmpty(t *testing.T) { |
| }) |
| } |
| } |
| - b := &ExecBackend{CgroupEvents: func(string, string) (bool, bool, error) { return false, false, nil }} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, CgroupEvents: func(string, string) (bool, bool, error) { return false, false, nil }} |
| b.openHostCleanup = func(string) (hostCleanup, error) { return nil, cgroup.ErrNoDelegation } |
| if b.ReplicaRetirementEmpty(registry.Route{Host: "shop.example.com"}) == nil { |
| t.Fatal("no delegation proves nothing") |
diff --git a/internal/activator/rootfs_worker_unit_test.go b/internal/activator/rootfs_worker_unit_test.go| index b0f8a9ed3..5e76c332a 100644 |
| --- a/internal/activator/rootfs_worker_unit_test.go |
| +++ b/internal/activator/rootfs_worker_unit_test.go |
| @@ -13,7 +13,7 @@ import ( |
| // cgroup.events as the unit's. The wait refuses instead of reading. |
| func TestWaitRoleCgroupEmptyRefusesAWorker(t *testing.T) { |
| t.Parallel() |
| - b := &ExecBackend{CgroupEvents: func(slice, unit string) (bool, bool, error) { |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, CgroupEvents: func(slice, unit string) (bool, bool, error) { |
| t.Errorf("cgroup.events read for slice %q unit %q", slice, unit) |
| return false, false, nil |
| }} |
| @@ -35,7 +35,7 @@ func TestUnitNameRefusesAWorker(t *testing.T) { |
| if u := runUnitName("shop.example.com", 7); u != instancectl.GenUnitName("shop.example.com", 7) { |
| t.Fatalf("runUnitName(7) = %q", u) |
| } |
| - b := &ExecBackend{} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools} |
| if up, err := b.newUnitProcFor(registry.Route{Host: "shop.example.com"}, instancectl.RoleWorker, 0, instancePaths{}, "inv", nil, nil); err == nil || up != nil { |
| t.Fatalf("newUnitProcFor(worker) = %v, %v; want a refusal", up, err) |
| } |
diff --git a/internal/activator/rootfsworkers_backend_test.go b/internal/activator/rootfsworkers_backend_test.go| index 78b639a02..fe6eb0007 100644 |
| --- a/internal/activator/rootfsworkers_backend_test.go |
| +++ b/internal/activator/rootfsworkers_backend_test.go |
| @@ -369,7 +369,7 @@ func TestRootfsWorkerIdentity(t *testing.T) { |
| t.Errorf("record %s gone = %v, want %v", name, gone, cleared) |
| } |
| } |
| - if got, want := (&ExecBackend{}).workerLogSocket(rt.Host, "jobs"), instancectl.WorkerLogSocket(rt.Host, "jobs"); got != want { |
| + if got, want := (&ExecBackend{ServedPools: eligibleSharedPools}).workerLogSocket(rt.Host, "jobs"), instancectl.WorkerLogSocket(rt.Host, "jobs"); got != want { |
| t.Errorf("workerLogSocket = %q, want root's %q (WorkerDropIn's StandardOutput=)", got, want) |
| } |
diff --git a/internal/activator/size_identical_test.go b/internal/activator/size_identical_test.go| index cd4a2629b..17f6aef23 100644 |
| --- a/internal/activator/size_identical_test.go |
| +++ b/internal/activator/size_identical_test.go |
| @@ -41,7 +41,7 @@ func TestNoSizeColumnSendsNoLiveCall(t *testing.T) { |
| {cgroup.TierChildren, cgroup.TierDefault}, |
| {cgroup.Limit{MemoryMax: 3 << 30}, cgroup.Limit{MemoryMax: 3 << 30}}, |
| } { |
| - eb := &ExecBackend{ |
| + eb := &ExecBackend{ServedPools: eligibleSharedPools, |
| Tier: func(registry.Route) cgroup.Limit { return c.live }, |
| TierOf: func(registry.Route, string) cgroup.Limit { return c.build }, |
| } |
| @@ -111,7 +111,7 @@ func TestNoSizeColumnSendsNoLiveCall(t *testing.T) { |
| var wb *wakeTierBackend |
| sf := newSwapFixtureOn(t, func(b *fakeSwapBackend) Backend { |
| b.tiers = map[string]cgroup.Limit{"v1": c.live, "v2": c.succ} |
| - wb = &wakeTierBackend{fakeSwapBackend: b, eb: &ExecBackend{ |
| + wb = &wakeTierBackend{fakeSwapBackend: b, eb: &ExecBackend{ServedPools: eligibleSharedPools, |
| Tier: func(registry.Route) cgroup.Limit { return c.live }, |
| TierOf: func(_ registry.Route, build string) cgroup.Limit { return b.tiers[build] }, |
| }} |
| @@ -220,7 +220,7 @@ func spawnCgroupFiles(t *testing.T, tier cgroup.Limit) []string { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - b := ExecBackend{Cgroups: m, Tier: func(registry.Route) cgroup.Limit { return tier }} |
| + b := ExecBackend{ServedPools: eligibleSharedPools, Cgroups: m, Tier: func(registry.Route) cgroup.Limit { return tier }} |
| cmd, _, err := b.spawnInCgroup(registry.Route{Host: "shop-a.example.com"}, func() *exec.Cmd { return exec.Command("/bin/true") }) |
| if err != nil { |
| t.Fatal(err) |
diff --git a/internal/activator/size_pending_test.go b/internal/activator/size_pending_test.go| index 58b1045fc..6e4e02625 100644 |
| --- a/internal/activator/size_pending_test.go |
| +++ b/internal/activator/size_pending_test.go |
| @@ -42,7 +42,7 @@ func newCgroupSidecarBackend(t *testing.T, fb *fakeSwapBackend) *cgroupSidecarBa |
| t.Fatal(err) |
| } |
| return &cgroupSidecarBackend{fakeSwapBackend: fb, root: root, t: t, |
| - eb: &ExecBackend{Cgroups: m, Tier: func(registry.Route) cgroup.Limit { return cgroup.TierDefault }}} |
| + eb: &ExecBackend{ServedPools: eligibleSharedPools, Cgroups: m, Tier: func(registry.Route) cgroup.Limit { return cgroup.TierDefault }}} |
| } |
| func (b *cgroupSidecarBackend) spawn(rt registry.Route) { |
diff --git a/internal/activator/startrule_test.go b/internal/activator/startrule_test.go| index 002734017..1938effe8 100644 |
| --- a/internal/activator/startrule_test.go |
| +++ b/internal/activator/startrule_test.go |
| @@ -352,7 +352,7 @@ func TestNothingToRestoreRefusesEveryTime(t *testing.T) { |
| for i, eb := range []*ExecBackend{ |
| b, // the first wake sets the copy aside |
| b, // a second wake finds it set aside |
| - {Cfg: b.Cfg, OptDir: b.OptDir, DataDir: b.DataDir}, // an agent restart |
| + {ServedPools: eligibleSharedPools, Cfg: b.Cfg, OptDir: b.OptDir, DataDir: b.DataDir}, // an agent restart |
| } { |
| rb, err := wakeOn(t, eb, rt, nil) |
| if !errors.Is(err, ErrNothingToRestore) { |
diff --git a/internal/activator/stateless_assignment_test.go b/internal/activator/stateless_assignment_test.go| index d551d3056..8e611a294 100644 |
| --- a/internal/activator/stateless_assignment_test.go |
| +++ b/internal/activator/stateless_assignment_test.go |
| @@ -93,7 +93,7 @@ func TestStatelessAssignmentNeverSetsAsideLocalDatabase(t *testing.T) { |
| t.Fatal(err) |
| } |
| rt := registry.Route{Host: "shop.example.com", DBPath: path, Assigned: "new", FleetBoxes: `["a"]`, Stateless: true} |
| - b := &ExecBackend{DataDir: dir} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, DataDir: dir} |
| for _, f := range []func() error{func() error { return b.reconcileAssignment(rt, path) }, func() error { return b.startAllowed(rt, true, false) }, func() error { return b.establishAssignment(rt, path) }} { |
| if f() == nil { |
| t.Fatal("set entered the SQLite assignment path") |
diff --git a/internal/activator/stateless_fix1_test.go b/internal/activator/stateless_fix1_test.go| index f8e1f6138..770ceac74 100644 |
| --- a/internal/activator/stateless_fix1_test.go |
| +++ b/internal/activator/stateless_fix1_test.go |
| @@ -312,7 +312,7 @@ func TestStatelessFinalRecordRunsAfterPendingWrite(t *testing.T) { |
| ctx = a.withStatelessFinalCheck(ctx, rt) |
| launch := func() error { return runExecGate(ctx) } |
| if seam == "launchGate" { |
| - launch = (&ExecBackend{}).launchGate(ctx, rt.Host) |
| + launch = (&ExecBackend{ServedPools: eligibleSharedPools}).launchGate(ctx, rt.Host) |
| } |
| for i := 0; i < 3; i++ { |
| if err := launch(); err != nil { |
diff --git a/internal/activator/stateless_fix2_linux_test.go b/internal/activator/stateless_fix2_linux_test.go| index 5a4dd2ee9..075df1923 100644 |
| --- a/internal/activator/stateless_fix2_linux_test.go |
| +++ b/internal/activator/stateless_fix2_linux_test.go |
| @@ -19,7 +19,7 @@ func TestStatelessStatefulWakeHashesOneCapture(t *testing.T) { |
| r.rt.Runtime = "" |
| r.routes.set(r.rt) |
| r.a.Planner = nil |
| - eb := &ExecBackend{OptDir: t.TempDir()} |
| + eb := &ExecBackend{ServedPools: eligibleSharedPools, OptDir: t.TempDir()} |
| path := release.VersionPath(eb.OptDir, r.rt.Account, "v1", r.rt.App) |
| if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { |
| t.Fatal(err) |
diff --git a/internal/activator/stateless_test.go b/internal/activator/stateless_test.go| index 200363b26..cc3e0c9f8 100644 |
| --- a/internal/activator/stateless_test.go |
| +++ b/internal/activator/stateless_test.go |
| @@ -21,7 +21,7 @@ import ( |
| ) |
| func TestStatelessBinaryArguments(t *testing.T) { |
| - b := &ExecBackend{} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools} |
| rt := testRoute("shop.example.com") |
| rt.DBPath = "/data/old.db" |
| if got, want := b.statelessArgv(rt, "/opt/shop", "/run/shop.sock"), []string{"/opt/shop", "--socket", "/run/shop.sock"}; !slices.Equal(got, want) { |
| @@ -215,7 +215,7 @@ func TestStatelessWakeHasNoDatabaseWork(t *testing.T) { |
| } |
| func TestStatelessEveryEnvironment(t *testing.T) { |
| - b := &ExecBackend{Region: "region"} |
| + b := &ExecBackend{ServedPools: eligibleSharedPools, Region: "region"} |
| rt := testRoute("shop.example.com") |
| rt.Stateless = true |
| env := map[string]string{"CARLOS_DB": "user-override", "KEEP": "yes"} |
diff --git a/internal/activator/wakerecord_recheck_test.go b/internal/activator/wakerecord_recheck_test.go| index a19034af7..92dbe8621 100644 |
| --- a/internal/activator/wakerecord_recheck_test.go |
| +++ b/internal/activator/wakerecord_recheck_test.go |
| @@ -42,7 +42,7 @@ func TestAnExecGateRefusingDuringTheRecordStartsNothing(t *testing.T) { |
| if seam == "runExecGate" { |
| err = runExecGate(ctx) |
| } else { |
| - err = (&ExecBackend{}).launchGate(ctx, "one.example.com")() |
| + err = (&ExecBackend{ServedPools: eligibleSharedPools}).launchGate(ctx, "one.example.com")() |
| } |
| if !errors.Is(err, superseding) { |
| t.Fatalf("%s = %v, want the gate's refusal after the record", seam, err) |
diff --git a/internal/edge/forwardha_wiring_test.go b/internal/edge/forwardha_wiring_test.go| index 62ce9d6dc..9409eaf58 100644 |
| --- a/internal/edge/forwardha_wiring_test.go |
| +++ b/internal/edge/forwardha_wiring_test.go |
| @@ -15,6 +15,7 @@ import ( |
| "github.com/carlosframework/platform/internal/edge" |
| "github.com/carlosframework/platform/internal/hafresh" |
| "github.com/carlosframework/platform/internal/lease/locktest" |
| + "github.com/carlosframework/platform/internal/provision" |
| ) |
| const unreachableBody = "instance is waking elsewhere; retry shortly\n" |
| @@ -48,7 +49,7 @@ func deadHolderGuard(t *testing.T, blackholed bool) { |
| fx.PutLock(prefix, body) |
| cfg := activator.Config{Bucket: fx.Bucket, Idle: time.Hour, |
| Self: func() hafresh.Self { return hafresh.Self{Ref: "annie", IID: "i-a"} }} |
| - svc := activator.New(cfg, &activator.ExecBackend{Cfg: cfg}, nil) |
| + svc := activator.New(cfg, &activator.ExecBackend{ServedPools: (provision.ReconcileConfig{}).ServedPools, Cfg: cfg}, nil) |
| x := edge.NewHAForwardScene(t, svc) |
| // The holder serves one forward. |
diff --git a/internal/edge/haplacement_wiring_test.go b/internal/edge/haplacement_wiring_test.go| index 61797aa58..42478334c 100644 |
| --- a/internal/edge/haplacement_wiring_test.go |
| +++ b/internal/edge/haplacement_wiring_test.go |
| @@ -13,6 +13,7 @@ import ( |
| "github.com/carlosframework/platform/internal/hafresh" |
| "github.com/carlosframework/platform/internal/lease" |
| "github.com/carlosframework/platform/internal/lease/locktest" |
| + "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/registry" |
| ) |
| @@ -41,7 +42,7 @@ func (a *placementAcquire) ServeHTTP(w http.ResponseWriter, r *http.Request, rt |
| defer a.mu.Unlock() |
| if a.held == nil { |
| a.acquires++ |
| - h, err := lease.AcquireHA(r.Context(), a.bucket, a.prefix, "eu-west-1", hafresh.Marker{}, hafresh.Proofs{}) |
| + h, err := lease.AcquireHA(r.Context(), a.bucket, a.prefix, "eu-west-1", hafresh.Marker{}, hafresh.Proofs{LocalEligible: func() bool { return true }}) |
| if err != nil { |
| http.Error(w, err.Error(), 503) |
| return true |
| @@ -88,7 +89,7 @@ func testFrontPlacementPausedPeer(t *testing.T, previousHolder, stillHeld bool) |
| } |
| fx.PutLock(prefix, body) |
| cfg := activator.Config{Bucket: fx.Bucket, Idle: time.Hour, Self: func() hafresh.Self { return self }} |
| - a := &placementAcquire{Service: activator.New(cfg, &activator.ExecBackend{Cfg: cfg}, nil), bucket: fx.Bucket, prefix: prefix} |
| + a := &placementAcquire{Service: activator.New(cfg, &activator.ExecBackend{ServedPools: (provision.ReconcileConfig{}).ServedPools, Cfg: cfg}, nil), bucket: fx.Bucket, prefix: prefix} |
| t.Cleanup(func() { |
| a.Service.Shutdown(context.Background()) |
| if a.held != nil { |
| @@ -211,7 +212,7 @@ func TestPlacementCanceledDialRealWiring(t *testing.T) { |
| } |
| fx.PutLock(prefix, body) |
| cfg := activator.Config{Bucket: fx.Bucket, Idle: time.Hour, Self: func() hafresh.Self { return self }} |
| - a := &placementAcquire{Service: activator.New(cfg, &activator.ExecBackend{Cfg: cfg}, nil), bucket: fx.Bucket, prefix: prefix} |
| + a := &placementAcquire{Service: activator.New(cfg, &activator.ExecBackend{ServedPools: (provision.ReconcileConfig{}).ServedPools, Cfg: cfg}, nil), bucket: fx.Bucket, prefix: prefix} |
| t.Cleanup(func() { |
| a.Service.Shutdown(context.Background()) |
| if a.held != nil { |
| @@ -317,7 +318,7 @@ func TestPlacementCanceledDialRealWiring(t *testing.T) { |
| func TestForwardTLSFailureIsHostLocalRealWiring(t *testing.T) { |
| fx := locktest.NewLockFixture(t) |
| cfg := activator.Config{Bucket: fx.Bucket, Idle: time.Hour, Self: func() hafresh.Self { return hafresh.Self{Ref: "annie", IID: "i-a"} }} |
| - a := &placementAcquire{Service: activator.New(cfg, &activator.ExecBackend{Cfg: cfg}, nil)} |
| + a := &placementAcquire{Service: activator.New(cfg, &activator.ExecBackend{ServedPools: (provision.ReconcileConfig{}).ServedPools, Cfg: cfg}, nil)} |
| t.Cleanup(func() { a.Service.Shutdown(context.Background()) }) |
| // A is a true holder; its own failure must not change B's placement peer. |
| held, err := json.Marshal(hafresh.Lock{Generation: 9, ExpiresAt: time.Now().Add(time.Minute), Owner: hafresh.OwnerFor(hafresh.Self{Ref: "betty", IID: "i-b"}, 7, true)}) |
diff --git a/internal/hafresh/acquire.go b/internal/hafresh/acquire.go| index b3382f9e2..3a224994d 100644 |
| --- a/internal/hafresh/acquire.go |
| +++ b/internal/hafresh/acquire.go |
| @@ -40,20 +40,23 @@ type Decision struct { |
| // terminated (a stopped or unknown instance is not); nil, false or an |
| // error refuses the takeover of another box's expired lock. |
| type Proofs struct { |
| + // LocalEligible proves this box serves the host pool; nil refuses. |
| + LocalEligible func() bool |
| SameBoxEmpty func() (bool, error) |
| OwnerTerminated func(iid string) (bool, error) |
| } |
| // Refusal reasons, matched by callers and tests. |
| const ( |
| - ReasonAbsent = "absent" |
| - ReasonMarker = "release marker" |
| - ReasonLeftoverLock = "leftover lock" |
| - ReasonBadMarker = "malformed release marker" |
| - ReasonSameBoxUnsure = "same box without emptiness proof" |
| - ReasonOtherExpired = "another box's expired lease" |
| - ReasonSameBox = "same box, proven empty" |
| - ReasonTerminated = "holder terminated" |
| + ReasonPoolIneligible = "ha_pool_ineligible" |
| + ReasonAbsent = "absent" |
| + ReasonMarker = "release marker" |
| + ReasonLeftoverLock = "leftover lock" |
| + ReasonBadMarker = "malformed release marker" |
| + ReasonSameBoxUnsure = "same box without emptiness proof" |
| + ReasonOtherExpired = "another box's expired lease" |
| + ReasonSameBox = "same box, proven empty" |
| + ReasonTerminated = "holder terminated" |
| ) |
| // DecideAcquire is the HA acquire's one table (I1), for HA hosts only: |
| @@ -70,6 +73,9 @@ const ( |
| // terminated owner's lock is not taken before it expires (N-HA9); |
| // - expired, owned by a box with no instance id: refuse. |
| func DecideAcquire(v View, self Self, now time.Time, p Proofs) Decision { |
| + if p.LocalEligible == nil || !p.LocalEligible() { |
| + return Decision{ActRefuse, ReasonPoolIneligible} |
| + } |
| if v.Absent { |
| return Decision{ActCreate, ReasonAbsent} |
| } |
diff --git a/internal/hafresh/acquire_test.go b/internal/hafresh/acquire_test.go| index 8a5e51356..f0460db10 100644 |
| --- a/internal/hafresh/acquire_test.go |
| +++ b/internal/hafresh/acquire_test.go |
| @@ -13,23 +13,23 @@ func TestDecideAcquireTable(t *testing.T) { |
| self := Self{Ref: "a", IID: "i-a"} |
| exp := now.Add(-time.Minute) |
| other, mine := OwnerFor(Self{Ref: "b", IID: "i-b"}, 9, true), OwnerFor(self, 9, true) |
| - yes := Proofs{SameBoxEmpty: func() (bool, error) { return true, nil }} |
| - no := Proofs{SameBoxEmpty: func() (bool, error) { return false, nil }} |
| - broken := Proofs{SameBoxEmpty: func() (bool, error) { return true, errors.New("cgroup unreadable") }} |
| - terminated := Proofs{OwnerTerminated: func(string) (bool, error) { return true, nil }} |
| - terminatedErr := Proofs{OwnerTerminated: func(string) (bool, error) { return true, errors.New("ec2 unreachable") }} |
| + yes := Proofs{LocalEligible: func() bool { return true }, SameBoxEmpty: func() (bool, error) { return true, nil }} |
| + no := Proofs{LocalEligible: func() bool { return true }, SameBoxEmpty: func() (bool, error) { return false, nil }} |
| + broken := Proofs{LocalEligible: func() bool { return true }, SameBoxEmpty: func() (bool, error) { return true, errors.New("cgroup unreadable") }} |
| + terminated := Proofs{LocalEligible: func() bool { return true }, OwnerTerminated: func(string) (bool, error) { return true, nil }} |
| + terminatedErr := Proofs{LocalEligible: func() bool { return true }, OwnerTerminated: func(string) (bool, error) { return true, errors.New("ec2 unreachable") }} |
| noIIDOther := OwnerFor(Self{Ref: "c"}, 9, true) |
| for i, c := range []struct { |
| v View |
| p Proofs |
| want Action |
| }{ |
| - {View{Absent: true}, Proofs{}, ActCreate}, |
| - {View{Lock: Lock{ExpiresAt: exp, Owner: "ip-10-0-0-1:77"}}, Proofs{}, ActRefuse}, |
| - {View{Lock: Lock{Owner: "released/v1;ref=b;iid=i-b", Release: &Marker{Box: "b"}}}, Proofs{}, ActTake}, |
| - {View{Lock: Lock{ExpiresAt: now.Add(time.Minute), Owner: other}}, Proofs{}, ActHeld}, |
| + {View{Absent: true}, Proofs{LocalEligible: func() bool { return true }}, ActCreate}, |
| + {View{Lock: Lock{ExpiresAt: exp, Owner: "ip-10-0-0-1:77"}}, Proofs{LocalEligible: func() bool { return true }}, ActRefuse}, |
| + {View{Lock: Lock{Owner: "released/v1;ref=b;iid=i-b", Release: &Marker{Box: "b"}}}, Proofs{LocalEligible: func() bool { return true }}, ActTake}, |
| + {View{Lock: Lock{ExpiresAt: now.Add(time.Minute), Owner: other}}, Proofs{LocalEligible: func() bool { return true }}, ActHeld}, |
| {View{Lock: Lock{ExpiresAt: exp, Owner: other}}, yes, ActRefuse}, |
| - {View{Lock: Lock{ExpiresAt: exp, Owner: mine}}, Proofs{}, ActRefuse}, |
| + {View{Lock: Lock{ExpiresAt: exp, Owner: mine}}, Proofs{LocalEligible: func() bool { return true }}, ActRefuse}, |
| {View{Lock: Lock{ExpiresAt: exp, Owner: mine}}, yes, ActTake}, |
| // Beyond the plan's table: a proof that says "not empty", or that |
| // fails, refuses; an unexpired lock of this very box is held; a |
| @@ -40,7 +40,7 @@ func TestDecideAcquireTable(t *testing.T) { |
| {View{Lock: Lock{ExpiresAt: now.Add(time.Minute), Owner: mine}}, yes, ActHeld}, |
| {View{Lock: Lock{ExpiresAt: exp, Owner: OwnerFor(self, 9, false)}}, yes, ActRefuse}, |
| {View{Lock: Lock{ExpiresAt: exp, Owner: "released/v1;ref=b"}}, yes, ActRefuse}, |
| - {View{Lock: Lock{ExpiresAt: exp, Owner: other}}, Proofs{}, ActRefuse}, |
| + {View{Lock: Lock{ExpiresAt: exp, Owner: other}}, Proofs{LocalEligible: func() bool { return true }}, ActRefuse}, |
| // Another box's lock, EC2 confirming it terminated: taken only |
| // once expired; a failed confirmation or an iid-less owner refuses. |
| {View{Lock: Lock{ExpiresAt: exp, Owner: other}}, terminated, ActTake}, |
| @@ -58,10 +58,10 @@ func TestDecideAcquireTable(t *testing.T) { |
| p Proofs |
| want string |
| }{ |
| - {View{Lock: Lock{ExpiresAt: exp, Owner: "ip-10-0-0-1:77"}}, Proofs{}, ReasonLeftoverLock}, |
| + {View{Lock: Lock{ExpiresAt: exp, Owner: "ip-10-0-0-1:77"}}, Proofs{LocalEligible: func() bool { return true }}, ReasonLeftoverLock}, |
| {View{Lock: Lock{ExpiresAt: exp, Owner: other}}, yes, ReasonOtherExpired}, |
| - {View{Lock: Lock{ExpiresAt: exp, Owner: mine}}, Proofs{}, ReasonSameBoxUnsure}, |
| - {View{Lock: Lock{ExpiresAt: now.Add(time.Minute), Owner: other}}, Proofs{}, other}, |
| + {View{Lock: Lock{ExpiresAt: exp, Owner: mine}}, Proofs{LocalEligible: func() bool { return true }}, ReasonSameBoxUnsure}, |
| + {View{Lock: Lock{ExpiresAt: now.Add(time.Minute), Owner: other}}, Proofs{LocalEligible: func() bool { return true }}, other}, |
| {View{Lock: Lock{ExpiresAt: exp, Owner: other}}, terminated, ReasonTerminated}, |
| {View{Lock: Lock{ExpiresAt: exp, Owner: mine}}, yes, ReasonSameBox}, |
| } { |
| @@ -84,11 +84,11 @@ func TestDecideAcquireReasons(t *testing.T) { |
| now := time.Unix(1_800_000_000, 0) |
| self := Self{Ref: "a", IID: "i-a"} |
| v := View{Lock: Lock{ExpiresAt: now.Add(-time.Minute), Owner: OwnerFor(Self{Ref: "b", IID: "i-b"}, 9, true)}} |
| - d := DecideAcquire(v, self, now, Proofs{OwnerTerminated: func(string) (bool, error) { return true, nil }}) |
| + d := DecideAcquire(v, self, now, Proofs{LocalEligible: func() bool { return true }, OwnerTerminated: func(string) (bool, error) { return true, nil }}) |
| if d.Action != ActTake || d.Reason != ReasonTerminated { |
| t.Fatalf("terminated take: %+v", d) |
| } |
| - d = DecideAcquire(v, self, now, Proofs{OwnerTerminated: func(string) (bool, error) { return false, errors.New("throttled") }}) |
| + d = DecideAcquire(v, self, now, Proofs{LocalEligible: func() bool { return true }, OwnerTerminated: func(string) (bool, error) { return false, errors.New("throttled") }}) |
| if d.Action != ActRefuse || d.Reason != ReasonOtherExpired+": throttled" { |
| t.Fatalf("proof error: %+v", d) |
| } |
| @@ -115,7 +115,7 @@ func TestDecideAcquireProofScope(t *testing.T) { |
| } { |
| var term []string |
| same := 0 |
| - p := Proofs{ |
| + p := Proofs{LocalEligible: func() bool { return true }, |
| SameBoxEmpty: func() (bool, error) { same++; return true, nil }, |
| OwnerTerminated: func(iid string) (bool, error) { term = append(term, iid); return true, nil }, |
| } |
| @@ -131,7 +131,7 @@ func TestDecideAcquireProofScope(t *testing.T) { |
| func TestDecideAcquireStoppedOwnerIsNotTaken(t *testing.T) { |
| now := time.Unix(1_800_000_000, 0) |
| v := View{Lock: Lock{ExpiresAt: now.Add(-time.Minute), Owner: OwnerFor(Self{Ref: "b", IID: "i-b"}, 9, true)}} |
| - d := DecideAcquire(v, Self{Ref: "a", IID: "i-a"}, now, Proofs{OwnerTerminated: func(string) (bool, error) { return false, nil }}) |
| + d := DecideAcquire(v, Self{Ref: "a", IID: "i-a"}, now, Proofs{LocalEligible: func() bool { return true }, OwnerTerminated: func(string) (bool, error) { return false, nil }}) |
| if d.Action != ActRefuse || d.Reason != ReasonOtherExpired { |
| t.Fatalf("%+v", d) |
| } |
diff --git a/internal/hafresh/pools_test.go b/internal/hafresh/pools_test.go| new file mode 100644 |
| index 000000000..505c327c0 |
| --- /dev/null |
| +++ b/internal/hafresh/pools_test.go |
| @@ -0,0 +1,31 @@ |
| +package hafresh |
| + |
| +import ( |
| + "testing" |
| + "time" |
| +) |
| + |
| +func TestAcquireHAPoolEligibility(t *testing.T) { |
| + now := time.Now() |
| + me := Self{Ref: "a", IID: "i-a"} |
| + for name, v := range map[string]View{ |
| + "absent": {Absent: true}, |
| + "clean marker": {Lock: Lock{Release: &Marker{V: 1, Box: "b", Clean: true}}}, |
| + "unclean marker": {Lock: Lock{Release: &Marker{V: 1, Box: "b"}}}, |
| + "lifted tombstone": {Lock: Lock{Owner: "moved:lifted", ExpiresAt: time.Unix(0, 0)}}, |
| + "own expired": {Lock: Lock{Owner: OwnerFor(me, 1, true), ExpiresAt: now.Add(-time.Hour)}}, |
| + "foreign terminated": {Lock: Lock{Owner: OwnerFor(Self{Ref: "b", IID: "i-b"}, 1, true), ExpiresAt: now.Add(-time.Hour)}}, |
| + "unexpired": {Lock: Lock{Owner: OwnerFor(me, 1, true), ExpiresAt: now.Add(time.Hour)}}, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + p := Proofs{SameBoxEmpty: func() (bool, error) { t.Error("emptiness proof called"); return true, nil }, OwnerTerminated: func(string) (bool, error) { t.Error("termination proof called"); return true, nil }} |
| + for _, eligible := range []func() bool{nil, func() bool { return false }} { |
| + p.LocalEligible = eligible |
| + d := DecideAcquire(v, me, now, p) |
| + if d.Action != ActRefuse || d.Reason != "ha_pool_ineligible" { |
| + t.Fatalf("decision %+v", d) |
| + } |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/host/agent.go b/internal/host/agent.go| index 713a605c4..4eeaa5463 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -497,9 +497,10 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| // gate is still the hibernate bucket env even though unit tenants |
| // never touch the bucket — one opt-in switch for the whole activator. |
| eb := &activator.ExecBackend{ |
| - Cfg: *cfg, |
| - OptDir: release.OptDir(), |
| - DataDir: dd, |
| + ServedPools: provisionTickConfig(os.Getenv).ServedPools, |
| + Cfg: *cfg, |
| + OptDir: release.OptDir(), |
| + DataDir: dd, |
| // The box's placement code, into every exec child's env |
| // (issue #329) — same env the reconcile pass scopes by. |
| Region: strings.TrimSpace(os.Getenv("CARLOS_REGION")), |
diff --git a/internal/host/booting_publication_test.go b/internal/host/booting_publication_test.go| index 0dc621079..037457374 100644 |
| --- a/internal/host/booting_publication_test.go |
| +++ b/internal/host/booting_publication_test.go |
| @@ -64,7 +64,7 @@ func TestAdmissionBootingKeepsLegacyRows(t *testing.T) { |
| } |
| svc := activator.New(activator.Config{}, nil, nil) |
| - opt := wireAgentAdmission(a, svc, &activator.ExecBackend{}, nil) |
| + opt := wireAgentAdmission(a, svc, &activator.ExecBackend{ServedPools: testSharedPoolEvidence}, nil) |
| e, err := edge.New(reg, svc) |
| if err != nil { |
| t.Fatal(err) |
diff --git a/internal/host/claim_first_wake_linux_test.go b/internal/host/claim_first_wake_linux_test.go| index 0819fac05..3946704b9 100644 |
| --- a/internal/host/claim_first_wake_linux_test.go |
| +++ b/internal/host/claim_first_wake_linux_test.go |
| @@ -14,7 +14,7 @@ import ( |
| ) |
| func TestClaimFirstWakeCreatesAuthorizedInstanceDirectory(t *testing.T) { |
| - b := &activator.ExecBackend{DataDir: t.TempDir()} |
| + b := &activator.ExecBackend{ServedPools: testSharedPoolEvidence, DataDir: t.TempDir()} |
| host := "first-claim.example" |
| rt := registry.Route{Host: host, DBPath: provision.NestedDBPath(b.DataDir, host), Socket: provision.NestedSocket(host)} |
| parent := filepath.Join(b.DataDir, "instances") |
diff --git a/internal/host/claimproduction.go b/internal/host/claimproduction.go| index 03a0ab129..a275c4527 100644 |
| --- a/internal/host/claimproduction.go |
| +++ b/internal/host/claimproduction.go |
| @@ -246,7 +246,7 @@ func (ProductionClaimOwnerProvider) OpenClaimOwners(ctx context.Context, store r |
| // could mint before the configuration was delivered; the agent's backend |
| // is wired from the same pair. |
| func claimExecBackend(r ClaimRuntimeResources, keys instanceKeyReaders) *activator.ExecBackend { |
| - eb := &activator.ExecBackend{DataDir: r.DataDir, OptDir: r.OptDir, Cgroups: r.Manager, RawInstanceDir: layout.RawInstanceDir} |
| + eb := &activator.ExecBackend{ServedPools: provisionTickConfig(os.Getenv).ServedPools, DataDir: r.DataDir, OptDir: r.OptDir, Cgroups: r.Manager, RawInstanceDir: layout.RawInstanceDir} |
| keys.wire(eb) |
| return eb |
| } |
diff --git a/internal/host/claimproduction_admintoken_test.go b/internal/host/claimproduction_admintoken_test.go| index 3b1bddc7b..857d1948c 100644 |
| --- a/internal/host/claimproduction_admintoken_test.go |
| +++ b/internal/host/claimproduction_admintoken_test.go |
| @@ -70,7 +70,7 @@ func newAdminTokenFixture(t *testing.T, execBox string) *adminTokenFixture { |
| t.Fatal(err) |
| } |
| t.Cleanup(func() { reg.Close() }) |
| - f := &adminTokenFixture{t: t, claims: st, data: data, backend: &activator.ExecBackend{DataDir: data, OptDir: opt}, actor: hostbox.Actor{Box: "box-1", Region: "ie", Enrollment: "enr-1"}} |
| + f := &adminTokenFixture{t: t, claims: st, data: data, backend: &activator.ExecBackend{ServedPools: testSharedPoolEvidence, DataDir: data, OptDir: opt}, actor: hostbox.Actor{Box: "box-1", Region: "ie", Enrollment: "enr-1"}} |
| f.rt = registry.Route{Host: adminTokenHost, Socket: filepath.Join(root, "run", "app.sock"), DBPath: filepath.Join(data, adminTokenHost+".db")} |
| local := &productionClaimLocal{legacyParticipation: true, Resources: ClaimRuntimeResources{Mode: "agent", DataDir: data}, slots: map[string]*claimParticipation{}} |
| f.tokens = claimAdminTokens{ |
diff --git a/internal/host/claimunit_inputs_test.go b/internal/host/claimunit_inputs_test.go| index 269903dda..72eacee5d 100644 |
| --- a/internal/host/claimunit_inputs_test.go |
| +++ b/internal/host/claimunit_inputs_test.go |
| @@ -133,7 +133,7 @@ func TestClaimBoundSnapshotCarriesTheSizeColumn(t *testing.T) { |
| } |
| unit := &hostbox.UnitLaunchInputs{Unit: "console.service", Addr: "127.0.0.1:9000", DBPath: filepath.Join(provision.InstanceDir("/data", host), "app.db"), Program: strings.Repeat("ab", 32)} |
| read := func(context.Context, registry.Route) (*hostbox.UnitLaunchInputs, error) { return unit, nil } |
| - backend := &activator.ExecBackend{OptDir: opt, Tier: func(registry.Route) cgroup.Limit { return cgroup.TierChildren }} |
| + backend := &activator.ExecBackend{ServedPools: testSharedPoolEvidence, OptDir: opt, Tier: func(registry.Route) cgroup.Limit { return cgroup.TierChildren }} |
| xlarge, _ := cgroup.SizeByName("xlarge") |
| for _, c := range []struct { |
| size string |
diff --git a/internal/host/declinedgate_identity_test.go b/internal/host/declinedgate_identity_test.go| index f5bff4298..cc67fce4d 100644 |
| --- a/internal/host/declinedgate_identity_test.go |
| +++ b/internal/host/declinedgate_identity_test.go |
| @@ -66,7 +66,7 @@ func TestDeclinedBoxRefusesAHeldCapturedIdentityAtLaunch(t *testing.T) { |
| t.Fatal(err) |
| } |
| writeFailureBook(t, env.dataDir, []rollout.FailureRecord{{Account: release.RouteAccount(rt), App: "fastapp", Build: "v2", Host: "sibling.test"}}, nil) |
| - eb := &activator.ExecBackend{Cfg: activator.Config{Bucket: "test-bucket", Idle: time.Hour}, |
| + eb := &activator.ExecBackend{ServedPools: testSharedPoolEvidence, Cfg: activator.Config{Bucket: "test-bucket", Idle: time.Hour}, |
| OptDir: env.optDir, DataDir: t.TempDir(), RunDirOverride: run} |
| backend := &liveIdentityBackend{liveLaunchBackend{eb: eb}} |
| svc := activator.New(activator.Config{Bucket: "test-bucket", Idle: time.Hour}, backend, env.reg) |
diff --git a/internal/host/edgesfile.go b/internal/host/edgesfile.go| index 6924db709..4281d3a75 100644 |
| --- a/internal/host/edgesfile.go |
| +++ b/internal/host/edgesfile.go |
| @@ -1092,14 +1092,13 @@ func edgesFileRegion(getenv func(string) string, probedRegion string) string { |
| func edgesFileEligibility(getenv func(string) string) (sharedPool, inbound bool, namedPools []string) { |
| cfg := provisionTickConfig(getenv) |
| sharedPool, inbound = cfg.SharedInstanceEligibility() |
| - namedPools = make([]string, 0, len(cfg.Pools)) |
| - for _, pool := range cfg.Pools { |
| - if pool != "" && provision.ValidPool(pool) { |
| + pools, _ := cfg.ServedPools().Pools() |
| + namedPools = make([]string, 0, len(pools)) |
| + for _, pool := range pools { |
| + if pool != "" { |
| namedPools = append(namedPools, pool) |
| } |
| } |
| - slices.Sort(namedPools) |
| - namedPools = slices.Compact(namedPools) |
| return |
| } |
| @@ -1404,16 +1403,5 @@ func (s *edgesFileSchedule) done(now time.Time, ok bool) { |
| var aliasClaimCache domains.ClaimCache |
| func edgesFileServedPools(cfg provision.ReconcileConfig) edgesfile.PoolEvidence { |
| - pools := make([]string, 0, len(cfg.Pools)) |
| - if len(cfg.Pools) == 0 { |
| - pools = append(pools, "") |
| - } |
| - for _, p := range cfg.Pools { |
| - if p == "" || provision.ValidPool(p) { |
| - pools = append(pools, p) |
| - } |
| - } |
| - slices.Sort(pools) |
| - body, _ := json.Marshal(slices.Compact(pools)) |
| - return edgesfile.PoolEvidence(body) |
| + return cfg.ServedPools() |
| } |
diff --git a/internal/host/fleettwobox_e2e_test.go b/internal/host/fleettwobox_e2e_test.go| index 5c79dcc6c..c7ffd2d92 100644 |
| --- a/internal/host/fleettwobox_e2e_test.go |
| +++ b/internal/host/fleettwobox_e2e_test.go |
| @@ -318,7 +318,7 @@ func (w *fleetWorld) newBox(label string) *fleetBox { |
| func (b *fleetBox) start() { |
| cfg := activator.Config{Bucket: fleetBucket, Region: fleetRegion, Prefix: fleetPrefix} |
| id := b.self |
| - b.eb = &activator.ExecBackend{Cfg: cfg, DataDir: b.dd, OptDir: b.w.t.TempDir(), LeaseIdentity: &id, LeaseTTL: fleetTTL} |
| + b.eb = &activator.ExecBackend{ServedPools: testSharedPoolEvidence, Cfg: cfg, DataDir: b.dd, OptDir: b.w.t.TempDir(), LeaseIdentity: &id, LeaseTTL: fleetTTL} |
| b.awake = map[string]activator.Rep{} |
| } |
diff --git a/internal/host/group_admission_fix_test.go b/internal/host/group_admission_fix_test.go| index 195058a70..d8e558d91 100644 |
| --- a/internal/host/group_admission_fix_test.go |
| +++ b/internal/host/group_admission_fix_test.go |
| @@ -89,7 +89,7 @@ func testPreAdmissionAgentWiring(t *testing.T, group bool) { |
| }) |
| a.tick(t.Context()) |
| } |
| - eb := &activator.ExecBackend{ConfigGate: func(context.Context, registry.Route) error { return errors.New("unexpected backend work") }} |
| + eb := &activator.ExecBackend{ServedPools: testSharedPoolEvidence, ConfigGate: func(context.Context, registry.Route) error { return errors.New("unexpected backend work") }} |
| opt := wireAgentAdmission(a, svc, eb, func() hadeparture.Lifecycle { |
| if svc.TenantAdmitted() { |
| t.Error("consumer armed before service gate") |
| @@ -129,7 +129,7 @@ func TestPreAdmissionAgentRetainedRespawn(t *testing.T) { |
| t.Fatal(err) |
| } |
| a := newFixedAdmission(admissionEnv, admissionHealth()) |
| - wireAgentAdmission(a, svc, &activator.ExecBackend{}, nil) |
| + wireAgentAdmission(a, svc, &activator.ExecBackend{ServedPools: testSharedPoolEvidence}, nil) |
| result := svc.ReplaceWorker(t.Context(), activator.Attempt{Host: rt.Host, Cause: activator.CauseRelease, Build: "v2", Mode: activator.ModeOverlap, SchedRev: 1}, nil, func(string) uint64 { return 1 }) |
| if result.Executed || b.starts.Load() != 1 || !strings.Contains(result.Reason, activator.ErrTenantAdmission.Error()) { |
| t.Fatalf("closed retained-lease respawn: %+v, starts=%d", result, b.starts.Load()) |
| @@ -138,7 +138,7 @@ func TestPreAdmissionAgentRetainedRespawn(t *testing.T) { |
| func TestAdmissionAgentWorkerRestart(t *testing.T) { |
| reg, svc, b, rt := admissionWorkerFixture(t) |
| a := newFixedAdmission(admissionEnv, admissionHealth()) |
| - wireAgentAdmission(a, svc, &activator.ExecBackend{}, nil) |
| + wireAgentAdmission(a, svc, &activator.ExecBackend{ServedPools: testSharedPoolEvidence}, nil) |
| done := make(chan struct{}) |
| go func() { defer close(done); runWorkerBootPassAfterAdmission(t.Context(), a, reg.List, svc.WakeWorker) }() |
| select { |
| @@ -174,7 +174,7 @@ func TestAdmissionAgentScheduleDeferred(t *testing.T) { |
| const host = "shop.example.com" |
| reg, inst, svc, dd := wakeFixture(t, host, time.Hour, func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(204) }) |
| a := newFixedAdmission(admissionEnv, admissionHealth()) |
| - wireAgentAdmission(a, svc, &activator.ExecBackend{}, nil) |
| + wireAgentAdmission(a, svc, &activator.ExecBackend{ServedPools: testSharedPoolEvidence}, nil) |
| sd := armSchedule(reg, nil, errors.New("local only"), svc, nil, dd) |
| now := time.Now().UTC() |
| due := now.Unix() - 1 |
| @@ -224,7 +224,7 @@ func TestAdmissionAgentResponsePhase(t *testing.T) { |
| t.Fatal(err) |
| } |
| a := newFixedAdmission(admissionEnv, admissionHealth()) |
| - opt := wireAgentAdmission(a, svc, &activator.ExecBackend{}, nil) |
| + opt := wireAgentAdmission(a, svc, &activator.ExecBackend{ServedPools: testSharedPoolEvidence}, nil) |
| e, err := edge.New(reg, svc) |
| if err != nil { |
| t.Fatal(err) |
diff --git a/internal/host/group_admission_test.go b/internal/host/group_admission_test.go| index 3ca20d135..e87202e89 100644 |
| --- a/internal/host/group_admission_test.go |
| +++ b/internal/host/group_admission_test.go |
| @@ -57,7 +57,7 @@ func TestAdmissionFixedOptIn(t *testing.T) { |
| } |
| a := newFixedAdmission(get, admissionHealth()) |
| svc := activator.New(activator.Config{}, nil, nil) |
| - eb := &activator.ExecBackend{} |
| + eb := &activator.ExecBackend{ServedPools: testSharedPoolEvidence} |
| a.bind(svc, eb) |
| if a == nil || a.refusal == "" || svc.TenantAdmitted() || svc.TenantStartAllowed() { |
| t.Fatal(v) |
| @@ -96,7 +96,7 @@ func TestAdmissionFlagshipUnchanged(t *testing.T) { |
| } |
| svc := activator.New(activator.Config{}, nil, nil) |
| var a *fixedAdmission |
| - a.bind(svc, &activator.ExecBackend{}) |
| + a.bind(svc, &activator.ExecBackend{ServedPools: testSharedPoolEvidence}) |
| if svc.TenantStartAllowed != nil || svc.TenantAdmittedFunc != nil || !svc.TenantAdmitted() { |
| t.Fatal("switch-off callbacks") |
| } |
diff --git a/internal/host/hadepartures_production_test.go b/internal/host/hadepartures_production_test.go| index 36d0e2d96..27bac03ae 100644 |
| --- a/internal/host/hadepartures_production_test.go |
| +++ b/internal/host/hadepartures_production_test.go |
| @@ -389,7 +389,11 @@ func testDepartureTwoQueueImporters(t *testing.T) { |
| cfg := activator.Config{Bucket: "data", Region: "eu-west-1", Prefix: "instances", Record: func(context.Context, registry.Route) (activator.RecordFacts, error) { |
| return activator.RecordFacts{LifetimeEntry: provision.LifetimeEntry{ID: "life", HA: true}}, nil |
| }} |
| - eb := &activator.ExecBackend{Cfg: cfg, Registry: x.r, DataDir: filepath.Join(t.TempDir(), "data"), RunDirOverride: filepath.Join(t.TempDir(), "run"), FilesStore: files, Control: instancectl.NewClient("/unused/control.sock")} |
| + pools := []string{""} |
| + if x == c { |
| + pools = append(pools, "hapair") |
| + } |
| + eb := &activator.ExecBackend{ServedPools: (provision.ReconcileConfig{Pools: pools}).ServedPools, Cfg: cfg, Registry: x.r, DataDir: filepath.Join(t.TempDir(), "data"), RunDirOverride: filepath.Join(t.TempDir(), "run"), FilesStore: files, Control: instancectl.NewClient("/unused/control.sock")} |
| svc := activator.New(cfg, eb, x.r) |
| svc.DutyStore = x.r |
| if err = lease.SetObligationDir(t.TempDir()); err != nil { |
diff --git a/internal/host/hadepartures_proof_followups_test.go b/internal/host/hadepartures_proof_followups_test.go| index ac34431aa..d9bb05648 100644 |
| --- a/internal/host/hadepartures_proof_followups_test.go |
| +++ b/internal/host/hadepartures_proof_followups_test.go |
| @@ -90,7 +90,7 @@ func TestTerminationProofIdentityRefusals(t *testing.T) { |
| t.Errorf("refusal observation gone=%t err=%v", gone, err) |
| } |
| } |
| - held, err := lease.AcquireHA(lease.WithTerminationProof(t.Context(), a.Backend.TerminationProofs), fx.Bucket, "instances/shop.example.com", a.Self.Scope.CloudRegion, hafresh.Marker{Lifetime: "life"}, hafresh.Proofs{OwnerTerminated: func(iid string) (bool, error) { return a.Confirmer.Terminated(t.Context(), iid) }}) |
| + held, err := lease.AcquireHA(lease.WithTerminationProof(t.Context(), a.Backend.TerminationProofs), fx.Bucket, "instances/shop.example.com", a.Self.Scope.CloudRegion, hafresh.Marker{Lifetime: "life"}, hafresh.Proofs{LocalEligible: func() bool { return true }, OwnerTerminated: func(iid string) (bool, error) { return a.Confirmer.Terminated(t.Context(), iid) }}) |
| if held != nil { |
| defer held.Release(context.Background()) |
| } |
diff --git a/internal/host/hadepartures_wiring_test.go b/internal/host/hadepartures_wiring_test.go| index 866546730..3f0a41320 100644 |
| --- a/internal/host/hadepartures_wiring_test.go |
| +++ b/internal/host/hadepartures_wiring_test.go |
| @@ -89,7 +89,7 @@ func departureArmFixtureBucket(t *testing.T, bucket string) (departureArm, *depa |
| }} |
| env := map[string]string{"CARLOS_REGION_HA": "true", "CARLOS_DEPLOYMENT_BUCKET": "deployment-in-us-east-1", departureBindingsEnv: `{"dead":"i-1123456789abcdef0"}`} |
| cfg := activator.Config{Bucket: bucket, Region: "eu-west-1", Prefix: "instances"} |
| - return departureArm{Getenv: func(k string) string { return env[k] }, Registry: reg, Service: &activator.Service{}, Backend: &activator.ExecBackend{Cfg: cfg}, Confirmer: confirmer, Inventory: &provision.DepartureInventory{}, OpenStore: func(context.Context) (release.Store, error) { return store, nil }, MakeQueue: func(context.Context) (hadeparture.Queue, error) { return &departureEmptyQueue{}, nil }, ProofStore: func(_ context.Context, b, r string) (termfence.ProofStore, error) { |
| + return departureArm{Getenv: func(k string) string { return env[k] }, Registry: reg, Service: &activator.Service{}, Backend: &activator.ExecBackend{ServedPools: (provision.ReconcileConfig{}).ServedPools, Cfg: cfg}, Confirmer: confirmer, Inventory: &provision.DepartureInventory{}, OpenStore: func(context.Context) (release.Store, error) { return store, nil }, MakeQueue: func(context.Context) (hadeparture.Queue, error) { return &departureEmptyQueue{}, nil }, ProofStore: func(_ context.Context, b, r string) (termfence.ProofStore, error) { |
| if b != cfg.Bucket || r != cfg.Region { |
| t.Errorf("proof scope %s %s", b, r) |
| } |
| @@ -261,7 +261,7 @@ func TestTerminationProductionLifetimeIncompleteInventory(t *testing.T) { |
| for _, life := range []string{"wrong", "life"} { |
| body, _ := json.Marshal(hafresh.Lock{Generation: 1, Owner: hafresh.OwnerFor(hafresh.Self{Ref: "dead", IID: o.Box.InstanceID}, 1, true), ExpiresAt: time.Now().Add(-time.Hour)}) |
| fx.PutLock("instances/shop.example.com", body) |
| - held, e := lease.AcquireHA(lease.WithTerminationProof(ctx, a.Backend.TerminationProofs), fx.Bucket, "instances/shop.example.com", a.Self.Scope.CloudRegion, hafresh.Marker{Lifetime: life}, hafresh.Proofs{}) |
| + held, e := lease.AcquireHA(lease.WithTerminationProof(ctx, a.Backend.TerminationProofs), fx.Bucket, "instances/shop.example.com", a.Self.Scope.CloudRegion, hafresh.Marker{Lifetime: life}, hafresh.Proofs{LocalEligible: func() bool { return true }}) |
| if life == "wrong" { |
| if e == nil { |
| _ = held.Release(ctx) |
| @@ -606,7 +606,7 @@ func TestTerminationUnboundFixedPeerFallback(t *testing.T) { |
| } |
| body, _ := json.Marshal(hafresh.Lock{Generation: 1, Owner: hafresh.OwnerFor(hafresh.Self{Ref: "dead", IID: "i-1123456789abcdef0"}, 1, true), ExpiresAt: time.Now().Add(-time.Hour)}) |
| fx.PutLock("instances/shop.example.com", body) |
| - held, err := lease.AcquireHA(lease.WithTerminationProof(ctx, a.Backend.TerminationProofs), fx.Bucket, "instances/shop.example.com", a.Self.Scope.CloudRegion, hafresh.Marker{Lifetime: "life"}, hafresh.Proofs{OwnerTerminated: func(iid string) (bool, error) { return a.Backend.OwnerTerminated(ctx, iid) }}) |
| + held, err := lease.AcquireHA(lease.WithTerminationProof(ctx, a.Backend.TerminationProofs), fx.Bucket, "instances/shop.example.com", a.Self.Scope.CloudRegion, hafresh.Marker{Lifetime: "life"}, hafresh.Proofs{LocalEligible: func() bool { return true }, OwnerTerminated: func(iid string) (bool, error) { return a.Backend.OwnerTerminated(ctx, iid) }}) |
| if err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/host/haduties_wiring_test.go b/internal/host/haduties_wiring_test.go| index 7418fb0b7..3ff8cd295 100644 |
| --- a/internal/host/haduties_wiring_test.go |
| +++ b/internal/host/haduties_wiring_test.go |
| @@ -200,7 +200,7 @@ func peerHeldDutyService(t *testing.T, reg *registry.Registry, rt *registry.Rout |
| t.Fatal(err) |
| } |
| index.Merge(map[string]provision.Record{rt.Host: rec}) |
| - b := &activator.ExecBackend{Cfg: activator.Config{Bucket: fx.Bucket}, Registry: reg, Lifetimes: index, DataDir: dataDir, RunDirOverride: dir, Control: dutyNoControl{}, StartupSwept: func() bool { return true }} |
| + b := &activator.ExecBackend{ServedPools: (provision.ReconcileConfig{}).ServedPools, Cfg: activator.Config{Bucket: fx.Bucket}, Registry: reg, Lifetimes: index, DataDir: dataDir, RunDirOverride: dir, Control: dutyNoControl{}, StartupSwept: func() bool { return true }} |
| body, err := json.Marshal(hafresh.Lock{Generation: 1, Owner: hafresh.OwnerFor(hafresh.Self{Ref: "b", IID: "i-b"}, 1, true), ExpiresAt: time.Now().Add(time.Hour)}) |
| if err != nil { |
| t.Fatal(err) |
diff --git a/internal/host/haforward_wiring_test.go b/internal/host/haforward_wiring_test.go| index b8b64598b..c40dcc6cf 100644 |
| --- a/internal/host/haforward_wiring_test.go |
| +++ b/internal/host/haforward_wiring_test.go |
| @@ -40,7 +40,7 @@ func TestAgentActivatorForwards(t *testing.T) { |
| // What the agent assigns: a Service over a SplitBackend. |
| svc := activator.New(activator.Config{Bucket: "hib", Idle: time.Hour}, &activator.SplitBackend{ |
| - Exec: &activator.ExecBackend{}, |
| + Exec: &activator.ExecBackend{ServedPools: testSharedPoolEvidence}, |
| Unit: &activator.UnitBackend{}, |
| }, nil) |
| var act edge.Activator = svc |
diff --git a/internal/host/haplacement_budget_test.go b/internal/host/haplacement_budget_test.go| index 901ca34e1..79cc38b95 100644 |
| --- a/internal/host/haplacement_budget_test.go |
| +++ b/internal/host/haplacement_budget_test.go |
| @@ -330,10 +330,10 @@ func testColdPlacementExpiryEquality(t *testing.T) { |
| now := time.Now() |
| self := hafresh.Self{Ref: "leo", IID: "i-leo", Account: "111122223333", Region: "eu-west-1"} |
| view := hafresh.View{Lock: hafresh.Lock{Generation: 1, Owner: hafresh.OwnerFor(self, 123, true), ExpiresAt: now}} |
| - if d := hafresh.DecideAcquire(view, self, now, hafresh.Proofs{SameBoxEmpty: func() (bool, error) { t.Error("equality requested proof"); return true, nil }}); d.Action != hafresh.ActHeld { |
| + if d := hafresh.DecideAcquire(view, self, now, hafresh.Proofs{LocalEligible: func() bool { return true }, SameBoxEmpty: func() (bool, error) { t.Error("equality requested proof"); return true, nil }}); d.Action != hafresh.ActHeld { |
| t.Fatal("equality was not held", d) |
| } |
| - if d := hafresh.DecideAcquire(view, self, now.Add(time.Nanosecond), hafresh.Proofs{}); d.Action != hafresh.ActRefuse { |
| + if d := hafresh.DecideAcquire(view, self, now.Add(time.Nanosecond), hafresh.Proofs{LocalEligible: func() bool { return true }}); d.Action != hafresh.ActRefuse { |
| t.Fatal("missing proof did not refuse", d) |
| } |
| } |
diff --git a/internal/host/haplacement_root_linux_test.go b/internal/host/haplacement_root_linux_test.go| index d6ede07c9..85dea1c75 100644 |
| --- a/internal/host/haplacement_root_linux_test.go |
| +++ b/internal/host/haplacement_root_linux_test.go |
| @@ -149,7 +149,7 @@ func TestColdPlacementRootAgent(t *testing.T) { |
| lifecycleCheck(t, "files store", err) |
| ctl := coldRootControlClient(t, ref) |
| manager := cgroup.SetupRetaining(t.Logf) |
| - eb := &activator.ExecBackend{Cfg: cfg, Registry: reg, DataDir: "/data", OptDir: "/opt/carlos", FilesStore: files, EscrowKey: haEscrowKey(os.Getenv("CARLOS_SECRETS_KEY")), Control: ctl, Cgroups: manager} |
| + eb := &activator.ExecBackend{ServedPools: testSharedPoolEvidence, Cfg: cfg, Registry: reg, DataDir: "/data", OptDir: "/opt/carlos", FilesStore: files, EscrowKey: haEscrowKey(os.Getenv("CARLOS_SECRETS_KEY")), Control: ctl, Cgroups: manager} |
| if os.Getenv("COLD_ROOT_NO_PROOF") != "1" { |
| deadline := time.Now().Add(time.Minute) |
| for { |
diff --git a/internal/host/haplacement_wiring_test.go b/internal/host/haplacement_wiring_test.go| index b7f0dea8b..043e62b7f 100644 |
| --- a/internal/host/haplacement_wiring_test.go |
| +++ b/internal/host/haplacement_wiring_test.go |
| @@ -375,7 +375,7 @@ func TestColdPlacementProcess(t *testing.T) { |
| if err := reg.Upsert(rt); err != nil { |
| t.Fatal(err) |
| } |
| - backend := &activator.ExecBackend{Cfg: cfg, Registry: reg, DataDir: data, RunDirOverride: run, Control: instancectl.NewClient(filepath.Join(root, "unused-control.sock"))} |
| + backend := &activator.ExecBackend{ServedPools: (provision.ReconcileConfig{}).ServedPools, Cfg: cfg, Registry: reg, DataDir: data, RunDirOverride: run, Control: instancectl.NewClient(filepath.Join(root, "unused-control.sock"))} |
| svc := activator.New(cfg, &activator.SplitBackend{Exec: backend, Unit: &activator.UnitBackend{}}, reg) |
| if _, err := edge.New(reg, svc); err != nil { |
| t.Fatal(err) |
diff --git a/internal/host/instancekey_adoption_test.go b/internal/host/instancekey_adoption_test.go| index cab9fb9c7..09e5f8036 100644 |
| --- a/internal/host/instancekey_adoption_test.go |
| +++ b/internal/host/instancekey_adoption_test.go |
| @@ -53,7 +53,7 @@ func TestAdoptionSurvivesBoxLossWithoutAnotherAdmissionOrRelease(t *testing.T) { |
| tok := strings.Repeat("f", 64) |
| launch := activator.AdoptionLaunch{Writer: writer, KeySHA256: instancekey.Digest(key), Source: instancekey.SourcePlatform, Dir: envDir, Publish: relay.Publish} |
| mux := http.NewServeMux() |
| - (&activator.ExecBackend{}).MountInstanceKeyAdoption(mux, registry.Route{Host: writer.Host, Kind: "instance"}, |
| + (&activator.ExecBackend{ServedPools: testSharedPoolEvidence}).MountInstanceKeyAdoption(mux, registry.Route{Host: writer.Host, Kind: "instance"}, |
| func() (string, error) { return tok, nil }, func() (activator.AdoptionLaunch, bool) { return launch, true }) |
| req := httptest.NewRequest(http.MethodPut, "/instance-key/adoption", strings.NewReader(`{"sha256":"`+instancekey.Digest(key)+`","source":"platform"}`)) |
| req.Header.Set("Authorization", "Bearer "+tok) |
diff --git a/internal/host/interactive_rootrunner_linux_test.go b/internal/host/interactive_rootrunner_linux_test.go| index b8924a462..b21688027 100644 |
| --- a/internal/host/interactive_rootrunner_linux_test.go |
| +++ b/internal/host/interactive_rootrunner_linux_test.go |
| @@ -911,7 +911,7 @@ func TestInteractiveSessionRefusedWhenTheAppDisallows(t *testing.T) { |
| if _, err := appconfig.SetInteractive(context.Background(), wd.store.Store, ixAcct, ixrApps[ixrHostA], false); err != nil { |
| t.Fatal(err) |
| } |
| - eb := &activator.ExecBackend{DataDir: "/data", OptDir: "/opt/carlos", Control: instancectl.NewClient(controlsock.Path)} |
| + eb := &activator.ExecBackend{ServedPools: testSharedPoolEvidence, DataDir: "/data", OptDir: "/opt/carlos", Control: instancectl.NewClient(controlsock.Path)} |
| svc := activator.New(activator.Config{}, &activator.SplitBackend{Exec: eb, Unit: &activator.UnitBackend{OptDir: "/opt/carlos"}}, b.reg) |
| wd.w = newInteractiveWorker(wd.store, b.reg.Get, svc, wd.pub, "runner") |
| wd.w.events = wd.events |
| @@ -1086,7 +1086,7 @@ func ixrSessions(rep *ixrAgentReport, fail func(string, ...any)) { |
| ctx, cancel := context.WithTimeout(context.Background(), 4*time.Minute) |
| defer cancel() |
| ctl := &ixrIntruderControl{Client: instancectl.NewClient(controlsock.Path), host: ixrHostA, got: &rep.Intruder} |
| - eb := &activator.ExecBackend{DataDir: "/data", OptDir: "/opt/carlos", Control: ctl} |
| + eb := &activator.ExecBackend{ServedPools: testSharedPoolEvidence, DataDir: "/data", OptDir: "/opt/carlos", Control: ctl} |
| staged := func(h string) *instancectl.StagedExe { |
| sum := sha256.New() |
| f, err := os.Open(release.VersionPath("/opt/carlos", ixAcct, ixrVersion, ixrApps[h])) |
| @@ -1196,7 +1196,7 @@ func ixrRootfsRun(rep *ixrAgentReport, fail func(string, ...any)) { |
| ctx, cancel := context.WithTimeout(context.Background(), 4*time.Minute) |
| defer cancel() |
| ctl := instancectl.NewClient(controlsock.Path) |
| - eb := &activator.ExecBackend{DataDir: "/data", OptDir: "/opt/carlos", Control: ctl} |
| + eb := &activator.ExecBackend{ServedPools: testSharedPoolEvidence, DataDir: "/data", OptDir: "/opt/carlos", Control: ctl} |
| eb.NestedOK = nestedGate(func() error { return instancefs.SelfCheck("/data") }, instancefs.MountNoSymfollow, ctl.Ready) |
| // A dev box: single tenant here, and overlap deploys on (CARLOS_SWAP=overlap). |
| rf := &agentRootfs{nested: eb.NestedOK, control: ctl, single: true, overlap: true} |
diff --git a/internal/host/interactive_test.go b/internal/host/interactive_test.go| index d99186e7f..c0c77a37c 100644 |
| --- a/internal/host/interactive_test.go |
| +++ b/internal/host/interactive_test.go |
| @@ -1460,7 +1460,7 @@ func TestArmInteractivePassNeedsItsInputs(t *testing.T) { |
| t.Fatal(err) |
| } |
| t.Cleanup(func() { reg.Close() }) |
| - svc := activator.New(activator.Config{Bucket: "test-bucket", Idle: time.Minute}, &activator.ExecBackend{DataDir: t.TempDir()}, reg) |
| + svc := activator.New(activator.Config{Bucket: "test-bucket", Idle: time.Minute}, &activator.ExecBackend{ServedPools: testSharedPoolEvidence, DataDir: t.TempDir()}, reg) |
| t.Setenv("CARLOS_DEPLOYMENT_BUCKET", "") |
| t.Setenv("CARLOS_FLEET", "") |
| t.Setenv("CARLOS_DEPLOYMENT_DIR", t.TempDir()) |
diff --git a/internal/host/lifetime_gating_test.go b/internal/host/lifetime_gating_test.go| index 365f0cbc5..5d0256748 100644 |
| --- a/internal/host/lifetime_gating_test.go |
| +++ b/internal/host/lifetime_gating_test.go |
| @@ -416,7 +416,7 @@ func TestHostConsumersIgnoreAFieldlessRecordBesideASlot(t *testing.T) { |
| if judged { |
| judge = newBoxJudge(claimsOffEnv) |
| } |
| - eb := &activator.ExecBackend{} |
| + eb := &activator.ExecBackend{ServedPools: testSharedPoolEvidence} |
| wireSeedPlacement(eb, false, storeOpener(data), storeOpener(deploy), seedBox{Judge: judge}) |
| err := eb.OnSeedPlaced(context.Background(), rec.Account, rec.App, rec.Host, rec.Seed.ID) |
| if judged { |
diff --git a/internal/host/movesenvskew_test.go b/internal/host/movesenvskew_test.go| index 38855d991..887272a6a 100644 |
| --- a/internal/host/movesenvskew_test.go |
| +++ b/internal/host/movesenvskew_test.go |
| @@ -152,7 +152,7 @@ func TestOlderTargetCannotMatchANewerPin(t *testing.T) { |
| t.Fatal(err) |
| } |
| t.Setenv("HOSTNAME", "b") |
| - env, _, err := (&activator.ExecBackend{DataDir: h.tdir, Region: h.dst}).LaunchEnvironment(h.route) |
| + env, _, err := (&activator.ExecBackend{ServedPools: testSharedPoolEvidence, DataDir: h.tdir, Region: h.dst}).LaunchEnvironment(h.route) |
| if err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/host/moveshome_target_test.go b/internal/host/moveshome_target_test.go| index 37db38b6a..6b7c26981 100644 |
| --- a/internal/host/moveshome_target_test.go |
| +++ b/internal/host/moveshome_target_test.go |
| @@ -79,7 +79,7 @@ func startIntoHomeT3(t *testing.T, h *phase1Harness) { |
| // fixture sets CARLOS_REGION=uk and would have hidden that. |
| func TestHomeTargetT3FromTheRealComposition(t *testing.T) { |
| h := newPhase1Harness(t) |
| - src := &activator.ExecBackend{DataDir: h.cfg.DataDir, Region: h.src} |
| + src := &activator.ExecBackend{ServedPools: testSharedPoolEvidence, DataDir: h.cfg.DataDir, Region: h.src} |
| h.cfg.LaunchEnv = func(string) (map[string]string, map[string]bool, error) { |
| env, instance, _, err := src.LaunchLayers(h.route) |
| return env, instance, err |
| @@ -111,7 +111,7 @@ func TestHomeTargetT3FromTheRealComposition(t *testing.T) { |
| // same production composer given a region. |
| func TestHomeTargetT3RefusesABoxThatSetsARegion(t *testing.T) { |
| h := newPhase1Harness(t) |
| - src := &activator.ExecBackend{DataDir: h.cfg.DataDir, Region: h.src} |
| + src := &activator.ExecBackend{ServedPools: testSharedPoolEvidence, DataDir: h.cfg.DataDir, Region: h.src} |
| h.cfg.LaunchEnv = func(string) (map[string]string, map[string]bool, error) { |
| env, instance, _, err := src.LaunchLayers(h.route) |
| return env, instance, err |
| @@ -806,7 +806,7 @@ func intoHomeMovesOutAgain(t *testing.T, r *intoHomeRun) { |
| // and launch environment. |
| c := h.landingCfg(t) |
| c.LaunchEnv = func(string) (map[string]string, map[string]bool, error) { |
| - env, instance, _, err := (&activator.ExecBackend{DataDir: h.tdir, Region: ""}).LaunchLayers(h.landingHarness.route) |
| + env, instance, _, err := (&activator.ExecBackend{ServedPools: testSharedPoolEvidence, DataDir: h.tdir, Region: ""}).LaunchLayers(h.landingHarness.route) |
| return env, instance, err |
| } |
| c.ReadyProbe, c.StrictNext = h.cfg.ReadyProbe, h.cfg.StrictNext |
diff --git a/internal/host/movesoffline_e2e_test.go b/internal/host/movesoffline_e2e_test.go| index 0a4148b5f..a663ec804 100644 |
| --- a/internal/host/movesoffline_e2e_test.go |
| +++ b/internal/host/movesoffline_e2e_test.go |
| @@ -335,7 +335,7 @@ func newE2EWorld(t *testing.T, opts landOpts) *e2eWorld { |
| shipVersion(t, rs, wd.acct, "app", "v2") |
| lw.promote(sealVersion) |
| lw.bundle(landStore) |
| - lw.ukEB = &activator.ExecBackend{DataDir: lw.uk.dd, OptDir: lw.uk.opt, Region: "uk"} |
| + lw.ukEB = &activator.ExecBackend{ServedPools: testSharedPoolEvidence, DataDir: lw.uk.dd, OptDir: lw.uk.opt, Region: "uk"} |
| lw.arm(lw.uk) |
| w := &e2eWorld{landWorld: lw, t: t, rs: rs, base: ts.URL + "/api/cli/apps/" + wd.acct + "/app/instances/" + offHost + "/move/offline", token: token} |
| @@ -346,7 +346,7 @@ func newE2EWorld(t *testing.T, opts landOpts) *e2eWorld { |
| ie.w.cfg.CarryRequest = moveCarry(bs, bsErr) |
| ie.w.cfg.LaunchLayers = withAgentEnv(e2eIEAgentEnv, ie.w.cfg.LaunchLayers) |
| lw.uk.w.cfg.LaunchLayers = withAgentEnv(e2eUKAgentEnv, lw.ukEB.LaunchLayers) |
| - w.ieEB = &activator.ExecBackend{Cfg: activator.Config{Bucket: sealIE, Region: sealIERegion, Prefix: sealPrefix}, DataDir: ie.dd, OptDir: ie.opt} |
| + w.ieEB = &activator.ExecBackend{ServedPools: testSharedPoolEvidence, Cfg: activator.Config{Bucket: sealIE, Region: sealIERegion, Prefix: sealPrefix}, DataDir: ie.dd, OptDir: ie.opt} |
| // The source at rest, as a box that has served it: rows replicated in |
| // two sessions, then a tail the stop never checkpointed. |
| @@ -366,7 +366,7 @@ func newE2EWorld(t *testing.T, opts landOpts) *e2eWorld { |
| // the same code, from the raw instance directory. |
| ie.w.cfg.LaunchLayers = withAgentEnv(e2eIEAgentEnv, func(rt registry.Route) (map[string]string, map[string]bool, []string, error) { |
| rt.DBPath, rt.Socket = provision.DefaultDBPath(raw, rt.Host), filepath.Join(provision.SocketDir, rt.Host+".sock") |
| - return (&activator.ExecBackend{DataDir: raw}).LaunchLayers(rt) |
| + return (&activator.ExecBackend{ServedPools: testSharedPoolEvidence, DataDir: raw}).LaunchLayers(rt) |
| }) |
| } |
| if opts.noFiles { |
| @@ -924,7 +924,7 @@ func (w *e2eWorld) firstWake() { |
| t.Fatal(err) |
| } |
| rt := w.uk.row(offHost) |
| - eb := &activator.ExecBackend{Cfg: activator.Config{Bucket: sealUK, Region: sealUKRegion, Prefix: sealPrefix}, DataDir: w.uk.dd, OptDir: w.uk.opt, Mirror: m} |
| + eb := &activator.ExecBackend{ServedPools: testSharedPoolEvidence, Cfg: activator.Config{Bucket: sealUK, Region: sealUKRegion, Prefix: sealPrefix}, DataDir: w.uk.dd, OptDir: w.uk.opt, Mirror: m} |
| l, err := eb.Acquire(ctx, *rt) |
| if err != nil { |
| t.Fatalf("the first wake's lease on data-uk: %v", err) |
diff --git a/internal/host/movesoffline_land_test.go b/internal/host/movesoffline_land_test.go| index 5953ea24a..3954d3c2e 100644 |
| --- a/internal/host/movesoffline_land_test.go |
| +++ b/internal/host/movesoffline_land_test.go |
| @@ -140,7 +140,7 @@ func newLandWorldWith(t *testing.T, opts landOpts) *landWorld { |
| lw.bundle(landStore) |
| lw.uk.env["CARLOS_HIBERNATE_REGION"] = sealUKRegion |
| lw.uk.env["CARLOS_RELEASE_PUBKEY"] = pub |
| - lw.ukEB = &activator.ExecBackend{DataDir: lw.uk.dd, OptDir: lw.uk.opt, Region: "uk"} |
| + lw.ukEB = &activator.ExecBackend{ServedPools: testSharedPoolEvidence, DataDir: lw.uk.dd, OptDir: lw.uk.opt, Region: "uk"} |
| lw.arm(lw.uk) |
| // The source at rest, as a box that has served it. |
| @@ -162,7 +162,7 @@ func newLandWorldWith(t *testing.T, opts landOpts) *landWorld { |
| // mount: the same two files, composed by the same code. |
| ie.w.cfg.LaunchLayers = func(rt registry.Route) (map[string]string, map[string]bool, []string, error) { |
| rt.DBPath, rt.Socket = provision.DefaultDBPath(raw, rt.Host), filepath.Join(provision.SocketDir, rt.Host+".sock") |
| - return (&activator.ExecBackend{DataDir: raw}).LaunchLayers(rt) |
| + return (&activator.ExecBackend{ServedPools: testSharedPoolEvidence, DataDir: raw}).LaunchLayers(rt) |
| } |
| } |
| if opts.configKey != "" { |
| @@ -848,7 +848,7 @@ func TestOfflineLandOpenReleasesOnlyWhenEveryItemVerifies(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - eb := &activator.ExecBackend{Cfg: activator.Config{Bucket: "data-uk", Region: "eu-west-2", Prefix: "instances"}, DataDir: lw.uk.dd, OptDir: lw.uk.opt, Mirror: m} |
| + eb := &activator.ExecBackend{ServedPools: testSharedPoolEvidence, Cfg: activator.Config{Bucket: "data-uk", Region: "eu-west-2", Prefix: "instances"}, DataDir: lw.uk.dd, OptDir: lw.uk.opt, Mirror: m} |
| fresh, err := eb.Restore(ctx, *rt) |
| if err != nil || fresh { |
| t.Fatalf("restore: fresh %v, %v", fresh, err) |
diff --git a/internal/host/movesoffline_seal_test.go b/internal/host/movesoffline_seal_test.go| index 15e7d04ba..96d4b7c47 100644 |
| --- a/internal/host/movesoffline_seal_test.go |
| +++ b/internal/host/movesoffline_seal_test.go |
| @@ -125,7 +125,7 @@ func (sw *sealWorld) arm(b *offBox) { |
| sw.fake.Put(bucket, prefix+"/build-state.json", []byte(`{"request":"carried"}`)) |
| return nil |
| } |
| - c.LaunchLayers = (&activator.ExecBackend{DataDir: b.dd}).LaunchLayers |
| + c.LaunchLayers = (&activator.ExecBackend{ServedPools: testSharedPoolEvidence, DataDir: b.dd}).LaunchLayers |
| c.Page = func(_ context.Context, level, subject, body string) error { |
| sw.pages = append(sw.pages, level+": "+subject) |
| sw.bodies = append(sw.bodies, body) |
diff --git a/internal/host/movesparks_test.go b/internal/host/movesparks_test.go| index d67bee1ba..440c08922 100644 |
| --- a/internal/host/movesparks_test.go |
| +++ b/internal/host/movesparks_test.go |
| @@ -670,7 +670,7 @@ func newProdWake(t *testing.T, h *phase1Harness, side prodSide) *prodProbe { |
| // release, and the env report made from that same composition, whose |
| // digest is the launch's move-portable pin. |
| Launch: func(_ context.Context, rt registry.Route) (ClaimServingLaunch, moves.EnvReport, error) { |
| - composed, supplied, _, err := (&activator.ExecBackend{DataDir: side.dataDir, Region: side.code}).LaunchLayers(rt) |
| + composed, supplied, _, err := (&activator.ExecBackend{ServedPools: testSharedPoolEvidence, DataDir: side.dataDir, Region: side.code}).LaunchLayers(rt) |
| if err != nil { |
| return ClaimServingLaunch{}, moves.EnvReport{}, err |
| } |
diff --git a/internal/host/movesphase1_harness_test.go b/internal/host/movesphase1_harness_test.go| index 25dd8a424..bed5440ff 100644 |
| --- a/internal/host/movesphase1_harness_test.go |
| +++ b/internal/host/movesphase1_harness_test.go |
| @@ -566,7 +566,7 @@ func newPhase1Harness(t *testing.T, opts ...p1Option) *phase1Harness { |
| h.cfg.SecretsKey, h.cfg.SecretsPriv, h.cfg.SecretsPub = privB64, priv, priv.PublicKey() |
| h.cfg.LaunchEnv = func(string) (map[string]string, map[string]bool, error) { return h.env, nil, nil } |
| if h.realEnv { |
| - src := &activator.ExecBackend{DataDir: h.cfg.DataDir, Region: h.src} |
| + src := &activator.ExecBackend{ServedPools: testSharedPoolEvidence, DataDir: h.cfg.DataDir, Region: h.src} |
| h.cfg.LaunchEnv = func(string) (map[string]string, map[string]bool, error) { |
| env, instance, _, err := src.LaunchLayers(h.route) |
| return env, instance, err |
diff --git a/internal/host/movesphase1_test.go b/internal/host/movesphase1_test.go| index 4d6d03cec..ef81efe08 100644 |
| --- a/internal/host/movesphase1_test.go |
| +++ b/internal/host/movesphase1_test.go |
| @@ -143,7 +143,7 @@ func TestPhase1IsInertWithTheSwitchOff(t *testing.T) { |
| v = "on" |
| } |
| t.Setenv(moves.SwitchEnv, v) |
| - eb := &activator.ExecBackend{} |
| + eb := &activator.ExecBackend{ServedPools: testSharedPoolEvidence} |
| armMovesPass(activator.Config{}, t.TempDir(), nil, nil, eb, hostwrite.Config{}, ClaimProviders{}, nil, nil, nil) |
| if (eb.Strict != nil) != on { |
| t.Fatalf("switch %v: eb.Strict set = %v", on, eb.Strict != nil) |
diff --git a/internal/host/plan14_generation_backend_root_linux_test.go b/internal/host/plan14_generation_backend_root_linux_test.go| index e1e2873a3..7f2ef44d9 100644 |
| --- a/internal/host/plan14_generation_backend_root_linux_test.go |
| +++ b/internal/host/plan14_generation_backend_root_linux_test.go |
| @@ -134,7 +134,7 @@ func TestPlan14GenerationBackendUnitPayload(t *testing.T) { |
| if err := os.WriteFile(filepath.Join(opt, "write-probe"), nil, 0600); !errors.Is(err, syscall.EROFS) { |
| t.Fatalf("installed agent version namespace is writable: %v", err) |
| } |
| - b := &activator.ExecBackend{OptDir: opt, DataDir: filepath.Join(dir, "data")} |
| + b := &activator.ExecBackend{ServedPools: testSharedPoolEvidence, OptDir: opt, DataDir: filepath.Join(dir, "data")} |
| b.Cfg.HostWrites.Enabled = mode == "on" |
| rt := registry.Route{Host: "worker.example", Kind: "worker", Args: `["run"]`} |
| id, err := release.ResolveLive(opt, rt.Host) |
diff --git a/internal/host/pools_test.go b/internal/host/pools_test.go| new file mode 100644 |
| index 000000000..c89f23bb8 |
| --- /dev/null |
| +++ b/internal/host/pools_test.go |
| @@ -0,0 +1,53 @@ |
| +package host |
| + |
| +import ( |
| + "encoding/json" |
| + "slices" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/edgesfile" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +func TestConfiguredAndPublishedPoolsAgree(t *testing.T) { |
| + for raw, wantPools := range map[string][]string{ |
| + "": {""}, "@shared": {""}, "ha": {"ha"}, "ha,@shared": {"", "ha"}, |
| + "ha,ha,@shared": {"", "ha"}, "INVALID": {}, "INVALID,ha": {"ha"}, |
| + } { |
| + t.Run(raw, func(t *testing.T) { |
| + cfg := provisionTickConfig(func(key string) string { |
| + if key == "CARLOS_POOLS" { |
| + return raw |
| + } |
| + return "" |
| + }) |
| + st, reg := release.NewDirStore(t.TempDir()), edgesTestRegistry(t) |
| + ident := edgesFile{Box: "self", ServedPools: edgesFileServedPools(cfg)} |
| + var last []byte |
| + if err := edgesFilePass(t.Context(), st, reg, ident, "", &last); err != nil { |
| + t.Fatal(err) |
| + } |
| + body, _, err := st.Get(t.Context(), edgesFileKey("self")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var published edgesfile.PlacementView |
| + if err = json.Unmarshal(body, &published); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, pool := range []string{"", "ha", "other"} { |
| + want := slices.Contains(wantPools, pool) |
| + shared, _ := cfg.SharedInstanceEligibility() |
| + if cfg.ServedPools().Serves(pool) != want || published.ServedPools.Serves(pool) != want || (pool == "" && shared != want) { |
| + t.Fatalf("pool %q: published %s config %s", pool, published.ServedPools, cfg.ServedPools()) |
| + } |
| + } |
| + pools, known := published.ServedPools.Pools() |
| + if !known || !slices.Equal(pools, wantPools) { |
| + t.Fatalf("publication %s", body) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func testSharedPoolEvidence() edgesfile.PoolEvidence { return edgesfile.PoolEvidence(`[""]`) } |
diff --git a/internal/host/rawsecretpage_test.go b/internal/host/rawsecretpage_test.go| index 9c6d5b8b9..15c254a8f 100644 |
| --- a/internal/host/rawsecretpage_test.go |
| +++ b/internal/host/rawsecretpage_test.go |
| @@ -17,7 +17,7 @@ func TestARawSecretReportPagesAnOperator(t *testing.T) { |
| type page struct{ level, subject, body string } |
| got := make(chan page, 1) |
| release := make(chan struct{}) |
| - eb := &activator.ExecBackend{} |
| + eb := &activator.ExecBackend{ServedPools: testSharedPoolEvidence} |
| wireRawSecretPages(eb, func(ctx context.Context, level, subject, body string) error { |
| <-release // a slow sink |
| if _, ok := ctx.Deadline(); !ok { |
diff --git a/internal/host/rollout_test.go b/internal/host/rollout_test.go| index 938d3265b..f0ff9552b 100644 |
| --- a/internal/host/rollout_test.go |
| +++ b/internal/host/rollout_test.go |
| @@ -114,7 +114,7 @@ func armableBackend(t *testing.T) *activator.ExecBackend { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - return &activator.ExecBackend{Cgroups: cgm, Control: instancectl.NewClient(filepath.Join(t.TempDir(), "ctl.sock"))} |
| + return &activator.ExecBackend{ServedPools: testSharedPoolEvidence, Cgroups: cgm, Control: instancectl.NewClient(filepath.Join(t.TempDir(), "ctl.sock"))} |
| } |
| func unusedStore(context.Context) (release.Store, error) { return nil, errors.New("unused") } |
| @@ -517,7 +517,7 @@ func TestNoDelegationDeclinesTheFlag(t *testing.T) { |
| } |
| resetRollout(t) |
| forbidPlacementCheck(t) |
| - eb := &activator.ExecBackend{Control: instancectl.NewClient(filepath.Join(t.TempDir(), "ctl.sock"))} |
| + eb := &activator.ExecBackend{ServedPools: testSharedPoolEvidence, Control: instancectl.NewClient(filepath.Join(t.TempDir(), "ctl.sock"))} |
| if swapArming(overlapEnv(pub), eb) { |
| t.Fatal("armed generations with no delegated cgroup subtree") |
| } |
| @@ -668,7 +668,7 @@ func TestSwapArmingDeclinesWhenHostClaimsAreOn(t *testing.T) { |
| t.Cleanup(func() { log.SetOutput(os.Stderr) }) |
| // No cgroups either: the claims check must come first, so the code |
| // says claims, not delegation. |
| - eb := &activator.ExecBackend{Cfg: activator.Config{HostWrites: hostwrite.Config{Enabled: true}}} |
| + eb := &activator.ExecBackend{ServedPools: testSharedPoolEvidence, Cfg: activator.Config{HostWrites: hostwrite.Config{Enabled: true}}} |
| if swapArming(overlapEnv(""), eb) { |
| t.Fatal("armed a box with host claims on") |
| } |
| @@ -687,7 +687,7 @@ func TestSwapArmingDeclinesWhenHostClaimsAreOn(t *testing.T) { |
| func TestSwapArmingIgnoresClaimsWithTheFlagOff(t *testing.T) { |
| resetRollout(t) |
| forbidPlacementCheck(t) |
| - eb := &activator.ExecBackend{Cfg: activator.Config{HostWrites: hostwrite.Config{Enabled: true}}} |
| + eb := &activator.ExecBackend{ServedPools: testSharedPoolEvidence, Cfg: activator.Config{HostWrites: hostwrite.Config{Enabled: true}}} |
| if swapArming(noEnv, eb) || rolloutUnarmed() != "" { |
| t.Fatal("flag off: a claims box must say nothing") |
| } |
diff --git a/internal/host/rolloutdeclined_test.go b/internal/host/rolloutdeclined_test.go| index c198144ad..eee056c54 100644 |
| --- a/internal/host/rolloutdeclined_test.go |
| +++ b/internal/host/rolloutdeclined_test.go |
| @@ -536,7 +536,7 @@ func TestDeclinedBoxRefusesAHeldBuildAtLaunch(t *testing.T) { |
| t.Fatal(err) |
| } |
| writeFailureBook(t, env.dataDir, []rollout.FailureRecord{{Account: release.RouteAccount(rt), App: "fastapp", Build: "v2", Host: "sibling.test"}}, nil) |
| - eb := &activator.ExecBackend{Cfg: activator.Config{Bucket: "test-bucket", Idle: time.Hour}, |
| + eb := &activator.ExecBackend{ServedPools: testSharedPoolEvidence, Cfg: activator.Config{Bucket: "test-bucket", Idle: time.Hour}, |
| OptDir: env.optDir, DataDir: t.TempDir(), RunDirOverride: run} |
| backend := &liveLaunchBackend{eb: eb} |
| svc := activator.New(activator.Config{Bucket: "test-bucket", Idle: time.Hour}, backend, env.reg) |
| @@ -719,7 +719,7 @@ func TestNoLiveExecGateUnlessADeclinedBoxHonoursSomething(t *testing.T) { |
| for name, env := range map[string]func(string) string{"flag off": noEnv, "declined, empty book": nil} { |
| t.Run(name, func(t *testing.T) { |
| t.Setenv("CARLOS_OPT_DIR", t.TempDir()) |
| - eb := &activator.ExecBackend{} |
| + eb := &activator.ExecBackend{ServedPools: testSharedPoolEvidence} |
| svc, reg, dd := rolloutFixtureWith(t, false, &activator.SplitBackend{Exec: eb}) |
| if env == nil { |
| declineWithBook(t, svc, reg, dd) |
| @@ -734,7 +734,7 @@ func TestNoLiveExecGateUnlessADeclinedBoxHonoursSomething(t *testing.T) { |
| } |
| t.Run("declined, a record", func(t *testing.T) { |
| t.Setenv("CARLOS_OPT_DIR", t.TempDir()) |
| - eb := &activator.ExecBackend{} |
| + eb := &activator.ExecBackend{ServedPools: testSharedPoolEvidence} |
| svc, reg, dd := rolloutFixtureWith(t, false, &activator.SplitBackend{Exec: eb}) |
| writeFailureBook(t, dd, []rollout.FailureRecord{{Account: "a", App: "blog", Build: "v2", Host: "sib.example.com"}}, nil) |
| declineWithBook(t, svc, reg, dd) |
diff --git a/internal/host/rootfsstart_test.go b/internal/host/rootfsstart_test.go| index 698503984..50add0cbd 100644 |
| --- a/internal/host/rootfsstart_test.go |
| +++ b/internal/host/rootfsstart_test.go |
| @@ -92,7 +92,7 @@ func TestArmedRootfsGatesRefuseARootfsStartOnASharedBox(t *testing.T) { |
| t.Cleanup(func() { os.RemoveAll(run) }) |
| ctl := &rootfsWireControl{} |
| nestedAsked := 0 |
| - eb := &activator.ExecBackend{Cfg: activator.Config{Bucket: "test-bucket", Idle: time.Hour}, |
| + eb := &activator.ExecBackend{ServedPools: testSharedPoolEvidence, Cfg: activator.Config{Bucket: "test-bucket", Idle: time.Hour}, |
| OptDir: t.TempDir(), DataDir: t.TempDir(), RunDirOverride: run, Control: ctl, |
| NestedOK: func() error { nestedAsked++; return nil }} |
| rf := &agentRootfs{nested: eb.NestedOK, control: ctl, overlap: true} |
diff --git a/internal/host/schedule_wiring_test.go b/internal/host/schedule_wiring_test.go| index 12ab5d7a7..5ed1aeb64 100644 |
| --- a/internal/host/schedule_wiring_test.go |
| +++ b/internal/host/schedule_wiring_test.go |
| @@ -252,7 +252,7 @@ func TestScheduleTokenErrorCarriesNoAbsolutePath(t *testing.T) { |
| func escrowedTickBox(t *testing.T, dd string, reg *registry.Registry, store release.Store, key *ecdh.PrivateKey) *activator.Service { |
| t.Helper() |
| cfg := activator.Config{Bucket: "hib", Idle: time.Hour} |
| - eb := &activator.ExecBackend{Cfg: cfg, OptDir: t.TempDir(), DataDir: dd, FilesStore: store, EscrowKey: key, Registry: reg} |
| + eb := &activator.ExecBackend{ServedPools: testSharedPoolEvidence, Cfg: cfg, OptDir: t.TempDir(), DataDir: dd, FilesStore: store, EscrowKey: key, Registry: reg} |
| return activator.New(cfg, &activator.SplitBackend{Exec: eb, Unit: &activator.UnitBackend{OptDir: t.TempDir()}}, reg) |
| } |
diff --git a/internal/host/seedwiring_test.go b/internal/host/seedwiring_test.go| index 008fd99b9..3540a44a9 100644 |
| --- a/internal/host/seedwiring_test.go |
| +++ b/internal/host/seedwiring_test.go |
| @@ -252,7 +252,7 @@ func TestWireSeedPlacement(t *testing.T) { |
| t.Run("armed", func(t *testing.T) { |
| resetArmedSeedHooks(t) |
| - eb := &activator.ExecBackend{} |
| + eb := &activator.ExecBackend{ServedPools: testSharedPoolEvidence} |
| wireSeedPlacement(eb, true, ok(data), ok(deploy), seedBox{}) |
| if !eb.ClaimArmed || eb.Seeds == nil || eb.OnSeedPlaced == nil { |
| t.Fatalf("ClaimArmed %v Seeds %v OnSeedPlaced set %v", eb.ClaimArmed, eb.Seeds, eb.OnSeedPlaced != nil) |
| @@ -264,7 +264,7 @@ func TestWireSeedPlacement(t *testing.T) { |
| }) |
| t.Run("claims off", func(t *testing.T) { |
| resetArmedSeedHooks(t) |
| - eb := &activator.ExecBackend{ClaimArmed: true} |
| + eb := &activator.ExecBackend{ServedPools: testSharedPoolEvidence, ClaimArmed: true} |
| wireSeedPlacement(eb, false, ok(data), ok(deploy), seedBox{}) |
| if eb.ClaimArmed { |
| t.Fatal("ClaimArmed set with claim control off") |
| @@ -276,7 +276,7 @@ func TestWireSeedPlacement(t *testing.T) { |
| } { |
| t.Run(name, func(t *testing.T) { |
| resetArmedSeedHooks(t) |
| - eb := &activator.ExecBackend{} |
| + eb := &activator.ExecBackend{ServedPools: testSharedPoolEvidence} |
| wireSeedPlacement(eb, true, opens[0], opens[1], seedBox{}) |
| if !eb.ClaimArmed { |
| t.Fatal("ClaimArmed not set when a store failed") |
| @@ -376,7 +376,7 @@ func storeOpener(s release.Store) func() (release.Store, error) { |
| func wiredSeedHooks(t *testing.T, f layout.Fence, reg *registry.Registry, data, deploy release.Store) *provision.SeedHooks { |
| t.Helper() |
| resetArmedSeedHooks(t) |
| - eb := &activator.ExecBackend{NestedOK: func() error { return nil }} |
| + eb := &activator.ExecBackend{ServedPools: testSharedPoolEvidence, NestedOK: func() error { return nil }} |
| wireSeedPlacement(eb, false, storeOpener(data), storeOpener(deploy), seedBox{ |
| Fence: f, Prefix: "instances", Swept: func() bool { return true }, NextFenceGen: fenceGenerations(reg)}) |
| h := armedSeedHooks.Load() |
| @@ -517,7 +517,7 @@ func TestWireSeedPlacementArmsTheSwapAndTheRollback(t *testing.T) { |
| t.Run("armed", func(t *testing.T) { |
| resetArmedSeedHooks(t) |
| - eb := &activator.ExecBackend{NestedOK: func() error { return nestedErr }} |
| + eb := &activator.ExecBackend{ServedPools: testSharedPoolEvidence, NestedOK: func() error { return nestedErr }} |
| wireSeedPlacement(eb, false, storeOpener(data), storeOpener(deploy), box) |
| h := armedSeedHooks.Load() |
| if h == nil || h.Data != release.Store(data) { |
| @@ -555,7 +555,7 @@ func TestWireSeedPlacementArmsTheSwapAndTheRollback(t *testing.T) { |
| }) |
| t.Run("claim control on", func(t *testing.T) { |
| resetArmedSeedHooks(t) |
| - eb := &activator.ExecBackend{NestedOK: func() error { return nil }} |
| + eb := &activator.ExecBackend{ServedPools: testSharedPoolEvidence, NestedOK: func() error { return nil }} |
| wireSeedPlacement(eb, true, storeOpener(data), storeOpener(deploy), box) |
| h := armedSeedHooks.Load() |
| if h == nil || h.Data != release.Store(data) { |
| @@ -572,7 +572,7 @@ func TestWireSeedPlacementArmsTheSwapAndTheRollback(t *testing.T) { |
| }) |
| t.Run("no activator fence", func(t *testing.T) { |
| resetArmedSeedHooks(t) |
| - wireSeedPlacement(&activator.ExecBackend{}, false, storeOpener(data), storeOpener(deploy), seedBox{Prefix: "instances"}) |
| + wireSeedPlacement(&activator.ExecBackend{ServedPools: testSharedPoolEvidence}, false, storeOpener(data), storeOpener(deploy), seedBox{Prefix: "instances"}) |
| h := armedSeedHooks.Load() |
| if h == nil { |
| t.Fatal("no hooks") |
diff --git a/internal/host/stateless_failed_release_test.go b/internal/host/stateless_failed_release_test.go| index c5b4c67ad..2c745ddfb 100644 |
| --- a/internal/host/stateless_failed_release_test.go |
| +++ b/internal/host/stateless_failed_release_test.go |
| @@ -130,7 +130,7 @@ func statelessReleaseHeldProductionWiring(t *testing.T, unknown bool) { |
| open := func(context.Context) (release.Store, error) { return store, nil } |
| facts := haRecordFacts(open, nil) |
| cfg := activator.Config{Bucket: "test", Idle: time.Hour, Record: facts, ReplicaRecord: func(rt registry.Route) (activator.RecordFacts, error) { return facts(ctx, rt) }} |
| - eb := &activator.ExecBackend{Cfg: cfg, DataDir: dir, OptDir: opt, RunDirOverride: filepath.Join(dir, "run"), Control: &rootfsWireControl{}, NestedOK: func() error { return nil }, RootfsOK: func(context.Context) error { return nil }, RootfsPlacement: func(context.Context, registry.Route) error { return nil }} |
| + eb := &activator.ExecBackend{ServedPools: testSharedPoolEvidence, Cfg: cfg, DataDir: dir, OptDir: opt, RunDirOverride: filepath.Join(dir, "run"), Control: &rootfsWireControl{}, NestedOK: func() error { return nil }, RootfsOK: func(context.Context) error { return nil }, RootfsPlacement: func(context.Context, registry.Route) error { return nil }} |
| be := &failedReleaseBackend{plannedBackend: &plannedBackend{socket: healthySocket(t)}, failedReleaseGates: failedReleaseGates{eb}, unknown: unknown} |
| rt := registry.Route{Host: rec.Host, Account: rec.Account, App: rec.App, Kind: "instance", Status: "ready", Channel: rec.Channel, Runtime: rec.Runtime, CreatedAt: rec.CreatedAt.Unix(), Version: "A", Stateless: true, DBPath: provision.NestedDBPath(dir, rec.Host), Socket: filepath.Join(eb.RunDirOverride, "instances", provision.InstanceID(rec.Host), "app.sock")} |
| for _, ver := range []string{"A", "B", "C"} { |
diff --git a/internal/host/stateless_runtime_test.go b/internal/host/stateless_runtime_test.go| index a05313fee..f6494914c 100644 |
| --- a/internal/host/stateless_runtime_test.go |
| +++ b/internal/host/stateless_runtime_test.go |
| @@ -27,7 +27,7 @@ func TestStatelessRuntimeUsesDurableFailureBook(t *testing.T) { |
| target := replicas.Build{Version: "v1", Digest: "manifest"} |
| var first string |
| for restart := 0; restart < 2; restart++ { |
| - svc := activator.New(activator.Config{}, &activator.ExecBackend{}, reg) |
| + svc := activator.New(activator.Config{}, &activator.ExecBackend{ServedPools: testSharedPoolEvidence}, reg) |
| armRolloutAndRelay(context.Background(), func(string) string { return "" }, svc, reg, dir, nil, nil) |
| if svc.ReplicaDeployID == nil { |
| t.Fatal("runtime has no durable deploy ID carrier") |
diff --git a/internal/host/suspects_test.go b/internal/host/suspects_test.go| index 1e8e396bd..4c55bbd73 100644 |
| --- a/internal/host/suspects_test.go |
| +++ b/internal/host/suspects_test.go |
| @@ -54,7 +54,7 @@ func withSuspectMetricBackend(t *testing.T, check func(*testing.T, *activator.Ex |
| root := t.TempDir() |
| synctest.Test(t, func(t *testing.T) { |
| proofs := 0 |
| - b := &activator.ExecBackend{ |
| + b := &activator.ExecBackend{ServedPools: testSharedPoolEvidence, |
| Cfg: activator.Config{Bucket: "locks", Region: "eu-west-1"}, |
| DataDir: filepath.Join(root, "data"), RunDirOverride: filepath.Join(root, "run"), |
| Control: instancectl.NewClient(filepath.Join(root, "unused-control.sock")), |
| @@ -102,7 +102,7 @@ func TestSuspectsFrom(t *testing.T) { |
| if got := count(now.Add(5 * time.Minute)); got != 0 { |
| t.Fatalf("stale refusal: count=%d, want 0", got) |
| } |
| - p.Store(&activator.ExecBackend{}) |
| + p.Store(&activator.ExecBackend{ServedPools: testSharedPoolEvidence}) |
| if got := count(now); got != 0 { |
| t.Fatalf("replacement backend: count=%d, want 0", got) |
| } |
diff --git a/internal/lease/ha.go b/internal/lease/ha.go| index 20fa40046..82901415c 100644 |
| --- a/internal/lease/ha.go |
| +++ b/internal/lease/ha.go |
| @@ -35,6 +35,8 @@ var ErrNoSelf = errors.New("lease: this box's identity (reference, instance id, |
| // AcquireHA is the acquire for HA hosts, and the only one: it never falls |
| // back to litestream's AcquireLease or to the legacy path. |
| // |
| +// Local pool eligibility is required before any client or obligation work. |
| +// |
| // 0. A pending obligation for this key is retried first (one PUT). If it |
| // fails, that *ObligationError is returned and nothing is read. |
| // 1. The lock is read with its ETag and classified (hafresh.DecideAcquire). |
| @@ -71,6 +73,9 @@ func acquireHATTL(ctx context.Context, bucket, prefix, region string, base hafre |
| } |
| func acquireHARestricted(ctx context.Context, bucket, prefix, region string, base hafresh.Marker, p hafresh.Proofs, ttl time.Duration, allow func(hafresh.View) error) (*Held, error) { |
| + if p.LocalEligible == nil || !p.LocalEligible() { |
| + return nil, &RefusedError{Reason: hafresh.ReasonPoolIneligible} |
| + } |
| if !obligationStoreSet() { |
| return nil, ErrNoObligationStore |
| } |
| @@ -104,6 +109,9 @@ func acquireHARestricted(ctx context.Context, bucket, prefix, region string, bas |
| // won is the last round's decision: the one whose write landed. |
| var won hafresh.Decision |
| lease, view, started, err := classifyAndTake(ctx, client, bucket, key, leaser.Owner, ttl, func(v hafresh.View) error { |
| + if p.LocalEligible == nil || !p.LocalEligible() { |
| + return &RefusedError{Reason: hafresh.ReasonPoolIneligible} |
| + } |
| if allow != nil { |
| if err := allow(v); err != nil { |
| return err |
diff --git a/internal/lease/ha_test.go b/internal/lease/ha_test.go| index 4d145146f..3aabeffa9 100644 |
| --- a/internal/lease/ha_test.go |
| +++ b/internal/lease/ha_test.go |
| @@ -91,7 +91,7 @@ func TestAcquireHAMarkerCostsOneGetOnePut(t *testing.T) { |
| fx := leasetest.NewLockFixture(t) |
| body, _ := hafresh.MarkerBody(3, hafresh.Marker{V: 1, Box: "b", IID: "i-b", Clean: true}) |
| fx.PutLock("instances/h", body) |
| - h, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1, Box: "a", IID: "i-a"}, hafresh.Proofs{}) |
| + h, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1, Box: "a", IID: "i-a"}, hafresh.Proofs{LocalEligible: func() bool { return true }}) |
| if err != nil || !h.HA() { |
| t.Fatal(err) |
| } |
| @@ -113,7 +113,7 @@ func TestAcquireHAMarkerCostsOneGetOnePut(t *testing.T) { |
| func TestAcquireHAFirstWakeCostsOneGetOneListOnePut(t *testing.T) { |
| haBox(t) |
| fx := leasetest.NewLockFixture(t) |
| - h, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, hafresh.Proofs{}) |
| + h, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, hafresh.Proofs{LocalEligible: func() bool { return true }}) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -139,7 +139,7 @@ func TestAcquireHAReclassifiesOnConflict(t *testing.T) { |
| fx.BeforeWrite(func(m, k string) { |
| fx.PutLock("instances/h", leaseBody(hafresh.OwnerFor(hafresh.Self{Ref: "c", IID: "i-c"}, 1, true), time.Now().Add(time.Hour))) |
| }) |
| - _, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, hafresh.Proofs{}) |
| + _, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, hafresh.Proofs{LocalEligible: func() bool { return true }}) |
| var held *lease.HeldError |
| if !errors.As(err, &held) || !strings.Contains(held.Owner, "ref=c") { |
| t.Fatalf("did not reclassify: %v", err) |
| @@ -162,7 +162,7 @@ func TestAcquireHAGivesUpAfterThreeRounds(t *testing.T) { |
| } |
| fx.PutLock("instances/h", marker()) |
| fx.BeforeWrite(func(m, k string) { fx.PutLock("instances/h", marker()) }) |
| - if _, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, hafresh.Proofs{}); err == nil { |
| + if _, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, hafresh.Proofs{LocalEligible: func() bool { return true }}); err == nil { |
| t.Fatal("acquired a lock that never held still") |
| } |
| want := slices.Repeat([]string{"GET instances/h/lock.json", "PUT instances/h/lock.json"}, 3) |
| @@ -175,7 +175,7 @@ func TestAcquireHAFirstWakeRefusesLeftovers(t *testing.T) { |
| haBox(t) |
| fx := leasetest.NewLockFixture(t) |
| fx.PutObject("instances/h/files/0/manifest.json", []byte(`{}`)) |
| - _, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, hafresh.Proofs{}) |
| + _, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, hafresh.Proofs{LocalEligible: func() bool { return true }}) |
| var r *lease.RefusedError |
| if !errors.As(err, &r) || r.Reason != lease.ReasonLeftoverData || slices.ContainsFunc(fx.Requests(), func(s string) bool { return strings.HasPrefix(s, "PUT") }) { |
| t.Fatal(err) |
| @@ -188,7 +188,7 @@ func TestAcquireHARefusesWithoutWriting(t *testing.T) { |
| other := hafresh.OwnerFor(hafresh.Self{Ref: "b", IID: "i-b"}, 9, true) |
| mine := hafresh.OwnerFor(hafresh.Self{Ref: "a", IID: "i-a", Account: "111122223333", Region: "eu-west-1"}, 9, true) |
| empty := func(ok bool) hafresh.Proofs { |
| - return hafresh.Proofs{SameBoxEmpty: func() (bool, error) { return ok, nil }} |
| + return hafresh.Proofs{LocalEligible: func() bool { return true }, SameBoxEmpty: func() (bool, error) { return ok, nil }} |
| } |
| for _, c := range []struct { |
| name string |
| @@ -236,7 +236,7 @@ func TestAcquireHARefusesWithoutSelf(t *testing.T) { |
| t.Fatal(err) |
| } |
| fx := leasetest.NewLockFixture(t) |
| - if _, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, hafresh.Proofs{}); !errors.Is(err, lease.ErrNoSelf) || len(fx.Requests()) != 0 { |
| + if _, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, hafresh.Proofs{LocalEligible: func() bool { return true }}); !errors.Is(err, lease.ErrNoSelf) || len(fx.Requests()) != 0 { |
| t.Fatal(err) |
| } |
| } |
| @@ -256,7 +256,7 @@ func TestAcquireHARefusesWithoutInstanceID(t *testing.T) { |
| t.Fatal(err) |
| } |
| fx := leasetest.NewLockFixture(t) |
| - if _, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, hafresh.Proofs{}); !errors.Is(err, lease.ErrNoSelf) || len(fx.Requests()) != 0 { |
| + if _, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, hafresh.Proofs{LocalEligible: func() bool { return true }}); !errors.Is(err, lease.ErrNoSelf) || len(fx.Requests()) != 0 { |
| t.Fatalf("%+v: %v after %v", self, err, fx.Requests()) |
| } |
| } |
| @@ -269,7 +269,7 @@ func TestAcquireHALateAckWritesUncleanMarker(t *testing.T) { |
| haBox(t) |
| fx := leasetest.NewLockFixture(t) |
| delayPutAck(t, fx, 4*time.Second) |
| - if _, err := lease.AcquireHATTL(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1, Box: "a", IID: "i-a"}, hafresh.Proofs{}, 3*time.Second); err == nil { |
| + if _, err := lease.AcquireHATTL(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1, Box: "a", IID: "i-a"}, hafresh.Proofs{LocalEligible: func() bool { return true }}, 3*time.Second); err == nil { |
| t.Fatal("late ack accepted") |
| } |
| v, _ := hafresh.DecodeLock(fx.LockBody("instances/h"), "") |
| @@ -352,7 +352,7 @@ func TestHAAcquireRefusedWithoutObligationStore(t *testing.T) { |
| t.Cleanup(lease.ResetForTest) |
| lease.SetSelf(hafresh.Self{Ref: "a", IID: "i-a", Account: "111122223333", Region: "eu-west-1"}) |
| fx := leasetest.NewLockFixture(t) |
| - if _, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, hafresh.Proofs{}); !errors.Is(err, lease.ErrNoObligationStore) || len(fx.Requests()) != 0 { |
| + if _, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, hafresh.Proofs{LocalEligible: func() bool { return true }}); !errors.Is(err, lease.ErrNoObligationStore) || len(fx.Requests()) != 0 { |
| t.Fatal(err) |
| } |
| } |
| @@ -370,7 +370,7 @@ func TestAcquireCleanupObligationSurvivesRestart(t *testing.T) { |
| delayPutAck(t, fx, 4*time.Second) // the acquire's PUT |
| // The marker's PUT fails with an error the SDK does not retry. |
| fx.FailNextMatching(http.MethodPut, http.StatusForbidden, func(_ string, b []byte) bool { return bytes.Contains(b, []byte("carlos_release")) }) |
| - _, err := lease.AcquireHATTL(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1, Box: "a", IID: "i-a"}, hafresh.Proofs{}, 3*time.Second) |
| + _, err := lease.AcquireHATTL(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1, Box: "a", IID: "i-a"}, hafresh.Proofs{LocalEligible: func() bool { return true }}, 3*time.Second) |
| var oe *lease.ObligationError |
| if !errors.As(err, &oe) || len(dirFiles(t, dir)) != 1 { |
| t.Fatalf("not persisted: %v", err) |
| @@ -380,7 +380,7 @@ func TestAcquireCleanupObligationSurvivesRestart(t *testing.T) { |
| if err := lease.SetObligationDir(dir); err != nil || len(lease.PendingObligations()) != 1 { |
| t.Fatalf("not loaded: %v", err) |
| } |
| - h, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1, Box: "a", IID: "i-a"}, hafresh.Proofs{}) |
| + h, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1, Box: "a", IID: "i-a"}, hafresh.Proofs{LocalEligible: func() bool { return true }}) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -403,12 +403,12 @@ func TestAcquireHAWithAFailingObligationReadsNothing(t *testing.T) { |
| fx := leasetest.NewLockFixture(t) |
| delayPutAck(t, fx, 2*time.Second) |
| fx.FailNextMatching(http.MethodPut, http.StatusForbidden, func(_ string, b []byte) bool { return bytes.Contains(b, []byte("carlos_release")) }) |
| - if _, err := lease.AcquireHATTL(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, hafresh.Proofs{}, time.Second); err == nil { |
| + if _, err := lease.AcquireHATTL(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, hafresh.Proofs{LocalEligible: func() bool { return true }}, time.Second); err == nil { |
| t.Fatal("late ack accepted") |
| } |
| fx.FailNextMatching(http.MethodPut, http.StatusForbidden, func(_ string, b []byte) bool { return bytes.Contains(b, []byte("carlos_release")) }) |
| before := len(fx.Requests()) |
| - _, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, hafresh.Proofs{}) |
| + _, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, hafresh.Proofs{LocalEligible: func() bool { return true }}) |
| var oe *lease.ObligationError |
| if !errors.As(err, &oe) { |
| t.Fatal(err) |
| @@ -452,7 +452,7 @@ func TestAcquireHALogsTheWinningRule(t *testing.T) { |
| other := hafresh.OwnerFor(hafresh.Self{Ref: "b", IID: "i-b"}, 7, true) |
| clean, _ := hafresh.MarkerBody(3, hafresh.Marker{V: 1, Box: "b", IID: "i-b", Clean: true}) |
| unclean, _ := hafresh.MarkerBody(3, hafresh.Marker{V: 1, Box: "b", IID: "i-b"}) |
| - proofs := hafresh.Proofs{ |
| + proofs := hafresh.Proofs{LocalEligible: func() bool { return true }, |
| SameBoxEmpty: func() (bool, error) { return true, nil }, |
| OwnerTerminated: func(iid string) (bool, error) { return iid == "i-b", nil }, |
| } |
diff --git a/internal/lease/haduty_test.go b/internal/lease/haduty_test.go| index 3ab01a683..c1a382cfa 100644 |
| --- a/internal/lease/haduty_test.go |
| +++ b/internal/lease/haduty_test.go |
| @@ -31,11 +31,11 @@ func TestDutyAcquireRestrictionOnly(t *testing.T) { |
| } |
| denied := errors.New("duty-denied") |
| calls := 0 |
| - _, err := lease.AcquireHAForDuty(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{}, hafresh.Proofs{}, func(hafresh.View) error { calls++; return denied }) |
| + _, err := lease.AcquireHAForDuty(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{}, hafresh.Proofs{LocalEligible: func() bool { return true }}, func(hafresh.View) error { calls++; return denied }) |
| if !errors.Is(err, denied) || calls != 1 || len(writes(fx)) != 0 { |
| t.Fatalf("err=%v calls=%d writes=%v", err, calls, writes(fx)) |
| } |
| - h, err := lease.AcquireHAForDuty(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{}, hafresh.Proofs{}, func(hafresh.View) error { return nil }) |
| + h, err := lease.AcquireHAForDuty(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{}, hafresh.Proofs{LocalEligible: func() bool { return true }}, func(hafresh.View) error { return nil }) |
| if state == "absent" || state == "marker" { |
| if err != nil { |
| t.Fatal(err) |
| @@ -63,7 +63,7 @@ func TestDutyAcquireRestrictionOnly(t *testing.T) { |
| } |
| }) |
| calls := 0 |
| - _, err := lease.AcquireHAForDuty(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{}, hafresh.Proofs{}, func(v hafresh.View) error { |
| + _, err := lease.AcquireHAForDuty(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{}, hafresh.Proofs{LocalEligible: func() bool { return true }}, func(v hafresh.View) error { |
| calls++ |
| if v.Lock.Generation != int64(calls+3) { |
| t.Errorf("stale view %+v", v) |
| @@ -90,7 +90,7 @@ func TestDutyAcquireRestrictionOnlyReclassifiedPeer(t *testing.T) { |
| }) |
| denied := errors.New("peer duty refused") |
| calls, proofs := 0, 0 |
| - h, err := lease.AcquireHAForDuty(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{}, hafresh.Proofs{OwnerTerminated: func(string) (bool, error) { proofs++; return true, nil }}, func(v hafresh.View) error { |
| + h, err := lease.AcquireHAForDuty(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{}, hafresh.Proofs{LocalEligible: func() bool { return true }, OwnerTerminated: func(string) (bool, error) { proofs++; return true, nil }}, func(v hafresh.View) error { |
| calls++ |
| if calls == 1 && v.Lock.Release != nil && v.Lock.Release.Box == "a" { |
| return nil |
diff --git a/internal/lease/pools_test.go b/internal/lease/pools_test.go| new file mode 100644 |
| index 000000000..98f42ae83 |
| --- /dev/null |
| +++ b/internal/lease/pools_test.go |
| @@ -0,0 +1,102 @@ |
| +package lease_test |
| + |
| +import ( |
| + "errors" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/hafresh" |
| + "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/lease/locktest" |
| +) |
| + |
| +func TestAcquireHAPoolEligibility(t *testing.T) { |
| + for _, state := range []string{"absent", "clean", "unclean", "lifted", "own expired", "foreign terminated", "unexpired"} { |
| + t.Run(state, func(t *testing.T) { |
| + haBox(t) |
| + fx := locktest.NewLockFixture(t) |
| + switch state { |
| + case "clean", "unclean": |
| + body, _ := hafresh.MarkerBody(3, hafresh.Marker{V: 1, Box: "b", IID: "i-b", Clean: state == "clean"}) |
| + fx.PutLock("instances/h", body) |
| + case "lifted": |
| + fx.PutLock("instances/h", leaseBody("moved:lifted", time.Unix(0, 0))) |
| + case "own expired": |
| + fx.PutLock("instances/h", leaseBody(hafresh.OwnerFor(hafresh.Self{Ref: "a", IID: "i-a"}, 1, true), time.Now().Add(-time.Hour))) |
| + case "foreign terminated", "unexpired": |
| + expires := time.Now().Add(-time.Hour) |
| + if state == "unexpired" { |
| + expires = time.Now().Add(time.Hour) |
| + } |
| + fx.PutLock("instances/h", leaseBody(hafresh.OwnerFor(hafresh.Self{Ref: "b", IID: "i-b"}, 1, true), expires)) |
| + } |
| + calls := 0 |
| + p := hafresh.Proofs{SameBoxEmpty: func() (bool, error) { calls++; return true, nil }, OwnerTerminated: func(string) (bool, error) { calls++; return true, nil }} |
| + h, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{}, p) |
| + if h != nil { |
| + h.Release(ctx) |
| + } |
| + var refused *lease.RefusedError |
| + if !errors.As(err, &refused) || refused.Reason != "ha_pool_ineligible" || len(fx.Requests()) != 0 || calls != 0 { |
| + t.Fatalf("err=%v requests=%v proof calls=%d", err, fx.Requests(), calls) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestPoolWithdrawalBetweenCASRounds(t *testing.T) { |
| + haBox(t) |
| + fx := locktest.NewLockFixture(t) |
| + eligible := true |
| + marker, _ := hafresh.MarkerBody(3, hafresh.Marker{V: 1, Box: "a", IID: "i-a"}) |
| + fx.PutLock("instances/h", marker) |
| + puts, allows := 0, 0 |
| + fx.BeforeWrite(func(method, key string) { |
| + if method == "PUT" { |
| + puts++ |
| + next, _ := hafresh.MarkerBody(4, hafresh.Marker{V: 1, Box: "a", IID: "i-a"}) |
| + fx.PutLock("instances/h", next) |
| + eligible = false |
| + } |
| + }) |
| + p := hafresh.Proofs{LocalEligible: func() bool { return eligible }} |
| + h, err := lease.AcquireHAForDuty(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{}, p, func(hafresh.View) error { allows++; return nil }) |
| + if h != nil { |
| + h.Release(ctx) |
| + } |
| + var refused *lease.RefusedError |
| + if !errors.As(err, &refused) || refused.Reason != hafresh.ReasonPoolIneligible || puts != 1 || allows != 1 { |
| + t.Fatalf("err=%v puts=%d allows=%d", err, puts, allows) |
| + } |
| +} |
| + |
| +func TestPoolRefusalLeavesOwedReleaseForRetry(t *testing.T) { |
| + haBox(t) |
| + now := time.Now() |
| + t.Cleanup(lease.SetOwedClockForTest(func() time.Time { return now })) |
| + fx := locktest.NewLockFixture(t) |
| + h, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{}, hafresh.Proofs{LocalEligible: func() bool { return true }}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + fx.FailNextMatching("PUT", 403, func(_ string, body []byte) bool { return true }) |
| + if err = h.Release(ctx); err == nil { |
| + t.Fatal("release should be owed") |
| + } |
| + if len(lease.PendingObligations()) != 1 { |
| + t.Fatal("missing obligation") |
| + } |
| + before := len(fx.Requests()) |
| + _, err = lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{}, hafresh.Proofs{LocalEligible: func() bool { return false }}) |
| + var refused *lease.RefusedError |
| + if !errors.As(err, &refused) || refused.Reason != hafresh.ReasonPoolIneligible || len(fx.Requests()) != before || len(lease.PendingObligations()) != 1 { |
| + t.Fatalf("err=%v requests=%v", err, fx.Requests()[before:]) |
| + } |
| + now = now.Add(time.Minute) |
| + if err = lease.RetryPending(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(lease.PendingObligations()) != 0 { |
| + t.Fatal("release retry was blocked") |
| + } |
| +} |
diff --git a/internal/lease/release_test.go b/internal/lease/release_test.go| index 91b7678e2..6fcbc2a11 100644 |
| --- a/internal/lease/release_test.go |
| +++ b/internal/lease/release_test.go |
| @@ -34,7 +34,7 @@ func haHeld(t *testing.T, fx *leasetest.LockFixture, prefix string) *lease.Held |
| func haHeldTTL(t *testing.T, fx *leasetest.LockFixture, prefix string, ttl time.Duration) *lease.Held { |
| t.Helper() |
| - h, err := lease.AcquireHATTL(ctx, fx.Bucket, prefix, "", hafresh.Marker{V: 1, Box: "a", IID: "i-a", Lifetime: "L1"}, hafresh.Proofs{}, ttl) |
| + h, err := lease.AcquireHATTL(ctx, fx.Bucket, prefix, "", hafresh.Marker{V: 1, Box: "a", IID: "i-a", Lifetime: "L1"}, hafresh.Proofs{LocalEligible: func() bool { return true }}, ttl) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -412,7 +412,7 @@ func TestMarkerPutIsOneRequestPerAttempt(t *testing.T) { |
| now = t0.Add(time.Minute) |
| attempt("RetryPending", func() error { return lease.RetryPending(ctx) }) |
| attempt("AcquireHA's settle", func() error { |
| - _, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, hafresh.Proofs{}) |
| + _, err := lease.AcquireHA(ctx, fx.Bucket, "instances/h", "", hafresh.Marker{V: 1}, hafresh.Proofs{LocalEligible: func() bool { return true }}) |
| return err |
| }) |
| } |
diff --git a/internal/lease/termination_proof_test.go b/internal/lease/termination_proof_test.go| index deb3b9a94..230b33028 100644 |
| --- a/internal/lease/termination_proof_test.go |
| +++ b/internal/lease/termination_proof_test.go |
| @@ -103,7 +103,7 @@ func TestTerminationProofAcquireOnly(t *testing.T) { |
| body, _ := json.Marshal(hafresh.Lock{Generation: 1, Owner: owner, ExpiresAt: expiry}) |
| fx.PutLock("instances/shop", body) |
| fallback := 0 |
| - p := hafresh.Proofs{OwnerTerminated: func(iid string) (bool, error) { fallback++; return iid == "i-1123456789abcdef0", nil }} |
| + p := hafresh.Proofs{LocalEligible: func() bool { return true }, OwnerTerminated: func(iid string) (bool, error) { fallback++; return iid == "i-1123456789abcdef0", nil }} |
| ctx := WithTerminationProof(context.Background(), adapter) |
| if mode == "equality" || mode == "unbound equality" { |
| v, err := readView(ctx, client, fx.Bucket, "instances/shop/lock.json") |
| @@ -188,7 +188,7 @@ func TestTerminationProofRequestBudget(t *testing.T) { |
| var wg sync.WaitGroup |
| for i := 0; i < 20; i++ { |
| wg.Go(func() { |
| - held, err := AcquireHA(ctx, fx.Bucket, fmt.Sprintf("instances/shop-%d", i), me.Region, hafresh.Marker{Lifetime: "life"}, hafresh.Proofs{}) |
| + held, err := AcquireHA(ctx, fx.Bucket, fmt.Sprintf("instances/shop-%d", i), me.Region, hafresh.Marker{Lifetime: "life"}, hafresh.Proofs{LocalEligible: func() bool { return true }}) |
| if held != nil { |
| _ = held.Release(context.Background()) |
| } |
| @@ -225,7 +225,7 @@ func TestTerminationProofRequestBudget(t *testing.T) { |
| } |
| seconds.Store(10) |
| for i := 0; i < 20; i++ { |
| - held, err := AcquireHA(ctx, fx.Bucket, fmt.Sprintf("instances/shop-%d", i), me.Region, hafresh.Marker{Lifetime: "life"}, hafresh.Proofs{}) |
| + held, err := AcquireHA(ctx, fx.Bucket, fmt.Sprintf("instances/shop-%d", i), me.Region, hafresh.Marker{Lifetime: "life"}, hafresh.Proofs{LocalEligible: func() bool { return true }}) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -267,7 +267,7 @@ func TestRequestConfirmationEnqueuesFromAcquire(t *testing.T) { |
| t.Fatal(err) |
| } |
| view := hafresh.View{Lock: hafresh.Lock{Owner: hafresh.OwnerFor(hafresh.Self{Ref: "departed", IID: "i-1123456789abcdef0"}, 1, true), ExpiresAt: time.Now().Add(-time.Hour)}} |
| - p := bindTerminationProof(WithTerminationProof(t.Context(), adapter), client, fx.Bucket, "instances/shop", me.Region, hafresh.Marker{Lifetime: "life"}, me, view, hafresh.Proofs{}) |
| + p := bindTerminationProof(WithTerminationProof(t.Context(), adapter), client, fx.Bucket, "instances/shop", me.Region, hafresh.Marker{Lifetime: "life"}, me, view, hafresh.Proofs{LocalEligible: func() bool { return true }}) |
| if yes, err := p.OwnerTerminated("i-1123456789abcdef0"); yes || err == nil || notified != 1 { |
| t.Fatalf("journal failure yes=%v err=%v notifications=%d", yes, err, notified) |
| } |
diff --git a/internal/provision/pools_test.go b/internal/provision/pools_test.go| new file mode 100644 |
| index 000000000..5f23871ba |
| --- /dev/null |
| +++ b/internal/provision/pools_test.go |
| @@ -0,0 +1,39 @@ |
| +package provision |
| + |
| +import ( |
| + "slices" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/edgesfile" |
| +) |
| + |
| +func TestConfiguredAndPublishedPoolsAgree(t *testing.T) { |
| + for _, tc := range []struct { |
| + raw string |
| + want []string |
| + }{ |
| + {"", []string{""}}, {"@shared", []string{""}}, {"ha", []string{"ha"}}, |
| + {"ha,@shared", []string{"", "ha"}}, {"ha,ha,@shared,@shared", []string{"", "ha"}}, |
| + {"INVALID,@wrong", []string{}}, {"INVALID,ha", []string{"ha"}}, |
| + } { |
| + t.Run(tc.raw, func(t *testing.T) { |
| + cfg := ReconcileConfig{Pools: ParseBoxPools(tc.raw)} |
| + evidence := cfg.ServedPools() |
| + got, known := evidence.Pools() |
| + if !known || !slices.Equal(got, tc.want) { |
| + t.Fatalf("evidence %s, want %v", evidence, tc.want) |
| + } |
| + for _, pool := range []string{"", "ha", "other", "INVALID"} { |
| + want := slices.Contains(tc.want, pool) |
| + if poolServed(cfg.Pools, pool) != want || evidence.Serves(pool) != want { |
| + t.Errorf("pool %q disagrees", pool) |
| + } |
| + } |
| + }) |
| + } |
| + for _, raw := range []string{"", "null", "[]", "{}", `["ha",null]`, `["ha","ha"]`, `["ha",7]`} { |
| + if edgesfile.PoolEvidence(raw).Serves("ha") { |
| + t.Errorf("remote evidence %q serves ha", raw) |
| + } |
| + } |
| +} |
diff --git a/internal/provision/reconcile.go b/internal/provision/reconcile.go| index a3f953b41..57ce06aa9 100644 |
| --- a/internal/provision/reconcile.go |
| +++ b/internal/provision/reconcile.go |
| @@ -26,6 +26,7 @@ import ( |
| "github.com/carlosframework/platform/internal/demo" |
| "github.com/carlosframework/platform/internal/domains" |
| + "github.com/carlosframework/platform/internal/edgesfile" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| "github.com/carlosframework/platform/internal/seeds" |
| @@ -3469,10 +3470,24 @@ var oddBoxPools sync.Map |
| // convention domains.Config's AppsDomain=="" carries: unconfigured means the |
| // default, not "all". |
| func poolServed(pools []string, pool string) bool { |
| - if len(pools) == 0 { |
| - return pool == "" |
| + return (ReconcileConfig{Pools: pools}).ServedPools().Serves(pool) |
| +} |
| + |
| +// ServedPools normalizes local configuration for publication and admission. |
| +// Unconfigured boxes serve the shared pool; invalid-only configuration serves none. |
| +func (cfg ReconcileConfig) ServedPools() edgesfile.PoolEvidence { |
| + pools := make([]string, 0, len(cfg.Pools)) |
| + if len(cfg.Pools) == 0 { |
| + pools = append(pools, "") |
| + } |
| + for _, p := range cfg.Pools { |
| + if p == "" || ValidPool(p) { |
| + pools = append(pools, p) |
| + } |
| } |
| - return slices.Contains(pools, pool) |
| + slices.Sort(pools) |
| + body, _ := json.Marshal(slices.Compact(pools)) |
| + return edgesfile.PoolEvidence(body) |
| } |
| // SharedInstanceEligibility answers, from this box's own reconcile config, |
diff --git a/internal/sim/regionha/actions_test.go b/internal/sim/regionha/actions_test.go| index 8180914b1..06ca64aa5 100644 |
| --- a/internal/sim/regionha/actions_test.go |
| +++ b/internal/sim/regionha/actions_test.go |
| @@ -49,7 +49,7 @@ func (w *world) decideAcquire(b *box, h string, v hafresh.View) hafresh.Decision |
| } |
| } |
| } |
| - d := hafresh.DecideAcquire(v, b.Self, w.now(), hafresh.Proofs{SameBoxEmpty: proof, OwnerTerminated: w.ownerTerminated}) |
| + d := hafresh.DecideAcquire(v, b.Self, w.now(), hafresh.Proofs{LocalEligible: func() bool { return true }, SameBoxEmpty: proof, OwnerTerminated: w.ownerTerminated}) |
| if !on("expiry-authorizes") && d.Action == hafresh.ActRefuse && d.Reason == hafresh.ReasonOtherExpired { |
| d = hafresh.Decision{Action: hafresh.ActTake, Reason: "expired"} |
| } |
diff --git a/internal/sim/regionha/duties_model_test.go b/internal/sim/regionha/duties_model_test.go| index fec5847dc..c57d8fdd8 100644 |
| --- a/internal/sim/regionha/duties_model_test.go |
| +++ b/internal/sim/regionha/duties_model_test.go |
| @@ -323,7 +323,7 @@ func (d *dutyWorld) adopt(b *dutyBox, s *dutyScan, hi int) bool { |
| if !on("take-before-expiry") || !on("proof-before-expiry") { |
| now = v.Lock.ExpiresAt.Add(time.Nanosecond) |
| } |
| - p := hafresh.Proofs{OwnerTerminated: func(iid string) (bool, error) { |
| + p := hafresh.Proofs{LocalEligible: func() bool { return true }, OwnerTerminated: func(iid string) (bool, error) { |
| if !b.proofs[s.dead] { |
| d.proofReads++ |
| if !d.storeDown && d.proofs[s.dead] { |