region HA P1a Task 2: P0: joining mode, carlos system join and its units removed; group-reference wait kept
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
21 files changed,
+287
−1,930
approved_region_ha_2b_copy_test.go+4 −2internal/host/agent.go+2 −8internal/host/agententry.go+60 −0internal/host/agententry_test.go+86 −0internal/host/bootstrap.go+6 −3internal/host/claimwiring.go+0 −9internal/host/claimwiring_hosting_test.go+0 −58internal/host/host_test.go+0 −2internal/host/joining.go+0 −296internal/host/joining_test.go+0 −412internal/host/joinmode.go+0 −346internal/host/joinmode_test.go+0 −301internal/host/joinroot.go+0 −210internal/host/joinroot_test.go+0 −216internal/host/retiredunits.go+60 −0internal/host/retiredunits_test.go+58 −0internal/host/units/carlos-system-join.path+0 −15internal/host/units/carlos-system-join.service+0 −41region_ha_boundary_test.go+1 −3system.go+1 −5system_test.go+9 −3
diff --git a/approved_region_ha_2b_copy_test.go b/approved_region_ha_2b_copy_test.go| index 4fa248032..56adb3ac8 100644 |
| --- a/approved_region_ha_2b_copy_test.go |
| +++ b/approved_region_ha_2b_copy_test.go |
| @@ -38,8 +38,10 @@ var regionHA2bCopyIDs = func() []string { |
| // regionHA2bCopyBuilt is every id whose text the code or docs carry. The |
| // task that writes a row's text adds its ids here in the same commit, once |
| -// Paul has approved the rows. |
| -var regionHA2bCopyBuilt = []string{"RHB-C1", "RHB-C2", "RHB-C3", "RHB-C4", "RHB-C5", "RHB-C6", "RHB-C7", "RHB-C8", "RHB-C9", "RHB-C10", "RHB-C11", "RHB-C12", "RHB-C13", "RHB-C14", "RHB-C15", "RHB-C16", "RHB-C17", "RHB-C18", "RHB-C64", "RHB-C67", "RHB-C68", "RHB-C19", "RHB-C20", "RHB-C21", "RHB-C22", "RHB-C23", "RHB-C24", "RHB-C25", "RHB-C26", "RHB-C27", "RHB-C28", "RHB-C29", "RHB-C30", "RHB-C31", "RHB-C32", "RHB-C33", "RHB-C34", "RHB-C35", "RHB-C36", "RHB-C37", "RHB-C38", "RHB-C39", "RHB-C40", "RHB-C41", "RHB-C42", "RHB-C43", "RHB-C44", "RHB-C45", "RHB-C46", "RHB-C47", "RHB-C48", "RHB-C49", "RHB-C62", "RHB-C63", "RHB-C50", "RHB-C51", "RHB-C52", "RHB-C53", "RHB-C54", "RHB-C55", "RHB-C56", "RHB-C57", "RHB-C58", "RHB-C59", "RHB-C60", "RHB-C61", "RHB-C69", "RHB-C70", "RHB-C71"} |
| +// Paul has approved the rows. Region HA P1a Task 2 took out the ids of |
| +// carlos system join, its units and its help line (RHB-C40 to RHB-C49, |
| +// RHB-C54, RHB-C62, RHB-C63, RHB-C70, RHB-C71), removed with joining mode. |
| +var regionHA2bCopyBuilt = []string{"RHB-C1", "RHB-C2", "RHB-C3", "RHB-C4", "RHB-C5", "RHB-C6", "RHB-C7", "RHB-C8", "RHB-C9", "RHB-C10", "RHB-C11", "RHB-C12", "RHB-C13", "RHB-C14", "RHB-C15", "RHB-C16", "RHB-C17", "RHB-C18", "RHB-C64", "RHB-C67", "RHB-C68", "RHB-C19", "RHB-C20", "RHB-C21", "RHB-C22", "RHB-C23", "RHB-C24", "RHB-C25", "RHB-C26", "RHB-C27", "RHB-C28", "RHB-C29", "RHB-C30", "RHB-C31", "RHB-C32", "RHB-C33", "RHB-C34", "RHB-C35", "RHB-C36", "RHB-C37", "RHB-C38", "RHB-C39", "RHB-C50", "RHB-C51", "RHB-C52", "RHB-C53", "RHB-C55", "RHB-C56", "RHB-C57", "RHB-C58", "RHB-C59", "RHB-C60", "RHB-C61", "RHB-C69"} |
| func mustParseRegionHA2bRecord(t *testing.T) []copyRow { |
| t.Helper() |
diff --git a/internal/host/agent.go b/internal/host/agent.go| index e28bf3c75..34e832ff6 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -217,17 +217,11 @@ func dataDir() string { |
| // edge.RunWithActivator, which owns the serving loop and blocks until |
| // SIGTERM/SIGINT. |
| // |
| -// With CARLOS_HOST_CLAIM and CARLOS_REGION_HA on, a box that is not yet |
| -// enrolled with its guard armed runs region HA's joining mode instead, and |
| -// RunAgent returns once it can host, so systemd starts it again as the |
| -// claim agent (hostingGate, joining.go). |
| -// |
| -// Before either, a box its region's group launched resolves its group |
| +// Before it starts, a box its region's group launched resolves its group |
| // reference, whatever the switches say: the loops runAgent starts read |
| -// the box's label once and keep it (agentEntry, joining.go). |
| +// the box's label once and keep it (agentEntry, agententry.go). |
| func RunAgent(args []string) { |
| agentEntry(os.Getenv, resolveGroupBoxReference, groupReferenceBackoff, log.Printf, |
| - func() bool { return hostingGate(args) }, |
| func() { runAgent(args, productionClaimFactory) }) |
| } |
diff --git a/internal/host/agententry.go b/internal/host/agententry.go| new file mode 100644 |
| index 000000000..c3945a5b9 |
| --- /dev/null |
| +++ b/internal/host/agententry.go |
| @@ -0,0 +1,60 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "os" |
| + "os/signal" |
| + "syscall" |
| + "time" |
| +) |
| + |
| +// groupReferenceBackoff is how long agentEntry waits after the n-th |
| +// failed read of a group box's reference (n from 1): a second, doubling, |
| +// at most 30 seconds. |
| +func groupReferenceBackoff(n int) time.Duration { |
| + d := time.Second |
| + for ; n > 1 && d < 30*time.Second; n-- { |
| + d *= 2 |
| + } |
| + return min(d, 30*time.Second) |
| +} |
| + |
| +// agentEntry is RunAgent's order. A box its region's group launched (the |
| +// CARLOS_BOX_REFERENCE=group marker) first resolves its group reference, |
| +// whatever the claim and region HA switches say: metricsBoxLabel answers |
| +// "" until it resolves, and the loops runAgent starts (the edges file, |
| +// the registry snapshot, metrics, usage, the layout box, the moves pass) |
| +// read the label once and keep it for the process. It asks IMDS again |
| +// with backoff, logging each failure's cause, until it answers or the |
| +// process is told to stop. Any other box resolves nothing. Then it starts |
| +// the agent (run). |
| +func agentEntry(getenv func(string) string, resolve func() (string, error), backoff func(int) time.Duration, logf func(string, ...any), run func()) { |
| + if groupReferenced(getenv) { |
| + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt) |
| + ok := awaitGroupReference(ctx, resolve, backoff, logf) |
| + stop() |
| + if !ok { |
| + return |
| + } |
| + } |
| + run() |
| +} |
| + |
| +// awaitGroupReference asks resolve until it answers, waiting backoff(n) |
| +// after the n-th failure; false when ctx ends first. |
| +func awaitGroupReference(ctx context.Context, resolve func() (string, error), backoff func(int) time.Duration, logf func(string, ...any)) bool { |
| + for n := 1; ; n++ { |
| + ref, err := resolve() |
| + if err == nil { |
| + logf("agent: this box's group reference is %s", ref) |
| + return true |
| + } |
| + wait := backoff(n) |
| + logf("agent: this box's group reference could not be read from its identity document (attempt %d): %v; the agent starts once it is, asking again in %s", n, err, wait) |
| + select { |
| + case <-ctx.Done(): |
| + return false |
| + case <-time.After(wait): |
| + } |
| + } |
| +} |
diff --git a/internal/host/agententry_test.go b/internal/host/agententry_test.go| new file mode 100644 |
| index 000000000..a63f37cc9 |
| --- /dev/null |
| +++ b/internal/host/agententry_test.go |
| @@ -0,0 +1,86 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/hostactors" |
| + "github.com/carlosframework/platform/internal/hostenv" |
| + "github.com/carlosframework/platform/internal/status" |
| +) |
| + |
| +// Moved from joining_test.go (region HA P1a Task 2). A group box resolves |
| +// its reference before the agent starts, whatever the claim and region HA |
| +// switches say; any other box resolves nothing. |
| +func TestAGroupBoxResolvesItsReferenceBeforeTheAgentStarts(t *testing.T) { |
| + quick := func(int) time.Duration { return time.Millisecond } |
| + for name, tc := range map[string]struct { |
| + env map[string]string |
| + marked bool |
| + }{ |
| + "group box, switches off": {env: map[string]string{hostenv.BoxReference: hostenv.GroupReference}, marked: true}, |
| + "group box, switches on": {env: map[string]string{hostenv.BoxReference: hostenv.GroupReference, "CARLOS_HOST_CLAIM": "1", "CARLOS_REGION_HA": "1", "CARLOS_REGION": "eu-west-1"}, |
| + marked: true}, |
| + "other box, switches off": {env: map[string]string{}}, |
| + "other box, switches on": {env: map[string]string{"CARLOS_HOST_CLAIM": "1", "CARLOS_REGION_HA": "1"}}, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + withGroupIdentity(t, "", "", nil) |
| + asked := 0 |
| + groupIdentity = func() (string, string, error) { |
| + asked++ |
| + if asked < 3 { |
| + return "", "", errors.New("IMDS answered 500") |
| + } |
| + return "123456789012", "i-0a61f580df1acfa65", nil |
| + } |
| + getenv := groupEnv(tc.env) |
| + var lines []string |
| + logf := func(format string, args ...any) { lines = append(lines, fmt.Sprintf(format, args...)) } |
| + ranAt, label := -1, "" |
| + run := func() { ranAt = asked; label = metricsBoxLabel(getenv, "machine-1") } |
| + agentEntry(getenv, resolveGroupBoxReference, quick, logf, run) |
| + want, ref := 0, status.Label("machine-1") |
| + if tc.marked { |
| + want, ref = 3, hostactors.GroupBoxReference("123456789012", "i-0a61f580df1acfa65") |
| + } |
| + if ranAt != want { |
| + t.Fatalf("agent after %d IMDS reads; want %d", ranAt, want) |
| + } |
| + if label != ref { |
| + t.Fatalf("the agent started with label %q, want %q", label, ref) |
| + } |
| + failures := 0 |
| + for _, l := range lines { |
| + if strings.Contains(l, "IMDS answered 500") { |
| + failures++ |
| + } |
| + } |
| + if tc.marked && failures != 2 { |
| + t.Fatalf("logged %d failures with their cause, want 2: %q", failures, lines) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// Moved from joining_test.go (region HA P1a Task 2). |
| +func TestAwaitGroupReferenceStopsWithItsContext(t *testing.T) { |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + cancel() |
| + failing := func() (string, error) { return "", errors.New("IMDS answered 500") } |
| + if awaitGroupReference(ctx, failing, func(int) time.Duration { return time.Hour }, func(string, ...any) {}) { |
| + t.Fatal("a stopped wait reported the reference resolved") |
| + } |
| + var got []time.Duration |
| + for n := 1; n <= 8; n++ { |
| + got = append(got, groupReferenceBackoff(n)) |
| + } |
| + want := []time.Duration{time.Second, 2 * time.Second, 4 * time.Second, 8 * time.Second, 16 * time.Second, 30 * time.Second, 30 * time.Second, 30 * time.Second} |
| + if fmt.Sprint(got) != fmt.Sprint(want) { |
| + t.Fatalf("backoff %v, want %v", got, want) |
| + } |
| +} |
diff --git a/internal/host/bootstrap.go b/internal/host/bootstrap.go| index 9b9427a49..05939e3e8 100644 |
| --- a/internal/host/bootstrap.go |
| +++ b/internal/host/bootstrap.go |
| @@ -166,9 +166,6 @@ const relayUnitName = "carlos-relay.service" |
| var enabledUnits = []string{"carlos-edge.service", relayUnitName, "carlos-adopt.timer", "carlos-adopt.path", "carlos-stage.path", "carlos-restart.path", |
| "carlos-system-update.path", "carlos-system-recover.service", |
| - // Region HA joining (spec 2 §5 step 5.3): root's half, on the agent's |
| - // request. Idle on every box that is not joining. |
| - "carlos-system-join.path", |
| // The isolated-exec mounts (design §3.2): the edge Requires= them. |
| "data-instances.mount", "run-carlos-instances.mount", "run-carlos-logs.mount", |
| // The root instance-control channel (design §5.2); socket-activated, so |
| @@ -527,6 +524,12 @@ func bootstrapWith(root string, consumers []string, planJSON bool) error { |
| } |
| fmt.Fprintf(out, " wrote %s\n", path) |
| } |
| + // Units an earlier build installed and this one no longer ships |
| + // (retiredunits.go): disabled, stopped and removed, so they are not |
| + // left armed behind the units above. |
| + if err := retireUnits(root, retiredUnits); err != nil { |
| + return err |
| + } |
| // On a live root the privileged plan runs BEFORE the tmpfiles conf is |
| // written: the conf's /run/carlos line names socketsGroup, and |
diff --git a/internal/host/claimwiring.go b/internal/host/claimwiring.go| index aef973f15..ecf84a2ca 100644 |
| --- a/internal/host/claimwiring.go |
| +++ b/internal/host/claimwiring.go |
| @@ -10,7 +10,6 @@ import ( |
| "github.com/carlosframework/platform/internal/hostclaim" |
| "github.com/carlosframework/platform/internal/hostguard" |
| "github.com/carlosframework/platform/internal/hostwrite" |
| - "github.com/carlosframework/platform/internal/lbhealth" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/schedule" |
| ) |
| @@ -94,16 +93,8 @@ func (w *ClaimWiring) startRegional(ctx context.Context, serial <-chan struct{}, |
| workerCtx, cancel := context.WithCancel(ctx) |
| w.cancel = cancel |
| w.joined = make(chan struct{}) |
| - // The load balancer's hosting condition (region HA spec 2 §5, §6) is |
| - // this process's mode, as RunAgent's gate chose it (agentHosting): |
| - // the claim agent of an enrolled box with an armed guard. It is set |
| - // before the worker starts and cleared when the worker ends, so a box |
| - // whose claim worker has stopped never answers healthy. |
| - hosting := agentHosting.Load() |
| - lbhealth.Default.SetHosting(hosting) |
| go func() { |
| defer close(w.joined) |
| - defer lbhealth.Default.SetHosting(false) |
| w.Providers.Regional.Loop(workerCtx, serial, report) |
| }() |
| return nil |
diff --git a/internal/host/claimwiring_hosting_test.go b/internal/host/claimwiring_hosting_test.go| deleted file mode 100644 |
| index cb5d95029..000000000 |
| --- a/internal/host/claimwiring_hosting_test.go |
| +++ /dev/null |
| @@ -1,58 +0,0 @@ |
| -package host |
| - |
| -import ( |
| - "testing" |
| - |
| - "github.com/carlosframework/platform/internal/hostwrite" |
| - "github.com/carlosframework/platform/internal/lbhealth" |
| -) |
| - |
| -// Region HA spec 2 §5, §6: the health answer's hosting condition is the |
| -// mode RunAgent's gate chose (agentHosting), held only while the claim |
| -// worker runs. Claim mode off never says hosting, a joining process never |
| -// does, and a hosting box's answer turns 503 when its worker ends. |
| -func TestClaimWiringHostingFollowsTheModeAndTheWorker(t *testing.T) { |
| - lbhealth.Default.SetHosting(false) |
| - was := agentHosting.Load() |
| - t.Cleanup(func() { lbhealth.Default.SetHosting(false); agentHosting.Store(was) }) |
| - |
| - agentHosting.Store(true) |
| - off := &ClaimWiring{} |
| - if err := off.startRegional(t.Context(), nil, nil); err != nil { |
| - t.Fatal(err) |
| - } |
| - if lbhealth.Default.Hosting() { |
| - t.Fatal("claim mode off marked the box hosting") |
| - } |
| - |
| - start := func() *ClaimWiring { |
| - loop := testRegionalLoop{started: make(chan struct{})} |
| - w := &ClaimWiring{Writes: hostwrite.Config{Enabled: true}, Providers: ClaimProviders{Regional: loop}} |
| - if err := w.startRegional(t.Context(), nil, nil); err != nil { |
| - t.Fatal(err) |
| - } |
| - <-loop.started |
| - return w |
| - } |
| - |
| - agentHosting.Store(false) |
| - w := start() |
| - if lbhealth.Default.Hosting() { |
| - t.Fatal("a process that is not hosting marked the box hosting") |
| - } |
| - if err := w.close(t.Context()); err != nil { |
| - t.Fatal(err) |
| - } |
| - |
| - agentHosting.Store(true) |
| - w = start() |
| - if !lbhealth.Default.Hosting() { |
| - t.Fatal("the claim agent of an enrolled box is not hosting") |
| - } |
| - if err := w.close(t.Context()); err != nil { |
| - t.Fatal(err) |
| - } |
| - if lbhealth.Default.Hosting() { |
| - t.Fatal("the box still says hosting after its claim worker ended") |
| - } |
| -} |
diff --git a/internal/host/host_test.go b/internal/host/host_test.go| index 56794f00b..872e958ea 100644 |
| --- a/internal/host/host_test.go |
| +++ b/internal/host/host_test.go |
| @@ -64,8 +64,6 @@ var expectedUnits = []string{ |
| "carlos-restore-verify.timer", |
| "carlos-stage.path", |
| "carlos-stage.service", |
| - "carlos-system-join.path", |
| - "carlos-system-join.service", |
| "carlos-system-recover.service", |
| "carlos-system-update.path", |
| "carlos-system-update.service", |
diff --git a/internal/host/joining.go b/internal/host/joining.go| deleted file mode 100644 |
| index 76176312a..000000000 |
| --- a/internal/host/joining.go |
| +++ /dev/null |
| @@ -1,296 +0,0 @@ |
| -package host |
| - |
| -import ( |
| - "context" |
| - "errors" |
| - "flag" |
| - "io" |
| - "log" |
| - "net/http" |
| - "os" |
| - "os/signal" |
| - "path/filepath" |
| - "runtime" |
| - "strings" |
| - "syscall" |
| - "time" |
| - |
| - "github.com/carlosframework/platform/internal/hostwrite" |
| - "github.com/carlosframework/platform/internal/lbhealth" |
| - "github.com/carlosframework/platform/internal/status" |
| - "github.com/carlosframework/platform/internal/version" |
| -) |
| - |
| -// The agent's joining mode (region HA spec 2 §5 step 4) and the gate that |
| -// chooses it (joinmode.go). |
| -// |
| -// A joining box publishes its signed identity record (boxRecordLoop) and, |
| -// once its guard is armed, its guard-ready report: the private status |
| -// report every hosting box publishes, carrying the guard's facts |
| -// (claimReport). It never publishes an edges file: a box an edges file |
| -// names is referenced, and automatic enrollment refuses a referenced box |
| -// (hostactors references.go, enroll.go). It opens no registry, starts no |
| -// activator and serves no instance. Its only listener is the load |
| -// balancer's health check on the edge's HTTP address, which answers 503: |
| -// lbhealth.Default is never marked hosting here. |
| -// |
| -// When the box is invited it asks root to arm the guard by touching |
| -// joinRequestMarker (carlos-system-join.path). Once a start check finds it |
| -// enrolled and armed, it returns, and RunAgent ends the process so systemd |
| -// starts the agent again, now as the claim agent through the guard. |
| - |
| -// joinEvery is how often joining checks its mode. |
| -const joinEvery = 15 * time.Second |
| - |
| -// joinNudgeEvery is how often joining re-publishes its report or re-asks |
| -// root, at most: the report stays well inside reportFreshness, and root |
| -// is not asked again while it is still arming. While the box stays |
| -// invited with its guard not armed, root is asked again at this interval, |
| -// once a minute: carlos-system-join.path fires only when the marker |
| -// changes, so a carlos system join that failed (an IMDS or store read, |
| -// say) is retried by the next touch, and by nothing else. |
| -const joinNudgeEvery = time.Minute |
| - |
| -// joinRequestMarker is the file carlos-system-join.path watches, under the |
| -// data dir. |
| -const joinRequestMarker = "system-join-requested" |
| - |
| -// joining is one joining run's steps; production's are productionJoining. |
| -type joining struct { |
| - facts modeFacts |
| - every time.Duration |
| - // serve answers the load balancer until ctx ends. |
| - serve func(ctx context.Context) error |
| - // record publishes the box's identity record, retrying until it is in |
| - // place. |
| - record func(ctx context.Context) |
| - // report publishes the guard-ready report. |
| - report func(ctx context.Context) error |
| - // requestArm asks root to arm the guard. |
| - requestArm func() error |
| - logf func(format string, args ...any) |
| -} |
| - |
| -// run joins until the box can host (the decision is returned) or ctx |
| -// ends (the last decision, and ctx's error). |
| -func (j joining) run(ctx context.Context) (modeDecision, error) { |
| - lbhealth.Default.SetHosting(false) |
| - go func() { |
| - if err := j.serve(ctx); err != nil && !errors.Is(err, http.ErrServerClosed) { |
| - j.logf("agent: joining: the load balancer health check is not answered: %v", err) |
| - } |
| - }() |
| - go j.record(ctx) |
| - var last modeDecision |
| - var lastErr string |
| - var nudged time.Time |
| - for { |
| - d, err := selectMode(ctx, j.facts) |
| - now := j.facts.now() |
| - switch { |
| - case err != nil: |
| - if err.Error() != lastErr { |
| - j.logf("agent: joining: %v; checking again", err) |
| - lastErr = err.Error() |
| - } |
| - case d.Mode == modeHosting: |
| - j.logf("agent: joining: %s is enrolled and its guard is armed; restarting as the claim agent", d.Box) |
| - return d, nil |
| - default: |
| - lastErr = "" |
| - if d.Stage != last.Stage || d.Why != last.Why { |
| - j.logf("agent: joining: %s: %s %s", d.Box, d.Stage, d.Why) |
| - nudged = time.Time{} |
| - } |
| - last = d |
| - if now.Sub(nudged) >= joinNudgeEvery { |
| - switch d.Stage { |
| - case stageInvited: |
| - if err := j.requestArm(); err != nil { |
| - j.logf("agent: joining: could not ask root to arm the guard: %v", err) |
| - } |
| - case stageGuardInstalled, stageGuardReady: |
| - if err := j.report(ctx); err != nil { |
| - j.logf("agent: joining: the guard-ready report was not published: %v", err) |
| - } |
| - } |
| - nudged = now |
| - } |
| - } |
| - select { |
| - case <-ctx.Done(): |
| - return last, ctx.Err() |
| - case <-time.After(j.every): |
| - } |
| - } |
| -} |
| - |
| -// productionJoining is joining on a real box. args are the agent's own |
| -// (edge.Run's flags): the health check listens on -http, as the edge will. |
| -func productionJoining(args []string, facts modeFacts, getenv func(string) string) joining { |
| - addr := joiningHTTPAddr(args) |
| - return joining{ |
| - facts: facts, |
| - every: joinEvery, |
| - serve: func(ctx context.Context) error { |
| - srv := &http.Server{Addr: addr, ReadHeaderTimeout: 10 * time.Second, Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| - if !lbhealth.Serve(w, r, lbhealth.Default, time.Now()) { |
| - http.NotFound(w, r) |
| - } |
| - })} |
| - go func() { <-ctx.Done(); _ = srv.Close() }() |
| - return srv.ListenAndServe() |
| - }, |
| - record: func(context.Context) { boxRecordLoop() }, |
| - report: func(ctx context.Context) error { |
| - store, _, err := openStatusStore(ctx, getenv) |
| - if err != nil { |
| - return err |
| - } |
| - p := status.Probes{MachineID: readMachineID(), InstanceID: cachedInstanceID(), Region: strings.TrimSpace(getenv("CARLOS_REGION")), |
| - Release: version.Build, Platform: runtime.GOOS + "-" + runtime.GOARCH, SystemChannel: boxSystemChannel(getenv)} |
| - claimReport(&p) |
| - box := status.CollectBox(nil, p, time.Now()) |
| - if groupReferenced(getenv) { |
| - // Under the group reference the console derives (census |
| - // ruling region-ha-2b), as statusLoop publishes it. |
| - box.Label = facts.box |
| - } |
| - return status.WriteBox(ctx, store, box) |
| - }, |
| - requestArm: func() error { |
| - return os.WriteFile(filepath.Join(dataDir(), joinRequestMarker), []byte(time.Now().UTC().Format(time.RFC3339Nano)+"\n"), 0o644) |
| - }, |
| - logf: log.Printf, |
| - } |
| -} |
| - |
| -// joiningHTTPAddr is the agent's -http flag, ":80" when it is not given. |
| -func joiningHTTPAddr(args []string) string { |
| - fs := flag.NewFlagSet("agent", flag.ContinueOnError) |
| - fs.SetOutput(io.Discard) |
| - addr := fs.String("http", ":80", "") |
| - fs.String("registry", "", "") |
| - fs.String("acme-cache", "", "") |
| - fs.String("https", "", "") |
| - fs.String("fallback", "", "") |
| - fs.Bool("dev", false, "") |
| - _ = fs.Parse(args) |
| - return *addr |
| -} |
| - |
| -// decideAgentMode is RunAgent's gate. With claim mode or region HA off |
| -// there is no joining mode, and the agent hosts as on main. Otherwise it |
| -// selects the mode, waiting out an unknown one, and on joining runs join |
| -// until the box can host or ctx ends; it reports whether this process |
| -// should go on to start the claim agent. |
| -func decideAgentMode(ctx context.Context, getenv func(string) string, open func(context.Context, func(string) string) (modeFacts, error), join func(context.Context, modeFacts, modeDecision) error, wait time.Duration, logf func(string, ...any)) bool { |
| - if !hostwrite.Enabled(getenv) || !regionHAEnabled(getenv) { |
| - return true |
| - } |
| - var last string |
| - note := func(err error) bool { |
| - if err.Error() != last { |
| - logf("agent: mode: %v; checking again", err) |
| - last = err.Error() |
| - } |
| - select { |
| - case <-ctx.Done(): |
| - return false |
| - case <-time.After(wait): |
| - return true |
| - } |
| - } |
| - for { |
| - facts, err := open(ctx, getenv) |
| - if err != nil { |
| - if !note(modeUnknown("the deployment's stores and this box's guard", err)) { |
| - return false |
| - } |
| - continue |
| - } |
| - d, err := selectMode(ctx, facts) |
| - if err != nil { |
| - if !note(err) { |
| - return false |
| - } |
| - continue |
| - } |
| - if d.Mode == modeHosting { |
| - return true |
| - } |
| - logf("agent: %s is joining (%s): it hosts nothing until it is enrolled", d.Box, d.Stage) |
| - if err := join(ctx, facts, d); err != nil && !errors.Is(err, context.Canceled) { |
| - logf("agent: joining: %v", err) |
| - } |
| - return false |
| - } |
| -} |
| - |
| -// hostingGate decides, for RunAgent, whether this process starts the claim |
| -// agent, and records the answer in agentHosting. SIGTERM or SIGINT while |
| -// joining ends the process cleanly. |
| -func hostingGate(args []string) bool { |
| - ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt) |
| - defer stop() |
| - hosting := decideAgentMode(ctx, os.Getenv, productionModeFacts, func(ctx context.Context, facts modeFacts, _ modeDecision) error { |
| - _, err := productionJoining(args, facts, os.Getenv).run(ctx) |
| - return err |
| - }, joinEvery, log.Printf) |
| - agentHosting.Store(hosting) |
| - return hosting |
| -} |
| - |
| -// groupReferenceBackoff is how long agentEntry waits after the n-th |
| -// failed read of a group box's reference (n from 1): a second, doubling, |
| -// at most 30 seconds. |
| -func groupReferenceBackoff(n int) time.Duration { |
| - d := time.Second |
| - for ; n > 1 && d < 30*time.Second; n-- { |
| - d *= 2 |
| - } |
| - return min(d, 30*time.Second) |
| -} |
| - |
| -// agentEntry is RunAgent's order. A box its region's group launched (the |
| -// CARLOS_BOX_REFERENCE=group marker) first resolves its group reference, |
| -// whatever the claim and region HA switches say: metricsBoxLabel answers |
| -// "" until it resolves, and the loops runAgent starts (the edges file, |
| -// the registry snapshot, metrics, usage, the layout box, the moves pass) |
| -// read the label once and keep it for the process. It asks IMDS again |
| -// with backoff, logging each failure's cause, until it answers or the |
| -// process is told to stop. Any other box resolves nothing. Then the gate |
| -// (hostingGate) decides whether this process starts the agent (run). |
| -func agentEntry(getenv func(string) string, resolve func() (string, error), backoff func(int) time.Duration, logf func(string, ...any), gate func() bool, run func()) { |
| - if groupReferenced(getenv) { |
| - ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt) |
| - ok := awaitGroupReference(ctx, resolve, backoff, logf) |
| - stop() |
| - if !ok { |
| - return |
| - } |
| - } |
| - if !gate() { |
| - return |
| - } |
| - run() |
| -} |
| - |
| -// awaitGroupReference asks resolve until it answers, waiting backoff(n) |
| -// after the n-th failure; false when ctx ends first. |
| -func awaitGroupReference(ctx context.Context, resolve func() (string, error), backoff func(int) time.Duration, logf func(string, ...any)) bool { |
| - for n := 1; ; n++ { |
| - ref, err := resolve() |
| - if err == nil { |
| - logf("agent: this box's group reference is %s", ref) |
| - return true |
| - } |
| - wait := backoff(n) |
| - logf("agent: this box's group reference could not be read from its identity document (attempt %d): %v; the agent starts once it is, asking again in %s", n, err, wait) |
| - select { |
| - case <-ctx.Done(): |
| - return false |
| - case <-time.After(wait): |
| - } |
| - } |
| -} |
diff --git a/internal/host/joining_test.go b/internal/host/joining_test.go| deleted file mode 100644 |
| index 03c1df772..000000000 |
| --- a/internal/host/joining_test.go |
| +++ /dev/null |
| @@ -1,412 +0,0 @@ |
| -package host |
| - |
| -import ( |
| - "context" |
| - "errors" |
| - "fmt" |
| - "io" |
| - "io/fs" |
| - "net" |
| - "net/http" |
| - "os" |
| - "path/filepath" |
| - "strings" |
| - "sync" |
| - "testing" |
| - "time" |
| - |
| - "github.com/carlosframework/platform/internal/hostactors" |
| - "github.com/carlosframework/platform/internal/hostenv" |
| - "github.com/carlosframework/platform/internal/hostfloor" |
| - "github.com/carlosframework/platform/internal/lbhealth" |
| - "github.com/carlosframework/platform/internal/status" |
| -) |
| - |
| -// stagedFacts walks a box through the joining stages, one per selectMode |
| -// call: no invitation, invited, guard installed, guard-ready reported, |
| -// then hosting. |
| -type stagedFacts struct { |
| - mu sync.Mutex |
| - calls int |
| - steps []joinFacts |
| -} |
| - |
| -func (s *stagedFacts) facts() modeFacts { |
| - pick := func() joinFacts { |
| - s.mu.Lock() |
| - defer s.mu.Unlock() |
| - i := min(s.calls/5, len(s.steps)-1) // each stage for five checks |
| - s.calls++ |
| - return s.steps[i] |
| - } |
| - cur := joinFacts{} |
| - f := modeFacts{box: "ada-hiking", now: time.Now} |
| - f.enrollment = func() (hostfloor.Enrollment, error) { cur = pick(); return cur.facts().enrollment() } |
| - f.roster = func(ctx context.Context) (hostactors.Roster, error) { return cur.facts().roster(ctx) } |
| - f.guard = func() (hostfloor.Running, error) { return cur.facts().guard() } |
| - f.invited = func(ctx context.Context, b string) (bool, error) { return cur.facts().invited(ctx, b) } |
| - f.report = func(ctx context.Context, b string) (status.Box, error) { return cur.facts().report(ctx, b) } |
| - return f |
| -} |
| - |
| -func freePort(t *testing.T) string { |
| - t.Helper() |
| - l, err := net.Listen("tcp", "127.0.0.1:0") |
| - if err != nil { |
| - t.Skipf("no TCP listener in this sandbox: %v", err) |
| - } |
| - addr := l.Addr().String() |
| - l.Close() |
| - return addr |
| -} |
| - |
| -// Joining publishes no edges file and admits nothing: it answers the load |
| -// balancer 503 throughout, asks root to arm the guard once invited, |
| -// publishes its report once armed, and returns as soon as it can host. |
| -func TestJoiningServes503UntilItCanHostAndPublishesNoEdgesFile(t *testing.T) { |
| - deploy, data := t.TempDir(), t.TempDir() |
| - t.Setenv("CARLOS_DEPLOYMENT_DIR", deploy) |
| - t.Setenv("CARLOS_DATA_DIR", data) |
| - t.Cleanup(func() { lbhealth.Default.SetHosting(false) }) |
| - addr := freePort(t) |
| - f := enrolledFacts() |
| - f.report = freshReport(time.Now()) |
| - steps := &stagedFacts{steps: []joinFacts{{}, {invited: true}, guardInstalled(), func() joinFacts { g := guardInstalled(); g.report = freshReport(time.Now()); return g }(), f}} |
| - j := productionJoining([]string{"-http", addr, "-https", ":0"}, steps.facts(), os.Getenv) |
| - j.every = 20 * time.Millisecond |
| - var mu sync.Mutex |
| - var reports int |
| - records := make(chan struct{}, 1) |
| - j.record = func(context.Context) { records <- struct{}{} } |
| - j.report = func(context.Context) error { mu.Lock(); reports++; mu.Unlock(); return nil } |
| - j.logf = t.Logf |
| - lbhealth.Default.SetHosting(true) // a stale flag from an earlier process state is cleared |
| - done := make(chan modeDecision, 1) |
| - go func() { d, _ := j.run(t.Context()); done <- d }() |
| - // The health check answers 503, naming hosting, while joining. |
| - var body string |
| - for i := 0; i < 100; i++ { |
| - resp, err := http.Get("http://" + addr + lbhealth.Path) |
| - if err == nil { |
| - b, _ := io.ReadAll(resp.Body) |
| - resp.Body.Close() |
| - if resp.StatusCode != http.StatusServiceUnavailable { |
| - t.Fatalf("joining box answered %d", resp.StatusCode) |
| - } |
| - body = string(b) |
| - break |
| - } |
| - time.Sleep(10 * time.Millisecond) |
| - } |
| - if !strings.Contains(body, lbhealth.CondHosting) { |
| - t.Fatalf("health body %q", body) |
| - } |
| - if resp, err := http.Get("http://" + addr + "/"); err != nil || resp.StatusCode != http.StatusNotFound { |
| - t.Fatalf("a joining box served something other than its health check: %v %v", resp, err) |
| - } |
| - select { |
| - case d := <-done: |
| - if d.Mode != modeHosting { |
| - t.Fatalf("returned %+v", d) |
| - } |
| - case <-time.After(10 * time.Second): |
| - t.Fatal("joining never returned") |
| - } |
| - <-records |
| - if _, err := os.Stat(filepath.Join(data, joinRequestMarker)); err != nil { |
| - t.Fatalf("root was never asked to arm the guard: %v", err) |
| - } |
| - mu.Lock() |
| - if reports == 0 { |
| - t.Fatal("the guard-ready report was never published") |
| - } |
| - mu.Unlock() |
| - if lbhealth.Default.Hosting() { |
| - t.Fatal("joining marked the box hosting") |
| - } |
| - err := filepath.WalkDir(deploy, func(p string, d fs.DirEntry, err error) error { |
| - if err == nil && strings.Contains(filepath.ToSlash(p), "control/edges") { |
| - t.Errorf("joining wrote %s", p) |
| - } |
| - return nil |
| - }) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| -} |
| - |
| -func TestDecideAgentMode(t *testing.T) { |
| - on := func(k string) string { |
| - switch k { |
| - case "CARLOS_HOST_CLAIM", "CARLOS_REGION_HA": |
| - return "1" |
| - } |
| - return "" |
| - } |
| - noHA := func(k string) string { |
| - if k == "CARLOS_HOST_CLAIM" { |
| - return "1" |
| - } |
| - return "" |
| - } |
| - never := func(context.Context, func(string) string) (modeFacts, error) { |
| - t.Fatal("facts read with joining mode off") |
| - return modeFacts{}, nil |
| - } |
| - noJoin := func(context.Context, modeFacts, modeDecision) error { t.Fatal("joined"); return nil } |
| - quiet := func(string, ...any) {} |
| - ctx := context.Background() |
| - for name, env := range map[string]func(string) string{"claim off": func(string) string { return "" }, "region HA off": noHA} { |
| - if !decideAgentMode(ctx, env, never, noJoin, time.Millisecond, quiet) { |
| - t.Fatalf("%s: not hosting", name) |
| - } |
| - } |
| - open := func(f joinFacts) func(context.Context, func(string) string) (modeFacts, error) { |
| - return func(context.Context, func(string) string) (modeFacts, error) { return f.facts(), nil } |
| - } |
| - if !decideAgentMode(ctx, on, open(enrolledFacts()), noJoin, time.Millisecond, quiet) { |
| - t.Fatal("an enrolled, armed box does not host") |
| - } |
| - var joined modeDecision |
| - join := func(_ context.Context, _ modeFacts, d modeDecision) error { joined = d; return nil } |
| - if decideAgentMode(ctx, on, open(joinFacts{invited: true}), join, time.Millisecond, quiet) || joined.Stage != stageInvited { |
| - t.Fatalf("an invited box: joined %+v", joined) |
| - } |
| - // Unknown, then known: the gate waits, asks again, and logs the |
| - // reason once. |
| - reads, logs := 0, 0 |
| - flaky := func(context.Context, func(string) string) (modeFacts, error) { |
| - reads++ |
| - f := enrolledFacts() |
| - if reads < 3 { |
| - f.rosterErr = errors.New("connection reset") |
| - } |
| - return f.facts(), nil |
| - } |
| - if !decideAgentMode(ctx, on, flaky, noJoin, time.Millisecond, func(string, ...any) { logs++ }) || reads != 3 || logs != 1 { |
| - t.Fatalf("flaky roster: %d reads, %d log lines", reads, logs) |
| - } |
| - // Stopped while unknown: no claim agent. |
| - stopped, cancel := context.WithCancel(ctx) |
| - cancel() |
| - failing := func(context.Context, func(string) string) (modeFacts, error) { |
| - return modeFacts{}, errors.New("no bucket") |
| - } |
| - if decideAgentMode(stopped, on, failing, noJoin, time.Hour, quiet) { |
| - t.Fatal("a stopped gate started the claim agent") |
| - } |
| -} |
| - |
| -// A failed carlos system join is retried (Task 7's review): the path unit |
| -// fires only when the marker changes, so joining touches it again once a |
| -// minute for as long as the box stays invited with its guard not armed, |
| -// and never more often. Once the guard is armed it stops asking. |
| -func TestJoiningAsksRootAgainEachMinuteWhileInvited(t *testing.T) { |
| - t.Cleanup(func() { lbhealth.Default.SetHosting(false) }) |
| - var mu sync.Mutex |
| - clock, checks := joinNow, 0 |
| - var touches []time.Time |
| - f := joinFacts{invited: true}.facts() |
| - armedAfter := 40 // checks; then the guard is armed and not yet enrolled |
| - f.enrollment = func() (hostfloor.Enrollment, error) { |
| - mu.Lock() |
| - defer mu.Unlock() |
| - if checks >= armedAfter { |
| - return guardInstalled().facts().enrollment() |
| - } |
| - return joinFacts{}.facts().enrollment() |
| - } |
| - f.roster = guardInstalled().facts().roster |
| - f.guard = guardInstalled().facts().guard |
| - f.now = func() time.Time { |
| - mu.Lock() |
| - defer mu.Unlock() |
| - checks++ |
| - clock = clock.Add(20 * time.Second) // each check, 20 seconds on |
| - return clock |
| - } |
| - ctx, cancel := context.WithCancel(t.Context()) |
| - defer cancel() |
| - reported := make(chan struct{}, 1) |
| - j := joining{ |
| - facts: f, |
| - every: time.Millisecond, |
| - serve: func(ctx context.Context) error { <-ctx.Done(); return nil }, |
| - record: func(context.Context) {}, |
| - report: func(context.Context) error { |
| - select { |
| - case reported <- struct{}{}: |
| - default: |
| - } |
| - return nil |
| - }, |
| - requestArm: func() error { |
| - mu.Lock() |
| - touches = append(touches, clock) |
| - mu.Unlock() |
| - return nil |
| - }, |
| - logf: t.Logf, |
| - } |
| - done := make(chan struct{}) |
| - go func() { defer close(done); _, _ = j.run(ctx) }() |
| - select { |
| - case <-reported: |
| - case <-time.After(10 * time.Second): |
| - t.Fatal("the guard was armed and joining never published its report") |
| - } |
| - // A few more checks with the guard armed: no more touches. |
| - for { |
| - mu.Lock() |
| - n := checks |
| - mu.Unlock() |
| - if n >= armedAfter+10 { |
| - break |
| - } |
| - time.Sleep(time.Millisecond) |
| - } |
| - cancel() |
| - <-done |
| - mu.Lock() |
| - defer mu.Unlock() |
| - // 40 checks 20 seconds apart while invited: about 13 minutes, so a |
| - // touch at the first check and then one each minute. |
| - if len(touches) < 12 || len(touches) > 14 { |
| - t.Fatalf("%d touches over %d invited checks: %v", len(touches), armedAfter, touches) |
| - } |
| - for i := 1; i < len(touches); i++ { |
| - if gap := touches[i].Sub(touches[i-1]); gap < joinNudgeEvery || gap >= joinNudgeEvery+20*time.Second { |
| - t.Fatalf("touch %d came %s after the one before; want once a minute", i, gap) |
| - } |
| - } |
| - if last := touches[len(touches)-1]; last.After(joinNow.Add(time.Duration(armedAfter) * 20 * time.Second)) { |
| - t.Fatalf("root was asked again at %s, after the guard was armed", last) |
| - } |
| -} |
| - |
| -// Any error opening the facts (an empty group reference, say) is unknown: |
| -// the gate waits and asks again, and neither joins nor hosts until a |
| -// read answers (Task 6's review). |
| -func TestDecideAgentModeWaitsOutAFactsError(t *testing.T) { |
| - on := func(k string) string { |
| - switch k { |
| - case "CARLOS_HOST_CLAIM", "CARLOS_REGION_HA": |
| - return "1" |
| - } |
| - return "" |
| - } |
| - for name, then := range map[string]joinFacts{"enrolled": enrolledFacts(), "invited": {invited: true}} { |
| - t.Run(name, func(t *testing.T) { |
| - reads, logs, joins := 0, 0, 0 |
| - open := func(context.Context, func(string) string) (modeFacts, error) { |
| - reads++ |
| - if reads < 3 { |
| - return modeFacts{}, errors.New("this box's group reference could not be read") |
| - } |
| - return then.facts(), nil |
| - } |
| - join := func(_ context.Context, _ modeFacts, d modeDecision) error { |
| - if reads < 3 { |
| - t.Fatalf("joined on read %d: %+v", reads, d) |
| - } |
| - joins++ |
| - return nil |
| - } |
| - hosting := decideAgentMode(context.Background(), on, open, join, time.Millisecond, func(string, ...any) { logs++ }) |
| - if reads != 3 || logs < 1 { |
| - t.Fatalf("%d reads, %d log lines", reads, logs) |
| - } |
| - wantHosting, wantJoins := name == "enrolled", 1 |
| - if wantHosting { |
| - wantJoins = 0 |
| - } |
| - if hosting != wantHosting || joins != wantJoins { |
| - t.Fatalf("hosting %t, %d joins; want %t, %d", hosting, joins, wantHosting, wantJoins) |
| - } |
| - }) |
| - } |
| -} |
| - |
| -// Task 6's review (R-A): a group box resolves its reference before the |
| -// gate and before runAgent arms any loop, whatever the switches say, since |
| -// those loops read metricsBoxLabel once and keep it. IMDS that fails twice |
| -// holds everything back until the third read; every failure is logged with |
| -// its cause. Any other box asks IMDS nothing and starts at once. |
| -func TestAGroupBoxResolvesItsReferenceBeforeTheAgentStarts(t *testing.T) { |
| - quick := func(int) time.Duration { return time.Millisecond } |
| - never := func(context.Context, func(string) string) (modeFacts, error) { |
| - t.Fatal("facts read with joining mode off") |
| - return modeFacts{}, nil |
| - } |
| - enrolled := func(context.Context, func(string) string) (modeFacts, error) { return enrolledFacts().facts(), nil } |
| - noJoin := func(context.Context, modeFacts, modeDecision) error { t.Fatal("joined"); return nil } |
| - for name, tc := range map[string]struct { |
| - env map[string]string |
| - facts func(context.Context, func(string) string) (modeFacts, error) |
| - marked bool |
| - }{ |
| - "group box, switches off": {env: map[string]string{hostenv.BoxReference: hostenv.GroupReference}, facts: never, marked: true}, |
| - "group box, switches on": {env: map[string]string{hostenv.BoxReference: hostenv.GroupReference, "CARLOS_HOST_CLAIM": "1", "CARLOS_REGION_HA": "1", "CARLOS_REGION": "eu-west-1"}, |
| - facts: enrolled, marked: true}, |
| - "other box, switches off": {env: map[string]string{}, facts: never}, |
| - "other box, switches on": {env: map[string]string{"CARLOS_HOST_CLAIM": "1", "CARLOS_REGION_HA": "1"}, facts: enrolled}, |
| - } { |
| - t.Run(name, func(t *testing.T) { |
| - withGroupIdentity(t, "", "", nil) |
| - asked := 0 |
| - groupIdentity = func() (string, string, error) { |
| - asked++ |
| - if asked < 3 { |
| - return "", "", errors.New("IMDS answered 500") |
| - } |
| - return "123456789012", "i-0a61f580df1acfa65", nil |
| - } |
| - getenv := groupEnv(tc.env) |
| - var lines []string |
| - logf := func(format string, args ...any) { lines = append(lines, fmt.Sprintf(format, args...)) } |
| - gatedAt, ranAt, label := -1, -1, "" |
| - gate := func() bool { |
| - gatedAt = asked |
| - return decideAgentMode(context.Background(), getenv, tc.facts, noJoin, time.Millisecond, logf) |
| - } |
| - run := func() { ranAt = asked; label = metricsBoxLabel(getenv, "machine-1") } |
| - agentEntry(getenv, resolveGroupBoxReference, quick, logf, gate, run) |
| - want, ref := 0, status.Label("machine-1") |
| - if tc.marked { |
| - want, ref = 3, hostactors.GroupBoxReference("123456789012", "i-0a61f580df1acfa65") |
| - } |
| - if gatedAt != want || ranAt != want { |
| - t.Fatalf("gate after %d IMDS reads, agent after %d; want %d", gatedAt, ranAt, want) |
| - } |
| - if label != ref { |
| - t.Fatalf("the agent started with label %q, want %q", label, ref) |
| - } |
| - failures := 0 |
| - for _, l := range lines { |
| - if strings.Contains(l, "IMDS answered 500") { |
| - failures++ |
| - } |
| - } |
| - if tc.marked && failures != 2 { |
| - t.Fatalf("logged %d failures with their cause, want 2: %q", failures, lines) |
| - } |
| - }) |
| - } |
| -} |
| - |
| -func TestAwaitGroupReferenceStopsWithItsContext(t *testing.T) { |
| - ctx, cancel := context.WithCancel(context.Background()) |
| - cancel() |
| - failing := func() (string, error) { return "", errors.New("IMDS answered 500") } |
| - if awaitGroupReference(ctx, failing, func(int) time.Duration { return time.Hour }, func(string, ...any) {}) { |
| - t.Fatal("a stopped wait reported the reference resolved") |
| - } |
| - var got []time.Duration |
| - for n := 1; n <= 8; n++ { |
| - got = append(got, groupReferenceBackoff(n)) |
| - } |
| - want := []time.Duration{time.Second, 2 * time.Second, 4 * time.Second, 8 * time.Second, 16 * time.Second, 30 * time.Second, 30 * time.Second, 30 * time.Second} |
| - if fmt.Sprint(got) != fmt.Sprint(want) { |
| - t.Fatalf("backoff %v, want %v", got, want) |
| - } |
| -} |
diff --git a/internal/host/joinmode.go b/internal/host/joinmode.go| deleted file mode 100644 |
| index 4f519b46d..000000000 |
| --- a/internal/host/joinmode.go |
| +++ /dev/null |
| @@ -1,346 +0,0 @@ |
| -package host |
| - |
| -import ( |
| - "context" |
| - "encoding/base64" |
| - "encoding/json" |
| - "errors" |
| - "fmt" |
| - "net/http" |
| - "os" |
| - "runtime" |
| - "strings" |
| - "sync/atomic" |
| - "time" |
| - |
| - "github.com/carlosframework/platform/internal/boxid" |
| - "github.com/carlosframework/platform/internal/hostactors" |
| - "github.com/carlosframework/platform/internal/hostfloor" |
| - "github.com/carlosframework/platform/internal/release" |
| - "github.com/carlosframework/platform/internal/status" |
| - "github.com/carlosframework/platform/internal/version" |
| -) |
| - |
| -// Joining and hosting (region HA spec 2 §5, A1-2, A2-4). |
| -// |
| -// With CARLOS_HOST_CLAIM and CARLOS_REGION_HA both on, the agent chooses |
| -// its mode at every start, from three facts and never from one file's |
| -// presence. It hosts only when all three hold: |
| -// |
| -// - /etc/carlos/host-actor.json names this box; |
| -// - the signed roster has an active entry for that enrollment and |
| -// instance; |
| -// - the host lifecycle guard is armed under the roster's floor, with |
| -// this process's own binary one it admits. |
| -// |
| -// Anything else is joining. A joining box hosts nothing, publishes no |
| -// edges file, and answers the load balancer 503 (joining.go). Joining |
| -// resumes from whatever it finds, and each stage names the next step: |
| -// |
| -// - no invitation: the console has not invited the box yet; |
| -// - invited: root arms the guard (carlos system join, joinroot.go); |
| -// - guard installed: the box publishes its guard-ready report; |
| -// - guard-ready reported: the console enrolls the box; |
| -// - held: the roster names this box, but not as an active entry for its |
| -// enrollment and armed guard, or, for a box its region's group |
| -// launched, the instance was stopped and started since the identity |
| -// record it was enrolled on (C3: it must prove its group membership |
| -// again, and never hosts on its old enrollment). Nothing automatic |
| -// can fix that: a held group box answers 503 and the group replaces |
| -// it; an operator sorts out any other. |
| -// |
| -// A fact that cannot be read is never taken as its negative: the mode is |
| -// then unknown (errModeUnknown), and the caller asks again later. |
| - |
| -type agentMode string |
| - |
| -const ( |
| - modeHosting agentMode = "hosting" |
| - modeJoining agentMode = "joining" |
| -) |
| - |
| -type joinStage string |
| - |
| -const ( |
| - stageNoInvitation joinStage = "no invitation" |
| - stageInvited joinStage = "invited" |
| - stageGuardInstalled joinStage = "guard installed" |
| - stageGuardReady joinStage = "guard-ready reported" |
| - stageHeld joinStage = "held" |
| -) |
| - |
| -// modeDecision is one start's answer. Stage and Why are joining's. |
| -type modeDecision struct { |
| - Mode agentMode |
| - Stage joinStage |
| - Box string |
| - Why string |
| -} |
| - |
| -// errModeUnknown is a fact that could not be read: no mode is chosen. |
| -var errModeUnknown = errors.New("agent mode unknown") |
| - |
| -func modeUnknown(what string, err error) error { |
| - return fmt.Errorf("%w: %s could not be read: %v", errModeUnknown, what, err) |
| -} |
| - |
| -// reportFreshness is how old a guard-ready report may be and still count: |
| -// the console's own limit (hostactors.VerifyReport). |
| -const reportFreshness = 15 * time.Minute |
| - |
| -// hostActorPath is the box's enrollment, written by guard-arm. |
| -const hostActorPath = "/etc/carlos/host-actor.json" |
| - |
| -// modeFacts are where selectMode reads from; production's are |
| -// productionModeFacts. |
| -type modeFacts struct { |
| - // box is this box's reference: the label its identity record and its |
| - // status report are published under. |
| - box string |
| - // enrollment reads host-actor.json; os.ErrNotExist when there is none. |
| - enrollment func() (hostfloor.Enrollment, error) |
| - // roster reads the signed roster. |
| - roster func(context.Context) (hostactors.Roster, error) |
| - // guard is the guard's view of this process (hostfloor.Disk.Running). |
| - // hostfloor.ErrFloor or os.ErrNotExist: not armed, or not for this |
| - // binary. |
| - guard func() (hostfloor.Running, error) |
| - // invited reports whether the console has written box's invitation. |
| - invited func(context.Context, string) (bool, error) |
| - // report reads box's own published status report; os.ErrNotExist when |
| - // there is none. |
| - report func(context.Context, string) (status.Box, error) |
| - // relaunch says why this instance is not the launch the roster entry |
| - // row was enrolled on ("" when it is): asked only of a box its |
| - // region's group launched (row.Group set). |
| - relaunch func(context.Context, hostactors.Box) (string, error) |
| - // marked is host.env's group marker (CARLOS_BOX_REFERENCE=group), and |
| - // region its CARLOS_REGION: values from the parameter store, which |
| - // select this box's authority, so they are checked against the signed |
| - // roster before the box hosts (crossCheck). |
| - marked bool |
| - region string |
| - now func() time.Time |
| -} |
| - |
| -// selectMode chooses this start's mode. |
| -func selectMode(ctx context.Context, f modeFacts) (modeDecision, error) { |
| - d := modeDecision{Mode: modeJoining, Box: f.box} |
| - e, err := f.enrollment() |
| - if errors.Is(err, os.ErrNotExist) { |
| - invited, err := f.invited(ctx, f.box) |
| - if err != nil { |
| - return d, modeUnknown("the invitation", err) |
| - } |
| - d.Stage = stageNoInvitation |
| - if invited { |
| - d.Stage = stageInvited |
| - } |
| - return d, nil |
| - } |
| - if err != nil { |
| - return d, modeUnknown(hostActorPath, err) |
| - } |
| - if e.Box != f.box { |
| - d.Stage, d.Why = stageHeld, fmt.Sprintf("%s names %s, not this box (%s)", hostActorPath, e.Box, f.box) |
| - return d, nil |
| - } |
| - r, err := f.roster(ctx) |
| - if err != nil { |
| - return d, modeUnknown("the roster", err) |
| - } |
| - g, err := f.guard() |
| - if err != nil && !errors.Is(err, hostfloor.ErrFloor) && !errors.Is(err, os.ErrNotExist) { |
| - return d, modeUnknown("the host lifecycle guard", err) |
| - } |
| - armed := err == nil && g.GuardReady && g.FloorSHA256 == r.FloorSHA256 |
| - row, listed := r.Boxes[e.Box] |
| - switch { |
| - case listed && row.Enrollment == e.Enrollment && row.Cloud.InstanceID == e.InstanceID && row.State == "active" && armed: |
| - if why := crossCheck(f, row); why != "" { |
| - d.Stage, d.Why = stageHeld, why |
| - return d, nil |
| - } |
| - if row.Group != "" { |
| - why, err := f.relaunch(ctx, row) |
| - if err != nil { |
| - return d, modeUnknown("this instance's launch", err) |
| - } |
| - if why != "" { |
| - d.Stage, d.Why = stageHeld, why |
| - return d, nil |
| - } |
| - } |
| - d.Mode, d.Stage = modeHosting, "" |
| - case listed: |
| - d.Stage = stageHeld |
| - d.Why = fmt.Sprintf("the roster's entry for %s is %s, enrollment %s on %s; this box holds enrollment %s on %s, guard armed %t", |
| - e.Box, row.State, row.Enrollment, row.Cloud.InstanceID, e.Enrollment, e.InstanceID, armed) |
| - case !armed: |
| - // guard-arm writes host-actor.json before it persists the armed |
| - // policy: an arm that was cut off is still the invited stage. |
| - d.Stage = stageInvited |
| - default: |
| - rep, err := f.report(ctx, f.box) |
| - if err != nil && !errors.Is(err, os.ErrNotExist) { |
| - return d, modeUnknown("this box's status report", err) |
| - } |
| - d.Stage = stageGuardInstalled |
| - if err == nil && guardReadyReport(rep, e, g, f.now()) { |
| - d.Stage = stageGuardReady |
| - } |
| - } |
| - return d, nil |
| -} |
| - |
| -// crossCheck says why host.env's authority-selecting values disagree with |
| -// the roster entry the box would host under ("" when they agree). The |
| -// group marker must match whether the console enrolled the box from a |
| -// group, and a group box's CARLOS_REGION must name the region it was |
| -// enrolled in. It is made here, at the agent's use, and not when |
| -// host-env write assembles the file: at boot the box has no roster entry |
| -// to check against (it is not enrolled yet), and before enrollment |
| -// neither value grants anything, since the console derives the box's |
| -// reference and region from its proven instance itself. A box an operator |
| -// enrolled keeps its own CARLOS_REGION, unchecked, as on main. |
| -func crossCheck(f modeFacts, row hostactors.Box) string { |
| - switch { |
| - case f.marked && row.Group == "": |
| - return "host.env marks this box as one its region's group launched, but the roster enrolled it by hand; it does not host" |
| - case !f.marked && row.Group != "": |
| - return "the roster enrolled this box from group " + row.Group + ", but host.env does not mark it so; it does not host" |
| - case f.marked && f.region == "": |
| - return "host.env names no region, but the roster enrolled this box in " + row.Region + "; it does not host" |
| - case f.marked && f.region != row.Region: |
| - return "host.env names region " + f.region + ", but the roster enrolled this box in " + row.Region + "; it does not host" |
| - } |
| - return "" |
| -} |
| - |
| -// relaunched says why current, this instance's identity record read from |
| -// IMDS now, is not the launch row was enrolled on: the record published |
| -// under the box's reference (enrolled) must be the one the roster entry |
| -// binds (its digest), and the two identity documents must name the same |
| -// pendingTime. EC2 sets pendingTime each time an instance enters the |
| -// pending state: at launch, and again at every start after a stop, but |
| -// not at a reboot. "" when they agree. |
| -func relaunched(row hostactors.Box, enrolled []byte, current boxid.Record) string { |
| - if hostfloor.Digest(enrolled) != row.EvidenceSHA256 { |
| - return "the identity record under this box's reference is not the one it was enrolled on" |
| - } |
| - var rec boxid.Record |
| - if json.Unmarshal(enrolled, &rec) != nil { |
| - return "the identity record it was enrolled on cannot be read" |
| - } |
| - then, now := recordPendingTime(rec), recordPendingTime(current) |
| - switch { |
| - case then == "" || now == "": |
| - return "an identity document names no pendingTime, so this launch cannot be matched to its enrollment" |
| - case then != now: |
| - return fmt.Sprintf("this instance was stopped and started since it was enrolled (launched %s, enrolled on the launch of %s): it must prove its group membership again, so it does not host", now, then) |
| - } |
| - return "" |
| -} |
| - |
| -// recordPendingTime is the pendingTime of a record's identity document, "" |
| -// when it has none. |
| -func recordPendingTime(rec boxid.Record) string { |
| - doc, err := base64.StdEncoding.DecodeString(rec.IdentityDocument) |
| - if err != nil { |
| - return "" |
| - } |
| - var d struct { |
| - PendingTime string `json:"pendingTime"` |
| - } |
| - if json.Unmarshal(doc, &d) != nil { |
| - return "" |
| - } |
| - return d.PendingTime |
| -} |
| - |
| -// guardReadyReport reports whether rep is this box's fresh guard-ready |
| -// report for enrollment e under the guard g. |
| -func guardReadyReport(rep status.Box, e hostfloor.Enrollment, g hostfloor.Running, now time.Time) bool { |
| - m := rep.Metrics |
| - return m != nil && m.Enrollment == e.Enrollment && m.FloorGuardReady && m.FloorSHA256 == g.FloorSHA256 && m.BinarySHA256 == g.Hash && |
| - !rep.GeneratedAt.IsZero() && now.Sub(rep.GeneratedAt) <= reportFreshness |
| -} |
| - |
| -// productionModeFacts reads the deployment store, the status store and |
| -// this box's own files. |
| -func productionModeFacts(ctx context.Context, getenv func(string) string) (modeFacts, error) { |
| - store, err := openDeployStoreEnv(ctx, getenv) |
| - if err != nil { |
| - return modeFacts{}, err |
| - } |
| - statusStore, _, err := openStatusStore(ctx, getenv) |
| - if err != nil { |
| - return modeFacts{}, err |
| - } |
| - pub, err := release.ParsePublicKey(getenv("CARLOS_RELEASE_PUBKEY"), "CARLOS_RELEASE_PUBKEY") |
| - if err != nil { |
| - return modeFacts{}, err |
| - } |
| - disk, err := floorDisk(release.OptDir()) |
| - if err != nil { |
| - return modeFacts{}, err |
| - } |
| - bucket := getenv("CARLOS_DEPLOYMENT_BUCKET") |
| - box := metricsBoxLabel(getenv, readMachineID()) |
| - if box == "" { |
| - return modeFacts{}, errors.New("this box's group reference could not be read") |
| - } |
| - imds := &http.Client{Timeout: 2 * time.Second} |
| - return modeFacts{ |
| - box: box, |
| - marked: groupReferenced(getenv), |
| - region: strings.TrimSpace(getenv("CARLOS_REGION")), |
| - enrollment: func() (hostfloor.Enrollment, error) { return hostfloor.ReadEnrollment(hostActorPath) }, |
| - roster: func(ctx context.Context) (hostactors.Roster, error) { |
| - return readGuardRoster(ctx, store, pub, bucket) |
| - }, |
| - guard: func() (hostfloor.Running, error) { |
| - return disk.Running(version.Build, runtime.GOOS+"-"+runtime.GOARCH) |
| - }, |
| - invited: func(ctx context.Context, box string) (bool, error) { |
| - _, _, err := store.Get(ctx, invitationKey(box)) |
| - if errors.Is(err, os.ErrNotExist) { |
| - return false, nil |
| - } |
| - return err == nil, err |
| - }, |
| - report: func(ctx context.Context, box string) (status.Box, error) { |
| - raw, _, err := statusStore.Get(ctx, "status/boxes/"+box+".json") |
| - if err != nil { |
| - return status.Box{}, err |
| - } |
| - var b status.Box |
| - if err := json.Unmarshal(raw, &b); err != nil { |
| - return status.Box{}, err |
| - } |
| - return b, nil |
| - }, |
| - relaunch: func(ctx context.Context, row hostactors.Box) (string, error) { |
| - enrolled, err := boxid.Load(ctx, store, box) |
| - if err != nil { |
| - return "", err |
| - } |
| - current, err := readIdentityRecord(imds, imdsBase, box, time.Now()) |
| - if err != nil { |
| - return "", err |
| - } |
| - return relaunched(row, enrolled, current), nil |
| - }, |
| - now: time.Now, |
| - }, nil |
| -} |
| - |
| -// invitationKey is where the console writes box's invitation |
| -// (hostactors.Directory.Invite). |
| -func invitationKey(box string) string { return "control/host-actor-invitations/" + box + ".json" } |
| - |
| -// agentHosting is this process's mode, decided once by RunAgent before |
| -// the agent starts (hostingGate): true for the claim agent, false while |
| -// joining. The claim wiring reports it to the load balancer's health |
| -// answer (ClaimWiring.startRegional). |
| -var agentHosting atomic.Bool |
diff --git a/internal/host/joinmode_test.go b/internal/host/joinmode_test.go| deleted file mode 100644 |
| index 035f1a5f7..000000000 |
| --- a/internal/host/joinmode_test.go |
| +++ /dev/null |
| @@ -1,301 +0,0 @@ |
| -package host |
| - |
| -import ( |
| - "context" |
| - "encoding/base64" |
| - "encoding/json" |
| - "errors" |
| - "io/fs" |
| - "os" |
| - "strings" |
| - "testing" |
| - "time" |
| - |
| - "github.com/carlosframework/platform/internal/boxid" |
| - "github.com/carlosframework/platform/internal/hostactors" |
| - "github.com/carlosframework/platform/internal/hostfloor" |
| - "github.com/carlosframework/platform/internal/status" |
| -) |
| - |
| -var joinNow = time.Date(2026, 10, 17, 12, 0, 0, 0, time.UTC) |
| - |
| -// joinFacts is a box, "ada-hiking", in each state the tests name. The |
| -// zero value has no host-actor.json and no invitation. |
| -type joinFacts struct { |
| - enrollment *hostfloor.Enrollment |
| - enrollmentErr error |
| - roster hostactors.Roster |
| - rosterErr error |
| - guard hostfloor.Running |
| - guardErr error |
| - invited bool |
| - invitedErr error |
| - report *status.Box |
| - reportErr error |
| - relaunchWhy string |
| - relaunchErr error |
| - relaunchAsked *bool |
| - marked bool |
| - region string |
| -} |
| - |
| -func (j joinFacts) facts() modeFacts { |
| - return modeFacts{ |
| - box: "ada-hiking", |
| - enrollment: func() (hostfloor.Enrollment, error) { |
| - if j.enrollmentErr != nil { |
| - return hostfloor.Enrollment{}, j.enrollmentErr |
| - } |
| - if j.enrollment == nil { |
| - return hostfloor.Enrollment{}, &fs.PathError{Op: "open", Path: hostActorPath, Err: fs.ErrNotExist} |
| - } |
| - return *j.enrollment, nil |
| - }, |
| - roster: func(context.Context) (hostactors.Roster, error) { return j.roster, j.rosterErr }, |
| - guard: func() (hostfloor.Running, error) { |
| - if j.guardErr != nil { |
| - return hostfloor.Running{}, j.guardErr |
| - } |
| - return j.guard, nil |
| - }, |
| - invited: func(context.Context, string) (bool, error) { return j.invited, j.invitedErr }, |
| - report: func(context.Context, string) (status.Box, error) { |
| - if j.reportErr != nil { |
| - return status.Box{}, j.reportErr |
| - } |
| - if j.report == nil { |
| - return status.Box{}, os.ErrNotExist |
| - } |
| - return *j.report, nil |
| - }, |
| - relaunch: func(context.Context, hostactors.Box) (string, error) { |
| - if j.relaunchAsked != nil { |
| - *j.relaunchAsked = true |
| - } |
| - return j.relaunchWhy, j.relaunchErr |
| - }, |
| - marked: j.marked, |
| - region: j.region, |
| - now: func() time.Time { return joinNow }, |
| - } |
| -} |
| - |
| -const joinEnrollment = "0123456789abcdef0123456789abcdef" |
| - |
| -func enrolledFacts() joinFacts { |
| - e := hostfloor.Enrollment{Box: "ada-hiking", Enrollment: joinEnrollment, InstanceID: "i-ada"} |
| - return joinFacts{ |
| - enrollment: &e, |
| - roster: hostactors.Roster{FloorSHA256: "floor", Boxes: map[string]hostactors.Box{"ada-hiking": { |
| - Enrollment: joinEnrollment, State: "active", Cloud: hostactors.Cloud{InstanceID: "i-ada"}}}}, |
| - guard: hostfloor.Running{GuardReady: true, FloorSHA256: "floor", Hash: "image"}, |
| - } |
| -} |
| - |
| -// guardInstalled is a box that guard-arm has armed but the console has not |
| -// enrolled yet. |
| -func guardInstalled() joinFacts { |
| - f := enrolledFacts() |
| - f.roster.Boxes = map[string]hostactors.Box{} |
| - return f |
| -} |
| - |
| -func freshReport(at time.Time) *status.Box { |
| - return &status.Box{GeneratedAt: at, Metrics: &status.BoxMetrics{Enrollment: joinEnrollment, FloorGuardReady: true, FloorSHA256: "floor", BinarySHA256: "image"}} |
| -} |
| - |
| -func TestSelectModeHostsOnlyWhenEnrolledAndArmed(t *testing.T) { |
| - d, err := selectMode(context.Background(), enrolledFacts().facts()) |
| - if err != nil || d.Mode != modeHosting || d.Box != "ada-hiking" { |
| - t.Fatalf("enrolled and armed: %+v %v", d, err) |
| - } |
| - held := map[string]func(*joinFacts){ |
| - "the guard is not armed": func(f *joinFacts) { f.guardErr = hostfloor.ErrFloor }, |
| - "the guard has no policy": func(f *joinFacts) { f.guardErr = &fs.PathError{Op: "open", Path: "policy.json", Err: fs.ErrNotExist} }, |
| - "the guard is for another floor": func(f *joinFacts) { f.guard.FloorSHA256 = "old" }, |
| - "the roster entry is quarantined": func(f *joinFacts) { |
| - b := f.roster.Boxes["ada-hiking"] |
| - b.State = "quarantined" |
| - f.roster.Boxes["ada-hiking"] = b |
| - }, |
| - "the roster entry is another enrollment": func(f *joinFacts) { |
| - b := f.roster.Boxes["ada-hiking"] |
| - b.Enrollment = strings.Repeat("f", 32) |
| - f.roster.Boxes["ada-hiking"] = b |
| - }, |
| - "the roster entry is another instance": func(f *joinFacts) { |
| - b := f.roster.Boxes["ada-hiking"] |
| - b.Cloud.InstanceID = "i-old" |
| - f.roster.Boxes["ada-hiking"] = b |
| - }, |
| - "host-actor.json names another box": func(f *joinFacts) { f.enrollment.Box = "grace-hiking" }, |
| - } |
| - for name, spoil := range held { |
| - t.Run(name, func(t *testing.T) { |
| - f := enrolledFacts() |
| - spoil(&f) |
| - d, err := selectMode(context.Background(), f.facts()) |
| - if err != nil || d.Mode != modeJoining || d.Stage != stageHeld || d.Why == "" { |
| - t.Fatalf("%+v %v", d, err) |
| - } |
| - }) |
| - } |
| -} |
| - |
| -// A restart at each joining state resumes joining at that state (spec 2 |
| -// §11): nothing but an active roster entry with an armed guard hosts. |
| -func TestSelectModeResumesEachJoiningStage(t *testing.T) { |
| - for _, c := range []struct { |
| - name string |
| - facts joinFacts |
| - want joinStage |
| - }{ |
| - {"no invitation", joinFacts{}, stageNoInvitation}, |
| - {"invited", joinFacts{invited: true}, stageInvited}, |
| - {"guard-arm cut off after host-actor.json", func() joinFacts { f := guardInstalled(); f.guardErr = hostfloor.ErrFloor; return f }(), stageInvited}, |
| - {"guard installed", guardInstalled(), stageGuardInstalled}, |
| - {"guard-ready reported", func() joinFacts { f := guardInstalled(); f.report = freshReport(joinNow.Add(-time.Minute)); return f }(), stageGuardReady}, |
| - {"a stale report", func() joinFacts { |
| - f := guardInstalled() |
| - f.report = freshReport(joinNow.Add(-16 * time.Minute)) |
| - return f |
| - }(), stageGuardInstalled}, |
| - {"a report for another image", func() joinFacts { |
| - f := guardInstalled() |
| - f.report = freshReport(joinNow) |
| - f.report.Metrics.BinarySHA256 = "bootstrap" |
| - return f |
| - }(), stageGuardInstalled}, |
| - } { |
| - t.Run(c.name, func(t *testing.T) { |
| - d, err := selectMode(context.Background(), c.facts.facts()) |
| - if err != nil || d.Mode != modeJoining || d.Stage != c.want { |
| - t.Fatalf("%+v %v, want joining at %s", d, err, c.want) |
| - } |
| - }) |
| - } |
| -} |
| - |
| -// A fact that cannot be read is unknown, never its negative: an enrolled |
| -// box whose roster read fails is not sent back to joining. |
| -func TestSelectModeIsUnknownWhenAFactCannotBeRead(t *testing.T) { |
| - outage := errors.New("connection reset") |
| - for name, f := range map[string]joinFacts{ |
| - "the invitation": {invitedErr: outage}, |
| - "host-actor.json": {enrollmentErr: hostfloor.ErrFloor}, |
| - "the roster": func() joinFacts { f := enrolledFacts(); f.rosterErr = outage; return f }(), |
| - "the guard": func() joinFacts { f := enrolledFacts(); f.guardErr = errors.New("permission denied"); return f }(), |
| - "the status report": func() joinFacts { f := guardInstalled(); f.reportErr = outage; return f }(), |
| - "a roster that does not verify": func() joinFacts { f := guardInstalled(); f.rosterErr = hostactors.ErrRoster; return f }(), |
| - } { |
| - t.Run(name, func(t *testing.T) { |
| - d, err := selectMode(context.Background(), f.facts()) |
| - if !errors.Is(err, errModeUnknown) || d.Mode == modeHosting { |
| - t.Fatalf("%+v %v", d, err) |
| - } |
| - }) |
| - } |
| -} |
| - |
| -// C3: a box its region's group launched hosts only on the launch it was |
| -// enrolled on. Stopped and started since, it is held, never hosting on its |
| -// old enrollment; a launch that cannot be read is unknown. A box an |
| -// operator enrolled (no group) is not asked. |
| -func TestSelectModeHoldsAGroupBoxStartedAgain(t *testing.T) { |
| - grouped := func() joinFacts { |
| - f := enrolledFacts() |
| - b := f.roster.Boxes["ada-hiking"] |
| - b.Group, b.Region = "routers-ie", "ie" |
| - f.roster.Boxes["ada-hiking"] = b |
| - f.relaunchAsked = new(bool) |
| - f.marked, f.region = true, "ie" |
| - return f |
| - } |
| - f := grouped() |
| - if d, err := selectMode(context.Background(), f.facts()); err != nil || d.Mode != modeHosting || !*f.relaunchAsked { |
| - t.Fatalf("same launch: %+v %v", d, err) |
| - } |
| - f = grouped() |
| - f.relaunchWhy = "this instance was stopped and started since it was enrolled" |
| - if d, err := selectMode(context.Background(), f.facts()); err != nil || d.Mode != modeJoining || d.Stage != stageHeld || d.Why != f.relaunchWhy { |
| - t.Fatalf("started again: %+v %v", d, err) |
| - } |
| - f = grouped() |
| - f.relaunchErr = errors.New("IMDS answered 500") |
| - if d, err := selectMode(context.Background(), f.facts()); !errors.Is(err, errModeUnknown) || d.Mode == modeHosting { |
| - t.Fatalf("unreadable launch: %+v %v", d, err) |
| - } |
| - f = enrolledFacts() |
| - f.relaunchWhy, f.relaunchAsked = "never asked", new(bool) |
| - if d, err := selectMode(context.Background(), f.facts()); err != nil || d.Mode != modeHosting || *f.relaunchAsked { |
| - t.Fatalf("an operator-enrolled box: %+v %v, asked %v", d, err, *f.relaunchAsked) |
| - } |
| -} |
| - |
| -func TestRelaunchedComparesTheLaunchTheRosterBinds(t *testing.T) { |
| - record := func(pending string) (boxid.Record, []byte) { |
| - doc := `{"accountId":"123","region":"eu-west-1","instanceId":"i-ada"` + pending + `}` |
| - rec := boxid.Record{V: 1, Box: "i-ada", IdentityDocument: base64.StdEncoding.EncodeToString([]byte(doc)), IdentitySignature: "c2ln"} |
| - raw, _ := json.Marshal(rec) |
| - return rec, raw |
| - } |
| - enrolledRec, enrolled := record(`,"pendingTime":"2026-10-17T09:00:00Z"`) |
| - row := hostactors.Box{EvidenceSHA256: hostfloor.Digest(enrolled), Group: "routers-ie"} |
| - if why := relaunched(row, enrolled, enrolledRec); why != "" { |
| - t.Fatalf("the same launch: %q", why) |
| - } |
| - again, _ := record(`,"pendingTime":"2026-10-17T11:30:00Z"`) |
| - if why := relaunched(row, enrolled, again); !strings.Contains(why, "stopped and started") { |
| - t.Fatalf("started again: %q", why) |
| - } |
| - none, _ := record("") |
| - if why := relaunched(row, enrolled, none); why == "" { |
| - t.Fatal("a document with no pendingTime matched") |
| - } |
| - _, other := record(`,"pendingTime":"2026-10-17T09:00:00Z","x":1`) |
| - if why := relaunched(row, other, enrolledRec); !strings.Contains(why, "not the one it was enrolled on") { |
| - t.Fatalf("another record: %q", why) |
| - } |
| -} |
| - |
| -// Condition 3 of census ruling region-ha-2b: the group marker and a group |
| -// box's CARLOS_REGION come from the parameter store, and a value that |
| -// disagrees with the signed roster holds the box instead of hosting it. |
| -func TestSelectModeHoldsAStoreValueTheRosterDisagreesWith(t *testing.T) { |
| - grouped := func() joinFacts { |
| - f := enrolledFacts() |
| - b := f.roster.Boxes["ada-hiking"] |
| - b.Group, b.Region = "routers-ie", "ie" |
| - f.roster.Boxes["ada-hiking"] = b |
| - f.marked, f.region = true, "ie" |
| - return f |
| - } |
| - if d, err := selectMode(context.Background(), grouped().facts()); err != nil || d.Mode != modeHosting { |
| - t.Fatalf("agreeing: %+v %v", d, err) |
| - } |
| - for name, spoil := range map[string]func(*joinFacts){ |
| - "marked, enrolled by hand": func(f *joinFacts) { |
| - b := f.roster.Boxes["ada-hiking"] |
| - b.Group = "" |
| - f.roster.Boxes["ada-hiking"] = b |
| - }, |
| - "enrolled from a group, not marked": func(f *joinFacts) { f.marked = false }, |
| - "another region": func(f *joinFacts) { f.region = "uk" }, |
| - "no region": func(f *joinFacts) { f.region = "" }, |
| - } { |
| - t.Run(name, func(t *testing.T) { |
| - f := grouped() |
| - spoil(&f) |
| - d, err := selectMode(context.Background(), f.facts()) |
| - if err != nil || d.Mode != modeJoining || d.Stage != stageHeld || !strings.Contains(d.Why, "does not host") { |
| - t.Fatalf("%+v %v", d, err) |
| - } |
| - }) |
| - } |
| - // A box an operator enrolled keeps its own region, unchecked. |
| - f := enrolledFacts() |
| - f.region = "anything" |
| - if d, err := selectMode(context.Background(), f.facts()); err != nil || d.Mode != modeHosting { |
| - t.Fatalf("an operator-enrolled box: %+v %v", d, err) |
| - } |
| -} |
diff --git a/internal/host/joinroot.go b/internal/host/joinroot.go| deleted file mode 100644 |
| index 6c86c6c6a..000000000 |
| --- a/internal/host/joinroot.go |
| +++ /dev/null |
| @@ -1,210 +0,0 @@ |
| -package host |
| - |
| -import ( |
| - "context" |
| - "crypto/ed25519" |
| - "encoding/json" |
| - "errors" |
| - "flag" |
| - "fmt" |
| - "log" |
| - "os" |
| - "path/filepath" |
| - "runtime" |
| - |
| - "github.com/carlosframework/platform/internal/boxid" |
| - "github.com/carlosframework/platform/internal/cliflag" |
| - "github.com/carlosframework/platform/internal/hostactors" |
| - "github.com/carlosframework/platform/internal/hostfloor" |
| - "github.com/carlosframework/platform/internal/hostwrite" |
| - "github.com/carlosframework/platform/internal/release" |
| - "github.com/carlosframework/platform/internal/version" |
| -) |
| - |
| -// carlos system join (region HA spec 2 §5 step 5.3): root's half of |
| -// joining, run by carlos-system-join.service when the joining agent asks. |
| -// |
| -// The invitation grants no membership: it is the console's signed nonce |
| -// for this box's identity record, with which the box installs its guard |
| -// and reports. Root reads it itself and checks it: signed by the release |
| -// key, for this deployment and this box, for the identity record this box |
| -// published, which must be this instance's. Then it writes the enrollment |
| -// the invitation names, builds the armed policy from the published host |
| -// floor, and runs guard-arm with the release identity install-channel |
| -// kept (channelIdentityPath). guard-arm checks both protected slots against |
| -// that identity and writes /etc/carlos/host-actor.json. |
| -// |
| -// A box already armed, a box with no invitation yet, and a box with claim |
| -// mode or region HA off have nothing to do. |
| - |
| -const joinUsage = "usage: carlos system join\n\n" + |
| - "Arm the host lifecycle guard of a joining box, as root, once the console has invited it.\n" |
| - |
| -const joinNotRoot = "carlos system join runs as root: it arms the host lifecycle guard" |
| - |
| -// joinDir holds what root hands guard-arm: the enrollment and the policy. |
| -func joinDir(optDir string) string { return filepath.Join(optDir, "system", "join") } |
| - |
| -// rootJoin is one run; production's is RunSystemJoin's. |
| -type rootJoin struct { |
| - box string |
| - optDir string |
| - bucket string |
| - store release.Store |
| - pub ed25519.PublicKey |
| - instance func() string |
| - // armed reports whether the guard is armed for host-actor.json. |
| - armed func() bool |
| - // arm is guard-arm, given the three files. |
| - arm func(policy, identity, enrollment string) error |
| -} |
| - |
| -// joinOutcome is what a run did. |
| -type joinOutcome string |
| - |
| -const ( |
| - joinArmedAlready joinOutcome = "armed already" |
| - joinNotInvited joinOutcome = "not invited" |
| - joinArmed joinOutcome = "armed" |
| -) |
| - |
| -// RunSystemJoin is `carlos system join`. |
| -func RunSystemJoin(args []string) { |
| - fs := flag.NewFlagSet("system join", flag.ExitOnError) |
| - fs.Usage = cliflag.Usage(fs, joinUsage) |
| - _ = fs.Parse(args) |
| - if fs.NArg() != 0 { |
| - fs.Usage() |
| - os.Exit(2) |
| - } |
| - if os.Geteuid() != 0 { |
| - fmt.Fprintln(os.Stderr, joinNotRoot) |
| - os.Exit(1) |
| - } |
| - if !hostwrite.Enabled(os.Getenv) || !regionHAEnabled(os.Getenv) { |
| - fmt.Println("CARLOS_HOST_CLAIM or CARLOS_REGION_HA is off, so this box does not join") |
| - return |
| - } |
| - ctx := context.Background() |
| - store, pub, err := openSystemStore(ctx) |
| - if err != nil { |
| - fmt.Fprintln(os.Stderr, err) |
| - os.Exit(1) |
| - } |
| - optDir := release.OptDir() |
| - box, err := joinBoxLabel(os.Getenv, readMachineID()) |
| - if err != nil { |
| - fmt.Fprintln(os.Stderr, err) |
| - os.Exit(1) |
| - } |
| - j := rootJoin{ |
| - box: box, optDir: optDir, bucket: os.Getenv("CARLOS_DEPLOYMENT_BUCKET"), |
| - store: store, pub: pub, instance: cachedInstanceID, |
| - armed: func() bool { |
| - if _, err := hostfloor.ReadEnrollment(hostActorPath); err != nil { |
| - return false |
| - } |
| - d, err := floorDisk(optDir) |
| - if err != nil { |
| - return false |
| - } |
| - r, err := d.Running(version.Build, runtime.GOOS+"-"+runtime.GOARCH) |
| - return err == nil && r.GuardReady |
| - }, |
| - arm: func(policy, identity, enrollment string) error { |
| - // guard-arm exits the process on any refusal, with its reason. |
| - RunSystemGuardArm([]string{"-policy", policy, "-identity", identity, "-enrollment", enrollment}) |
| - return nil |
| - }, |
| - } |
| - got, err := j.run(ctx) |
| - if err != nil { |
| - fmt.Fprintln(os.Stderr, err) |
| - os.Exit(1) |
| - } |
| - log.Printf("system join: %s: %s", j.box, got) |
| -} |
| - |
| -// joinBoxLabel is the name this box joins under: metricsBoxLabel's, except |
| -// that a group box whose reference IMDS has not given yet is an error with |
| -// IMDS's reason. Its label would be "", and "" names no invitation, so the |
| -// run would end as "not invited" on a box that may well be invited. |
| -func joinBoxLabel(getenv func(string) string, machineID string) (string, error) { |
| - if groupReferenced(getenv) { |
| - ref, err := resolveGroupBoxReference() |
| - if err != nil { |
| - return "", fmt.Errorf("this box's AWS identity could not be read, so it cannot join yet: %w", err) |
| - } |
| - return ref, nil |
| - } |
| - return metricsBoxLabel(getenv, machineID), nil |
| -} |
| - |
| -func (j rootJoin) run(ctx context.Context) (joinOutcome, error) { |
| - if j.box == "" { |
| - return "", errors.New("this box has no name to join under") |
| - } |
| - if j.armed() { |
| - return joinArmedAlready, nil |
| - } |
| - wire, _, err := j.store.Get(ctx, invitationKey(j.box)) |
| - if errors.Is(err, os.ErrNotExist) { |
| - return joinNotInvited, nil |
| - } |
| - if err != nil { |
| - return "", fmt.Errorf("the invitation for %s could not be read: %w", j.box, err) |
| - } |
| - var inv hostactors.Invitation |
| - if release.VerifyRootEnvelope(j.pub, wire, &inv) != nil || inv.V != 1 || inv.Bucket != j.bucket || inv.Reference != j.box || inv.Enrollment == "" { |
| - return "", fmt.Errorf("the invitation for %s does not verify, so the guard was not armed", j.box) |
| - } |
| - raw, err := boxid.Load(ctx, j.store, j.box) |
| - if err != nil { |
| - return "", fmt.Errorf("the identity record for %s could not be read: %w", j.box, err) |
| - } |
| - var rec boxid.Record |
| - if hostfloor.Digest(raw) != inv.EvidenceSHA256 || json.Unmarshal(raw, &rec) != nil { |
| - return "", fmt.Errorf("the invitation for %s is for another identity record, so the guard was not armed", j.box) |
| - } |
| - instance, err := recordInstanceID(rec) |
| - if err != nil || instance == "" || instance != j.instance() { |
| - return "", fmt.Errorf("the identity record for %s is not this instance's, so the guard was not armed", j.box) |
| - } |
| - // guard-arm refuses, naming the file, when install-channel has not |
| - // kept the release identity. |
| - identity := channelIdentityPath(j.optDir) |
| - floorRaw, _, err := j.store.Get(ctx, hostfloor.Key) |
| - if err != nil { |
| - return "", fmt.Errorf("the host floor could not be read: %w", err) |
| - } |
| - auth, _, err := j.store.Get(ctx, hostfloor.AuthKey) |
| - if err != nil { |
| - return "", fmt.Errorf("the host floor could not be read: %w", err) |
| - } |
| - if _, err := hostfloor.Verify(j.pub, j.bucket, floorRaw, auth); err != nil { |
| - return "", fmt.Errorf("the host floor does not verify, so the guard was not armed: %w", err) |
| - } |
| - policy, err := json.Marshal(hostfloor.Policy{Schema: 1, DeploymentBucket: j.bucket, Mode: "armed", Floor: floorRaw, Authorization: auth}) |
| - if err != nil { |
| - return "", err |
| - } |
| - enrollment, err := json.Marshal(hostfloor.Enrollment{Box: j.box, Enrollment: inv.Enrollment, InstanceID: instance}) |
| - if err != nil { |
| - return "", err |
| - } |
| - dir := joinDir(j.optDir) |
| - if err := os.MkdirAll(dir, 0o700); err != nil { |
| - return "", err |
| - } |
| - policyPath, enrollmentPath := filepath.Join(dir, "policy.json"), filepath.Join(dir, "enrollment.json") |
| - if err := hostfloor.Durable(policyPath, policy, 0o600); err != nil { |
| - return "", err |
| - } |
| - if err := hostfloor.Durable(enrollmentPath, enrollment, 0o600); err != nil { |
| - return "", err |
| - } |
| - if err := j.arm(policyPath, identity, enrollmentPath); err != nil { |
| - return "", err |
| - } |
| - return joinArmed, nil |
| -} |
diff --git a/internal/host/joinroot_test.go b/internal/host/joinroot_test.go| deleted file mode 100644 |
| index d19f998ae..000000000 |
| --- a/internal/host/joinroot_test.go |
| +++ /dev/null |
| @@ -1,216 +0,0 @@ |
| -package host |
| - |
| -import ( |
| - "bytes" |
| - "context" |
| - "crypto/ed25519" |
| - "encoding/json" |
| - "errors" |
| - "os" |
| - "path/filepath" |
| - "strings" |
| - "testing" |
| - |
| - "github.com/carlosframework/platform/internal/boxid" |
| - "github.com/carlosframework/platform/internal/boxid/boxidtest" |
| - "github.com/carlosframework/platform/internal/hostactors" |
| - "github.com/carlosframework/platform/internal/hostenv" |
| - "github.com/carlosframework/platform/internal/hostfloor" |
| - "github.com/carlosframework/platform/internal/release" |
| -) |
| - |
| -// rootJoinWorld is a deployment that has invited box "ada-hiking", whose |
| -// identity record says it is instance i-ada. |
| -type rootJoinWorld struct { |
| - j rootJoin |
| - store *release.DirStore |
| - sg release.Signer |
| - armed []string |
| - invite hostactors.Invitation |
| -} |
| - |
| -func newRootJoinWorld(t *testing.T, invite bool) *rootJoinWorld { |
| - t.Helper() |
| - ctx := context.Background() |
| - pub, key, err := ed25519.GenerateKey(nil) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - w := &rootJoinWorld{store: release.NewDirStore(t.TempDir()), sg: release.RootSigner(key)} |
| - _, raw := boxidtest.NewSigner(t).Record(t, "ada-hiking", "123", "eu-west-1", "i-ada") |
| - if _, err := w.store.Put(ctx, boxid.Key("ada-hiking"), raw, ""); err != nil { |
| - t.Fatal(err) |
| - } |
| - if err := hostfloor.Publish(ctx, w.store, w.sg, "bucket", hostfloor.Floor{Min: 1, MinRelease: "v1.0.0"}); err != nil { |
| - t.Fatal(err) |
| - } |
| - if invite { |
| - if w.invite, err = (hostactors.Directory{Store: w.store, PublicKey: pub, Bucket: "bucket"}).Invite(ctx, w.sg, "ada-hiking", raw); err != nil { |
| - t.Fatal(err) |
| - } |
| - } |
| - w.j = rootJoin{box: "ada-hiking", optDir: t.TempDir(), bucket: "bucket", store: w.store, pub: pub, |
| - instance: func() string { return "i-ada" }, armed: func() bool { return false }, |
| - arm: func(policy, identity, enrollment string) error { |
| - w.armed = []string{policy, identity, enrollment} |
| - return nil |
| - }} |
| - return w |
| -} |
| - |
| -func TestRootJoinArmsWithTheInvitationsEnrollment(t *testing.T) { |
| - t.Parallel() |
| - w := newRootJoinWorld(t, true) |
| - got, err := w.j.run(context.Background()) |
| - if err != nil || got != joinArmed || len(w.armed) != 3 { |
| - t.Fatalf("%s %v, armed %v", got, err, w.armed) |
| - } |
| - raw, err := os.ReadFile(w.armed[0]) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - var p hostfloor.Policy |
| - if json.Unmarshal(raw, &p) != nil || p.Mode != "armed" { |
| - t.Fatalf("policy %s", raw) |
| - } |
| - if _, err := p.Verify(w.j.pub, "bucket"); err != nil { |
| - t.Fatalf("the policy does not verify: %v", err) |
| - } |
| - if w.armed[1] != channelIdentityPath(w.j.optDir) { |
| - t.Fatalf("identity %s", w.armed[1]) |
| - } |
| - e, err := hostfloor.ReadEnrollment(w.armed[2]) |
| - if err != nil || e != (hostfloor.Enrollment{Box: "ada-hiking", Enrollment: w.invite.Enrollment, InstanceID: "i-ada"}) { |
| - t.Fatalf("enrollment %+v %v", e, err) |
| - } |
| - for _, p := range []string{w.armed[0], w.armed[2]} { |
| - if fi, err := os.Stat(p); err != nil || fi.Mode().Perm() != 0o600 { |
| - t.Fatalf("%s: %v %v", p, fi, err) |
| - } |
| - } |
| -} |
| - |
| -func TestRootJoinDoesNothingUntilInvitedOrOnceArmed(t *testing.T) { |
| - t.Parallel() |
| - w := newRootJoinWorld(t, false) |
| - if got, err := w.j.run(context.Background()); err != nil || got != joinNotInvited || w.armed != nil { |
| - t.Fatalf("not invited: %s %v %v", got, err, w.armed) |
| - } |
| - v := newRootJoinWorld(t, true) |
| - v.j.armed = func() bool { return true } |
| - v.j.store = nil // an armed box reads nothing |
| - if got, err := v.j.run(context.Background()); err != nil || got != joinArmedAlready || v.armed != nil { |
| - t.Fatalf("armed: %s %v %v", got, err, v.armed) |
| - } |
| -} |
| - |
| -func TestRootJoinRefusesAnInvitationThatIsNotThisBoxs(t *testing.T) { |
| - t.Parallel() |
| - for name, spoil := range map[string]func(*rootJoinWorld){ |
| - "another instance": func(w *rootJoinWorld) { w.j.instance = func() string { return "i-other" } }, |
| - "another record": func(w *rootJoinWorld) { |
| - _, raw := boxidtest.NewSigner(t).Record(t, "ada-hiking", "123", "eu-west-1", "i-ada") |
| - _, etag, _ := w.store.Get(context.Background(), boxid.Key("ada-hiking")) |
| - w.store.Put(context.Background(), boxid.Key("ada-hiking"), raw, etag) |
| - }, |
| - "another release key": func(w *rootJoinWorld) { |
| - other, _, _ := ed25519.GenerateKey(nil) |
| - w.j.pub = other |
| - }, |
| - "another deployment": func(w *rootJoinWorld) { w.j.bucket = "other-bucket" }, |
| - } { |
| - t.Run(name, func(t *testing.T) { |
| - w := newRootJoinWorld(t, true) |
| - spoil(w) |
| - if got, err := w.j.run(context.Background()); err == nil || w.armed != nil { |
| - t.Fatalf("%s %v, armed %v", got, err, w.armed) |
| - } |
| - }) |
| - } |
| - // A store that cannot be read is an error, never "not invited". |
| - w := newRootJoinWorld(t, true) |
| - w.j.store = joinOutageStore{} |
| - if got, err := w.j.run(context.Background()); err == nil || got == joinNotInvited { |
| - t.Fatalf("unreadable store: %s %v", got, err) |
| - } |
| -} |
| - |
| -type joinOutageStore struct{ release.Store } |
| - |
| -func (joinOutageStore) Get(context.Context, string) ([]byte, string, error) { |
| - return nil, "", errors.New("connection reset") |
| -} |
| - |
| -// The join units' census condition (platform-1e, region-ha-2b): the path |
| -// unit's file is only a trigger. Whatever the agent, or anything else, |
| -// writes into it, root's join reads none of it, takes no parameter from |
| -// it, and decides from the signed invitation, the published identity |
| -// record, the signed host floor and IMDS alone. |
| -func TestRootJoinTakesNothingFromItsTrigger(t *testing.T) { |
| - data := t.TempDir() |
| - t.Setenv("CARLOS_DATA_DIR", data) |
| - clean := newRootJoinWorld(t, true) |
| - want, err := clean.j.run(context.Background()) |
| - if err != nil || want != joinArmed { |
| - t.Fatalf("baseline: %s %v", want, err) |
| - } |
| - for name, body := range map[string]string{ |
| - "another box": `{"box":"grace-hiking","instance":"i-grace","enrollment":"ffffffffffffffffffffffffffffffff"}`, |
| - "a path": "../../etc/carlos/host-actor.json\n", |
| - "a policy": `{"schema":1,"mode":"armed","deployment_bucket":"other-bucket"}`, |
| - "nul and newlines": "a\x00b\n\n--policy=/tmp/x\n", |
| - "a megabyte of junk": strings.Repeat("x", 1<<20), |
| - } { |
| - t.Run(name, func(t *testing.T) { |
| - if err := os.WriteFile(filepath.Join(data, "system-join-requested"), []byte(body), 0o644); err != nil { |
| - t.Fatal(err) |
| - } |
| - w := newRootJoinWorld(t, true) |
| - got, err := w.j.run(context.Background()) |
| - if err != nil || got != want || len(w.armed) != 3 || w.armed[1] != channelIdentityPath(w.j.optDir) { |
| - t.Fatalf("%s %v, armed %v", got, err, w.armed) |
| - } |
| - e, err := hostfloor.ReadEnrollment(w.armed[2]) |
| - if err != nil || e != (hostfloor.Enrollment{Box: "ada-hiking", Enrollment: w.invite.Enrollment, InstanceID: "i-ada"}) { |
| - t.Fatalf("enrollment %+v %v", e, err) |
| - } |
| - }) |
| - } |
| - // And by construction: root's join names neither the trigger nor its |
| - // path anywhere in its source. |
| - src, err := os.ReadFile("joinroot.go") |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - if bytes.Contains(src, []byte("joinRequestMarker")) || bytes.Contains(src, []byte("system-join-requested")) { |
| - t.Fatal("joinroot.go reads its trigger") |
| - } |
| -} |
| - |
| -// A group box names its invitation by its group reference. While IMDS has |
| -// not given it, there is no name, and the join says so; it never reads the |
| -// invitation of "" and reports "not invited". |
| -func TestRootJoinNamesAGroupBoxByItsReferenceOrFails(t *testing.T) { |
| - group := groupEnv(map[string]string{hostenv.BoxReference: hostenv.GroupReference}) |
| - withGroupIdentity(t, "", "", errors.New("IMDS answered 500")) |
| - if got, err := joinBoxLabel(group, "machine"); err == nil || got != "" || err.Error() != "this box's AWS identity could not be read, so it cannot join yet: IMDS answered 500" { |
| - t.Fatalf("no identity: %q %v", got, err) |
| - } |
| - withGroupIdentity(t, "123456789012", "i-0a61f580df1acfa65", nil) |
| - want := hostactors.GroupBoxReference("123456789012", "i-0a61f580df1acfa65") |
| - if got, err := joinBoxLabel(group, "machine"); err != nil || got != want { |
| - t.Fatalf("group box: %q %v, want %q", got, err, want) |
| - } |
| - // Any other box keeps metricsBoxLabel's name. |
| - other := groupEnv(nil) |
| - if got, err := joinBoxLabel(other, "machine"); err != nil || got != metricsBoxLabel(other, "machine") || got == "" { |
| - t.Fatalf("other box: %q %v", got, err) |
| - } |
| - // And a run with no name reads nothing. |
| - w := newRootJoinWorld(t, true) |
| - w.j.box = "" |
| - w.j.store = nil |
| - if got, err := w.j.run(context.Background()); err == nil || got == joinNotInvited || w.armed != nil { |
| - t.Fatalf("nameless: %s %v %v", got, err, w.armed) |
| - } |
| -} |
diff --git a/internal/host/retiredunits.go b/internal/host/retiredunits.go| new file mode 100644 |
| index 000000000..67b084420 |
| --- /dev/null |
| +++ b/internal/host/retiredunits.go |
| @@ -0,0 +1,60 @@ |
| +package host |
| + |
| +import ( |
| + "errors" |
| + "fmt" |
| + "os" |
| + "path/filepath" |
| +) |
| + |
| +// retiredUnits are units an earlier build installed and this one no longer |
| +// ships: region HA's joining relay, removed with joining mode (region HA |
| +// P1a). Bootstrap retires them so a box bootstrapped by that build does |
| +// not keep them installed and enabled. |
| +var retiredUnits = []string{"carlos-system-join.path", "carlos-system-join.service"} |
| + |
| +// retireUnits disables, stops and removes each unit under |
| +// <root>/etc/systemd/system. A unit that is not installed is no error. On |
| +// the live root ("/") the unit is disabled and stopped through systemctl |
| +// first; on any root its file and every *.wants/ or *.requires/ link to it |
| +// are removed, which is what disable does to a staging tree. |
| +func retireUnits(root string, units []string) error { |
| + live := filepath.Clean(root) == "/" |
| + unitDir := filepath.Join(root, "etc", "systemd", "system") |
| + removed := false |
| + for _, u := range units { |
| + if filepath.Base(u) != u || u == "." || u == ".." { |
| + return fmt.Errorf("retire %q: not a unit name", u) |
| + } |
| + path := filepath.Join(unitDir, u) |
| + _, err := os.Lstat(path) |
| + installed := err == nil |
| + if err != nil && !errors.Is(err, os.ErrNotExist) { |
| + return fmt.Errorf("retire %s: %w", u, err) |
| + } |
| + if live && installed { |
| + if err := systemctl("disable", "--now", u); err != nil { |
| + return fmt.Errorf("retire %s: %w", u, err) |
| + } |
| + } |
| + links, err := filepath.Glob(filepath.Join(unitDir, "*.wants", u)) |
| + if err != nil { |
| + return err |
| + } |
| + more, err := filepath.Glob(filepath.Join(unitDir, "*.requires", u)) |
| + if err != nil { |
| + return err |
| + } |
| + for _, p := range append(append(links, more...), path) { |
| + if err := os.Remove(p); err == nil { |
| + removed = true |
| + } else if !errors.Is(err, os.ErrNotExist) { |
| + return fmt.Errorf("retire %s: %w", u, err) |
| + } |
| + } |
| + } |
| + if live && removed { |
| + return systemctl("daemon-reload") |
| + } |
| + return nil |
| +} |
diff --git a/internal/host/retiredunits_test.go b/internal/host/retiredunits_test.go| new file mode 100644 |
| index 000000000..f2d8a6fc5 |
| --- /dev/null |
| +++ b/internal/host/retiredunits_test.go |
| @@ -0,0 +1,58 @@ |
| +package host |
| + |
| +import ( |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "testing" |
| +) |
| + |
| +// writeUnit installs name under root's /etc/systemd/system, enabled the |
| +// way systemctl enable leaves a WantedBy=multi-user.target unit. |
| +func writeUnit(t *testing.T, root, name string) { |
| + t.Helper() |
| + dir := filepath.Join(root, "etc", "systemd", "system") |
| + if err := os.MkdirAll(filepath.Join(dir, "multi-user.target.wants"), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + path := filepath.Join(dir, name) |
| + if err := os.WriteFile(path, []byte("[Unit]\n"), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Symlink(path, filepath.Join(dir, "multi-user.target.wants", name)); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// Region HA P1a Task 2: bootstrap retires the join units. A box that ran |
| +// an earlier bootstrap has them installed and enabled; this one leaves |
| +// neither the unit nor its wants link, and an absent unit is no error. |
| +func TestBootstrapRetiresJoinUnits(t *testing.T) { |
| + root := t.TempDir() |
| + writeUnit(t, root, "carlos-system-join.path") |
| + if err := retireUnits(root, retiredUnits); err != nil { |
| + t.Fatal(err) |
| + } |
| + dir := filepath.Join(root, "etc", "systemd", "system") |
| + for _, p := range []string{filepath.Join(dir, "carlos-system-join.path"), filepath.Join(dir, "multi-user.target.wants", "carlos-system-join.path")} { |
| + if _, err := os.Lstat(p); !os.IsNotExist(err) { |
| + t.Fatalf("%s still installed (%v)", p, err) |
| + } |
| + } |
| + if slices.Contains(enabledUnits, "carlos-system-join.path") { |
| + t.Fatal("still enabled") |
| + } |
| + // Twice is the same as once: nothing left is no error. |
| + if err := retireUnits(root, retiredUnits); err != nil { |
| + t.Fatalf("a second retire: %v", err) |
| + } |
| + // bootstrap's own path retires them. |
| + stage := t.TempDir() |
| + writeUnit(t, stage, "carlos-system-join.path") |
| + if err := bootstrapWith(stage, nil, false); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := os.Lstat(filepath.Join(stage, "etc", "systemd", "system", "carlos-system-join.path")); !os.IsNotExist(err) { |
| + t.Fatalf("bootstrap left the join unit installed (%v)", err) |
| + } |
| +} |
diff --git a/internal/host/units/carlos-system-join.path b/internal/host/units/carlos-system-join.path| deleted file mode 100644 |
| index 4f4f4810b..000000000 |
| --- a/internal/host/units/carlos-system-join.path |
| +++ /dev/null |
| @@ -1,15 +0,0 @@ |
| -# Region HA spec 2 §5 step 5.3: the relay from a joining box's sandboxed |
| -# agent to root's half of joining. The agent (User=carlos, |
| -# ProtectSystem=strict) sees the console's invitation but cannot write /etc |
| -# or arm the host lifecycle guard; it touches this marker and root does the |
| -# rest, as carlos-system-update.path relays a self-update. Root takes |
| -# nothing from the marker: it reads and verifies the invitation itself. |
| -[Unit] |
| -Description=carlos joining: arm the host lifecycle guard on agent request |
| - |
| -[Path] |
| -PathChanged=/data/system-join-requested |
| -Unit=carlos-system-join.service |
| - |
| -[Install] |
| -WantedBy=multi-user.target |
diff --git a/internal/host/units/carlos-system-join.service b/internal/host/units/carlos-system-join.service| deleted file mode 100644 |
| index 9b60032df..000000000 |
| --- a/internal/host/units/carlos-system-join.service |
| +++ /dev/null |
| @@ -1,41 +0,0 @@ |
| -# Root's half of joining (region HA spec 2 §5 step 5.3): `carlos system |
| -# join` verifies this box's signed invitation, writes the enrollment it |
| -# names, and arms the host lifecycle guard (guard-arm) with the release |
| -# identity `carlos system install-channel` kept. On a box that is armed |
| -# already, has no invitation yet, or has CARLOS_HOST_CLAIM or |
| -# CARLOS_REGION_HA off, it does nothing. Started only by |
| -# carlos-system-join.path; no [Install] section, because nothing else |
| -# should want it. |
| -# |
| -# Root, with no filesystem sandboxing, like carlos-system-update.service: |
| -# guard-arm writes /opt/carlos/system/guard, /etc/carlos/host-actor.json and |
| -# the guarded units' drop-ins under /etc/systemd/system. |
| -# StartLimitIntervalSec=0 because the path unit can fire in bursts. |
| -[Unit] |
| -Description=carlos joining (root: arm the host lifecycle guard) |
| -After=network-online.target |
| -Wants=network-online.target |
| -StartLimitIntervalSec=0 |
| - |
| -[Service] |
| -Type=oneshot |
| -TimeoutStartSec=5min |
| -EnvironmentFile=-/etc/carlos/host.env |
| -ExecStart=/opt/carlos/carlos system join |
| - |
| -# --- hardening (the carlos-system-update.service set) --- |
| -ProtectHome=yes |
| -PrivateTmp=yes |
| -PrivateDevices=yes |
| -ProtectClock=yes |
| -ProtectHostname=yes |
| -ProtectKernelTunables=yes |
| -ProtectKernelModules=yes |
| -ProtectKernelLogs=yes |
| -RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX |
| -RestrictNamespaces=yes |
| -RestrictRealtime=yes |
| -LockPersonality=yes |
| -MemoryDenyWriteExecute=yes |
| -MemoryMax=256M |
| -TasksMax=64 |
diff --git a/region_ha_boundary_test.go b/region_ha_boundary_test.go| index e5bab36b5..978abfbf8 100644 |
| --- a/region_ha_boundary_test.go |
| +++ b/region_ha_boundary_test.go |
| @@ -39,11 +39,9 @@ var regionHACoreFiles = []string{ |
| "internal/hostactors/groupref.go", |
| "internal/hostactors/autoenroll.go", |
| "internal/console/enrollpass.go", |
| - "internal/host/joinmode.go", |
| "internal/host/boxreference.go", |
| "internal/status/fleet.go", |
| - "internal/host/joinroot.go", |
| - "internal/host/joining.go", |
| + "internal/host/agententry.go", |
| } |
| // regionHAAdapterFiles are spec 2's AWS adapters. Each is named for AWS so |
diff --git a/system.go b/system.go| index 8e9a6c9db..b02b2f1fa 100644 |
| --- a/system.go |
| +++ b/system.go |
| @@ -51,7 +51,7 @@ func systemVerb(args []string) (verb string, rest []string, component string) { |
| // untouched in rest for runSystemAntivirusVerb to read. |
| // layout is a family too: migrate|revert|status stay in rest for |
| // runSystemLayout. |
| - case "files", "guard-arm", "guard-exec", "journal-migrate", "floor-allows-prev", "update", "status", "rollback", "cancel-activation", "apply", "antivirus", "layout", "geoip", "seeds-floor", "legacy-routes", "lifetimes", "box", "group", "install-channel", "join", "host-env", "db-worker", "help", "-h", "--help": |
| + case "files", "guard-arm", "guard-exec", "journal-migrate", "floor-allows-prev", "update", "status", "rollback", "cancel-activation", "apply", "antivirus", "layout", "geoip", "seeds-floor", "legacy-routes", "lifetimes", "box", "group", "install-channel", "host-env", "db-worker", "help", "-h", "--help": |
| return args[0], args[1:], component |
| } |
| return "", args, component |
| @@ -101,9 +101,6 @@ func runSystem(args []string) { |
| case "install-channel": |
| // A joining box's own release (region HA spec 2 §5 step 3); root. |
| host.RunSystemInstallChannel(rest) |
| - case "join": |
| - // Root's half of joining, behind carlos-system-join.service. |
| - host.RunSystemJoin(rest) |
| case "host-env": |
| // host.env from and into the deployment's parameters (§5 step 2). |
| hostenv.RunSystemHostEnv(rest) |
| @@ -185,7 +182,6 @@ A box a region's group launches (region HA): |
| host-env write build host.env from the deployment's parameters (root) |
| host-env seed copy a box's host.env into the deployment's parameters |
| install-channel install the release this box's channel names (root) |
| - join (root oneshot behind carlos-system-join.service; not for operators) |
| Deployment-wide settings (CARLOS_STORE_OPERATORS): |
diff --git a/system_test.go b/system_test.go| index 4a97e9133..36b8d734b 100644 |
| --- a/system_test.go |
| +++ b/system_test.go |
| @@ -30,13 +30,12 @@ func TestSystemVerbAcceptsTheComponentForm(t *testing.T) { |
| {[]string{"layout", "migrate", "--box", "x"}, "layout", "router", 3}, |
| {[]string{"layout", "revert", "--force", "--yes"}, "layout", "router", 3}, |
| {[]string{"layout", "status"}, "layout", "router", 1}, |
| - // Region HA joining (spec 2 §5): host-env is a family; join and |
| - // install-channel take no arguments. |
| + // Region HA (spec 2 §5): host-env is a family; install-channel |
| + // takes no arguments. |
| {[]string{"host-env", "write", "--deployment", "flagship", "--region", "ie"}, "host-env", "router", 5}, |
| {[]string{"install-channel"}, "install-channel", "router", 0}, |
| // lifetimes is a family: cutover and its flag stay in rest. |
| {[]string{"lifetimes", "cutover", "--no-wait"}, "lifetimes", "router", 2}, |
| - {[]string{"join"}, "join", "router", 0}, |
| {[]string{}, "", "router", 0}, |
| {[]string{"router"}, "", "router", 0}, |
| } |
| @@ -332,3 +331,10 @@ func TestPrintSystemStatusSaysWhenBootstrapLags(t *testing.T) { |
| }) |
| } |
| } |
| + |
| +// Region HA P1a Task 2: carlos system join is gone with joining mode. |
| +func TestSystemJoinVerbGone(t *testing.T) { |
| + if v, _, _ := systemVerb([]string{"join"}); v != "" { |
| + t.Fatalf("join still a verb: %q", v) |
| + } |
| +} |