carlos / platform Public

host: drain verbs reach the agent as its user; reruns join the move

Branch review r1, Astra B1.3 and the census REJECT: root dialled the
agent-owned drain socket and used its answers in the fence workflow.

Ruling: the drain verb's agent RPC runs with privileges dropped to the
agent's user. The verbs now run a __drain-call child through the
registry child's pattern (pinned /proc/self/exe, no new privileges,
empty environment, "/"); the child drops to carlos itself (no groups,
not dumpable, verified) before it dials the socket and prints one
bounded JSON answer. Root never opens, dials or follows the agent's
path; the socket now serves only the agent's own user.

Root acts on an answer only to install the fence after an acknowledged
withdrawal, which only restricts. Fence removals (drain --cancel,
fence-clear) read only root's fence file: the agent keeps its own start
gate closed in memory from an acknowledged withdrawal until its cancel,
so lifting the fence never opens a drain in progress, and a restarted
agent holds no drain state. drain --cancel removes its fence whatever
the agent answers and fails when the agent did not confirm and systemd
does not show the edge stopped. This also covers Fable B1.6: fence-clear
needs no ask of the agent.

Fable B1.2 (a): a rerun of drain joins the move step the agent reports
running or done for the same transaction instead of asking for a
withdraw it would refuse.

Tests: the child's command, arguments and strict bounded answer; the
real child end to end from the pinned executable; a non-root child that
cannot drop refuses; a source guard that only the child and the agent's
listener name the socket; a dropped caller mid-move and a rerun that
joins it; the agent's start gate across fence-clear and cancel.
Spec §25.15 R3.1 records the ruling.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 6478609decae2f24eba3688b8887bd4d873c9965 parent b671eb8
16 files changed, +888 −74
  • docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md +1 −0
  • internal/host/agent.go +1 −1
  • internal/host/group_admission.go +7 −1
  • internal/host/group_maintenance_drain.go +94 −34
  • internal/host/group_maintenance_verbs.go +11 −8
  • internal/host/hadrain.go +12 −1
  • internal/host/hadrain_call.go +184 −0
  • internal/host/hadrain_call_linux.go +101 −0
  • internal/host/hadrain_call_linux_test.go +374 −0
  • internal/host/hadrain_call_other.go +21 −0
  • internal/host/hadrain_socket.go +7 −4
  • internal/host/hadrain_socket_linux.go +6 −4
  • internal/host/hadrain_test.go +12 −1
  • internal/host/hadrainfence_linux_test.go +26 −16
  • internal/host/hadrainstate.go +26 −4
  • main.go +5 −0
diff --git a/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md b/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md
index 7fbe2b532..2d3149f93 100644
--- a/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md
+++ b/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md
@@ -1319,6 +1319,7 @@ Paul approved all four §25.14 recommendations and Q1 to Q3 as recommended: drai
**H5 amended: a retained start fence (R3.1).** Quiescence is a state the transaction holds, not a report it reads.
- `drain` installs a root-owned **start fence** bound to the transaction id, at `/var/lib/carlos-group-fence/fence.json`: the directory root's and 0755, the file root's and 0644, created by the group-maintenance verbs. It is not under the maintenance directory, `/run/carlos-group-maintenance`, because that directory is root's alone (0700) and the agent, which runs as `carlos`, could not read a fence there. It is on persistent storage, not `/run`, so a member that reboots during a transaction comes back fenced (build ruling, 2026-11-09). The agent's tenant start gate refuses every start while a fence is present. The agent reads the fence at start and at every start decision, so a restarted agent is fenced too. A fence that cannot be read, is not root's or does not parse fences all the same. While a fence is present the agent also withdraws placement: it publishes the drain state (`draining`, with no `ha_drain` mark) from its first publication and places nothing on itself, until the fence is removed and its next edges tick (2 s) publishes it placeable again. So no peer places a cold wake on a fenced member, a roll's restarted agent included, and none gets the fenced start's 503 (branch review ruling, 2026-11-09). Only the tool removes the fence, with `drain --cancel` or `fence-clear` of the same transaction: at ExitStandby for roll, at cancel, or when the member is gone.
+- **Root and the agent (build ruling, 2026-11-09).** The drain verbs reach the agent through a child that drops to the agent's user (the registry child's pattern: no new privileges, no supplementary groups, not dumpable) and makes the call over the agent's socket; root never opens, dials or follows that agent-owned path. Root relays the agent's answers, and acts on one only to install the fence after an acknowledged withdrawal, which only restricts. Its fence removals read only its own fence file. They need no answer from the agent because the agent keeps its own start gate closed, in memory, from an acknowledged withdrawal until `drain --cancel`; an agent that restarts holds no drain state, and the fence gates it. `drain --cancel` therefore removes its transaction's fence whatever the agent answers, and fails, so the operator knows, when the agent did not confirm and systemd does not show the edge stopped. A rerun of `drain` joins the move step the agent reports running or done for the same transaction, so a dropped session can ask again.
- **replace and remove** stop `carlos-edge.service` under the fence after the drain report, prove the edge process gone, and only then make the provider call. A peer request chosen against an old snapshot then meets a closed port, not a box that might acquire.
- **roll**'s `apply` restarts the edge behind the fence, so the restarted agent can acquire nothing until the tool's return step.
- The pre-action check reads the fence, the report and the stopped edge. A fence of another transaction refuses.
diff --git a/internal/host/agent.go b/internal/host/agent.go
index fb973e7eb..8b8c04da8 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -1221,7 +1221,7 @@ func runAgent(args []string, buildClaims ClaimFactory) {
svc.SetDrainingSource(boxDrain.IsDraining)
svc.SetPeerDrainView(e.PeerDraining)
e.SetPeerDrainedHook(svc.DropHoldersNaming)
- // The drain driver and its root-only socket (hadrain.go),
+ // The drain driver and its agent-user-only socket (hadrain.go),
// on group members only: the drain verbs are theirs.
if admission != nil && admission.group {
driver := newDrainDriver(svc, e, boxDrain, groupStartFence.read)
diff --git a/internal/host/group_admission.go b/internal/host/group_admission.go
index 2360cae90..75cbd33b3 100644
--- a/internal/host/group_admission.go
+++ b/internal/host/group_admission.go
@@ -113,9 +113,15 @@ func (a *fixedAdmission) applyRole(role boxroles.Role, known bool) error {
func (a *fixedAdmission) startAllowed() bool {
a.mu.Lock()
defer a.mu.Unlock()
- return !a.closed && a.refusal == "" && a.known && a.role == boxroles.Serve && a.TenantAdmitted() && !(a.group && startFenced())
+ return !a.closed && a.refusal == "" && a.known && a.role == boxroles.Serve && a.TenantAdmitted() && !(a.group && (startFenced() || drainStartsClosed()))
}
+// drainStartsClosed is the agent's own start gate while it holds drain
+// state (hadrainstate.go): closed from an acknowledged withdrawal until
+// drain --cancel, so lifting the fence never opens a drain in progress. A
+// seam for tests.
+var drainStartsClosed = func() bool { return boxDrain.startClosed() }
+
// startFenced reads the retained start fence (hadrainfence.go, region HA
// §25.15 R3.1) at every start decision: a group member refuses every
// tenant start while a fence is present, from any agent incarnation. A
diff --git a/internal/host/group_maintenance_drain.go b/internal/host/group_maintenance_drain.go
index f40a0652e..36079b092 100644
--- a/internal/host/group_maintenance_drain.go
+++ b/internal/host/group_maintenance_drain.go
@@ -17,8 +17,8 @@ import (
var (
errDrainFailed = errors.New("drain failed")
- errDrainSocketDown = errors.New("the edge runs but its drain socket does not answer; the fence stays")
- errDrainEdgeAbsent = errors.New("the drain socket does not answer and the edge process cannot be confirmed stopped; the fence stays")
+ errDrainSocketDown = errors.New("the edge runs but its drain socket does not answer; the fence is removed, and the agent keeps its own start gate closed while it holds drain state")
+ errDrainEdgeAbsent = errors.New("the drain socket does not answer and the edge process cannot be confirmed stopped; the fence is removed, and the agent keeps its own start gate closed while it holds drain state")
)
// The edge probe's two MainPID errors. Both read as status's existing
@@ -62,27 +62,43 @@ func edgeConfirmedStopped(pid int, err error) (bool, error) {
// move step. It prints the agent's last report, and succeeds only when the
// report's result is ok. A fence of another transaction refuses before
// anything is asked.
+//
+// A rerun joins (branch review r1, Fable B1.2): when the agent reports
+// this transaction's move step running or done, and this transaction's
+// fence is present, the verb asks for the move again, which joins the
+// running step or answers its report, rather than a withdraw the agent
+// would refuse while the move runs. So a tool whose session dropped asks
+// again and reads the same drain's outcome.
func (cmd *groupMaintenanceCommand) runDrain(ctx context.Context, out io.Writer) error {
fence := cmd.fenceAt()
- if f := fence.read(); f.Present && (f.Err != nil || f.Transaction != cmd.txn) {
+ f := fence.read()
+ if f.Present && (f.Err != nil || f.Transaction != cmd.txn) {
return errFenceOther
}
ctx, cancel := context.WithTimeout(ctx, haDrainCallBound)
defer cancel()
- client := cmd.drainSocket()
- rep, err := client.step(ctx, "withdraw", cmd.txn)
- if err != nil {
- return err
- }
- if rep.Result == "ok" {
- // The withdrawal is acknowledged: close the start gate (§25.4
- // step 2), retained across agent restarts.
- if err = fence.install(cmd.txn, time.Now()); err != nil {
+ agent := cmd.agent()
+ var rep *drainReport
+ var err error
+ if f.Present && cmd.moveUnderway(ctx, agent) {
+ if rep, err = cmd.drainStep(ctx, agent, "move"); err != nil {
return err
}
- if rep, err = client.step(ctx, "move", cmd.txn); err != nil {
+ } else {
+ if rep, err = cmd.drainStep(ctx, agent, "withdraw"); err != nil {
return err
}
+ if rep.Result == "ok" {
+ // The withdrawal is acknowledged: close the start gate (§25.4
+ // step 2), retained across agent restarts. Installing a fence
+ // only restricts, so root may act on the agent's ok here.
+ if err = fence.install(cmd.txn, time.Now()); err != nil {
+ return err
+ }
+ if rep, err = cmd.drainStep(ctx, agent, "move"); err != nil {
+ return err
+ }
+ }
}
b, err := json.Marshal(rep)
if err != nil {
@@ -97,11 +113,44 @@ func (cmd *groupMaintenanceCommand) runDrain(ctx context.Context, out io.Writer)
return nil
}
-// runDrainCancel is drain --cancel <txn>: the agent ends its drain of txn,
-// then the fence of txn goes. Another transaction's drain or fence
-// refuses, and nothing is removed. An agent that is not running holds no
-// drain state, so only the fence is removed then; an edge process that
-// runs but does not answer refuses, and the fence stays.
+// moveUnderway is whether the agent says its drain of this transaction is
+// at the move step, running or done: a rerun then joins it.
+func (cmd *groupMaintenanceCommand) moveUnderway(ctx context.Context, agent drainCaller) bool {
+ sctx, cancel := context.WithTimeout(ctx, 10*time.Second)
+ defer cancel()
+ r, err := agent(sctx, "status", "")
+ if err != nil || r.err() != nil || r.Status == nil {
+ return false
+ }
+ s := r.Status
+ return s.Transaction == cmd.txn && s.Step == "move" && (s.Result == "running" || s.Result == "ok")
+}
+
+// drainStep asks the agent for one step and returns its report.
+func (cmd *groupMaintenanceCommand) drainStep(ctx context.Context, agent drainCaller, step string) (*drainReport, error) {
+ r, err := agent(ctx, step, cmd.txn)
+ if err != nil {
+ return nil, err
+ }
+ if err := r.err(); err != nil {
+ return nil, err
+ }
+ if r.Report == nil {
+ return nil, errors.New("the agent answered no report")
+ }
+ return r.Report, nil
+}
+
+// runDrainCancel is drain --cancel <txn>: the agent is asked to end its
+// drain of txn, then the fence of txn goes. A fence of another transaction
+// refuses, and nothing is asked or removed.
+//
+// The fence's removal reads only root's fence file (hadrain_call.go), never
+// the agent's answer: an agent that keeps drain state (its cancel refused,
+// or its socket not answering) keeps its own start gate closed until it
+// cancels or restarts, and a restarted agent holds none. The verb still
+// fails when the agent did not confirm, unless systemd says no edge
+// process runs, so the operator knows the agent may still be draining.
func (cmd *groupMaintenanceCommand) runDrainCancel(ctx context.Context) error {
fence := cmd.fenceAt()
if f := fence.read(); f.Present && (f.Err != nil || f.Transaction != cmd.txn) {
@@ -109,21 +158,25 @@ func (cmd *groupMaintenanceCommand) runDrainCancel(ctx context.Context) error {
}
ctx, cancel := context.WithTimeout(ctx, 2*time.Minute)
defer cancel()
- if err := cmd.drainSocket().cancel(ctx, cmd.txn); err != nil {
- if !errors.Is(err, errDrainAgentDown) {
- return err
- }
- // The socket does not answer. That proves no drain state only if
- // no agent runs: an edge process whose socket failed to start may
- // still be draining, and lifting its fence would leave it so,
- // unfenced. Only a confirmed stop lifts it; a running edge or a
- // probe that cannot tell keeps it.
- pid, _, perr := cmd.edge(ctx)
- if _, err := edgeConfirmedStopped(pid, perr); err != nil {
- return err
- }
+ r, callErr := cmd.agent()(ctx, "cancel", cmd.txn)
+ if callErr == nil {
+ callErr = r.err()
}
- return fence.remove(cmd.txn)
+ if err := fence.remove(cmd.txn); err != nil {
+ return err
+ }
+ if callErr == nil {
+ return nil
+ }
+ pid, _, perr := cmd.edge(ctx)
+ stopped, stopErr := edgeConfirmedStopped(pid, perr)
+ switch {
+ case stopped:
+ return nil
+ case errors.Is(callErr, errDrainAgentDown):
+ return stopErr
+ }
+ return callErr
}
// handoverStatus is status's fence and drain fields: the fence read from
@@ -138,13 +191,20 @@ func (cmd *groupMaintenanceCommand) handoverStatus(ctx context.Context) (mainten
fs.State, fs.Transaction = "present", &txn
}
ds := maintenanceDrainStatus{State: "unknown"}
- sctx, cancel := context.WithTimeout(ctx, time.Second)
+ sctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
- s, err := cmd.drainSocket().status(sctx)
+ r, err := cmd.agent()(sctx, "status", "")
+ if err == nil {
+ err = r.err()
+ }
+ if err == nil && r.Status == nil {
+ err = errors.New("the agent answered no status")
+ }
if err != nil {
ds.Error = maintenanceError(err)
return fs, ds
}
+ s := *r.Status
ds.State = "known"
ds.Incarnation, ds.Result = &s.Incarnation, &s.Result
if s.Transaction != "" {
diff --git a/internal/host/group_maintenance_verbs.go b/internal/host/group_maintenance_verbs.go
index 3a7c0a879..1c8e2ef5a 100644
--- a/internal/host/group_maintenance_verbs.go
+++ b/internal/host/group_maintenance_verbs.go
@@ -104,10 +104,11 @@ type groupMaintenanceCommand struct {
configure func(*systemApplier, map[string]string) error
// txn is the drain verbs' transaction.
txn string
- // fence and drain are the start fence and the agent's drain socket;
- // zero means production's (groupStartFence, haDrainSocketPath).
- fence *fenceLocation
- drain *drainClient
+ // fence and drainCall are the start fence and the agent call; zero
+ // means production's (groupStartFence, execDrainCall: a child as the
+ // agent's user, hadrain_call.go).
+ fence *fenceLocation
+ drainCall drainCaller
}
// drainVerb is whether verb is one of the drain verbs, whose argument is a
@@ -123,11 +124,11 @@ func (cmd *groupMaintenanceCommand) fenceAt() fenceLocation {
return groupStartFence
}
-func (cmd *groupMaintenanceCommand) drainSocket() *drainClient {
- if cmd.drain != nil {
- return cmd.drain
+func (cmd *groupMaintenanceCommand) agent() drainCaller {
+ if cmd.drainCall != nil {
+ return cmd.drainCall
}
- return newDrainClient(haDrainSocketPath)
+ return execDrainCall
}
func (cmd *groupMaintenanceCommand) run(ctx context.Context, verb string, in io.Reader, out io.Writer) error {
@@ -191,6 +192,8 @@ func (cmd *groupMaintenanceCommand) run(ctx context.Context, verb string, in io.
case "drain-cancel":
return cmd.runDrainCancel(ctx)
case "fence-clear":
+ // Root's fence file only (hadrain_call.go): an agent still holding
+ // drain state keeps its own start gate closed until its cancel.
return cmd.fenceAt().remove(cmd.txn)
}
var body []byte
diff --git a/internal/host/hadrain.go b/internal/host/hadrain.go
index ad4651aeb..c5c12d22c 100644
--- a/internal/host/hadrain.go
+++ b/internal/host/hadrain.go
@@ -2,7 +2,8 @@ package host
// The drain driver (region HA spec §25.4 steps 1 to 5, H5, §25.15 R3.1):
// the agent-side orchestration of a planned handover of this box. The
-// group-maintenance drain verb (root) asks for it over the agent's drain
+// group-maintenance drain verb (root, through a child running as the
+// agent's user, hadrain_call.go) asks for it over the agent's drain
// socket (hadrain_socket.go) in two steps:
//
// 1. withdraw: publish the drain state and wait until every live box of
@@ -111,6 +112,9 @@ type drainEdge interface {
type drainMarks interface {
begin(txn string) error
setDrained() error
+ // closeStarts closes the agent's own start gate, from the acknowledged
+ // withdrawal until clear (the fence's twin in memory, hadrain_call.go).
+ closeStarts()
clear()
waitPublished(ctx context.Context) (haDrainMark, error)
}
@@ -294,6 +298,13 @@ func (d *drainDriver) start(txn, step string) (<-chan struct{}, error) {
}
if step == "withdraw" {
d.withdrawn = rep.Result == "ok"
+ if d.withdrawn {
+ // The agent's own start gate closes with the withdrawal,
+ // as the fence the verb installs next does, and stays
+ // closed until drain --cancel, whatever happens to the
+ // fence (hadrain_call.go).
+ d.marks.closeStarts()
+ }
}
}()
return r.done, nil
diff --git a/internal/host/hadrain_call.go b/internal/host/hadrain_call.go
new file mode 100644
index 000000000..940d072bc
--- /dev/null
+++ b/internal/host/hadrain_call.go
@@ -0,0 +1,184 @@
+package host
+
+// The drain verbs' agent RPC, with root's privileges dropped (branch review
+// r1, Astra B1.3 and the census). The agent's drain socket and its
+// directory are the agent's own (hadrain_socket_linux.go), so root never
+// opens, dials or follows that path. A root verb runs this binary again as
+// a child, through the registry child's pattern (registrychild_exec_linux.go:
+// the pinned /proc/self/exe, no new privileges, an empty environment, "/"
+// as its directory); the child drops to the agent's user before it reads
+// anything (registryChildHarden: no supplementary groups, uid and gid of
+// carlos, not dumpable), dials the socket as that user, and prints one
+// drainCallResult. Root reads at most drainCallMax bytes of it from a pipe.
+//
+// What root does with an answer:
+// - relays it: drain prints the agent's report; status reports the drain
+// fields; drain --cancel reports whether the agent ended its drain;
+// - after the withdraw step, installs the start fence when the report
+// says ok. That only restricts: the fence refuses tenant starts on this
+// box, which the agent's user could do to itself anyway;
+// - drain joins a move step the agent reports running or done for the
+// same transaction, rather than asking for a withdraw it would refuse.
+//
+// Root's fence removals (drain --cancel, fence-clear) read only root's own
+// fence file and never depend on an answer. They are safe without asking
+// the agent because a running agent that holds drain state keeps its own
+// start gate closed (haDrainState.startClosed) until its own cancel, and an
+// agent that restarts holds none.
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+)
+
+// drainCallCommand is the child's private entry point, before CLI dispatch.
+const drainCallCommand = "__drain-call"
+
+// drainCallMax bounds the child's answer: the agent's own 4 MiB report
+// cap plus the envelope.
+const drainCallMax = 4<<20 + 4096
+
+// drainCallResult is the child's one answer.
+type drainCallResult struct {
+ V int `json:"v"`
+ // AgentDown: the socket did not accept the child's dial (no agent, or
+ // one whose socket is not serving).
+ AgentDown bool `json:"agent_down,omitempty"`
+ // Error is the call's failure, agent text included.
+ Error string `json:"error,omitempty"`
+ Report *drainReport `json:"report,omitempty"`
+ Status *drainStatus `json:"status,omitempty"`
+}
+
+// err is the call's failure as an error.
+func (r drainCallResult) err() error {
+ switch {
+ case r.AgentDown:
+ return errDrainAgentDown
+ case r.Error != "":
+ return errors.New(r.Error)
+ }
+ return nil
+}
+
+// drainCaller makes one call of the agent's drain socket: op is withdraw,
+// move, cancel or status. A transport failure of the caller itself (the
+// child did not run or answered nothing usable) is the error; the agent's
+// answer, a refusal included, is the result.
+type drainCaller func(ctx context.Context, op, txn string) (drainCallResult, error)
+
+// drainCallOp is whether op is a call the child makes.
+func drainCallOp(op string) bool {
+ return op == "withdraw" || op == "move" || op == "cancel" || op == "status"
+}
+
+// socketDrainCall is the call itself over c: the child's body, and the
+// in-process caller tests use.
+func socketDrainCall(c *drainClient) drainCaller {
+ return func(ctx context.Context, op, txn string) (drainCallResult, error) {
+ r := drainCallResult{V: 1}
+ var err error
+ switch op {
+ case "withdraw", "move":
+ r.Report, err = c.step(ctx, op, txn)
+ case "cancel":
+ err = c.cancel(ctx, txn)
+ case "status":
+ var s drainStatus
+ if s, err = c.status(ctx); err == nil {
+ r.Status = &s
+ }
+ default:
+ return r, errGroupMaintenance
+ }
+ if err != nil {
+ r.AgentDown = errors.Is(err, errDrainAgentDown)
+ r.Error = err.Error()
+ }
+ return r, nil
+ }
+}
+
+// drainCallArgs reads the child's arguments: an op and a transaction ("-"
+// for status).
+func drainCallArgs(args []string) (op, txn string, err error) {
+ if len(args) != 2 || !drainCallOp(args[0]) {
+ return "", "", errGroupMaintenance
+ }
+ op, txn = args[0], args[1]
+ if op == "status" {
+ if txn != "-" {
+ return "", "", errGroupMaintenance
+ }
+ return op, "", nil
+ }
+ if !groupTransactionID.MatchString(txn) || txn[0] == '-' {
+ return "", "", errGroupMaintenance
+ }
+ return op, txn, nil
+}
+
+// runDrainCallBody is the child after its privileges are dropped: one call
+// over the socket at path, its answer printed as one JSON line.
+func runDrainCallBody(ctx context.Context, args []string, path string, out io.Writer) error {
+ op, txn, err := drainCallArgs(args)
+ if err != nil {
+ return err
+ }
+ ctx, cancel := context.WithTimeout(ctx, haDrainCallBound)
+ defer cancel()
+ r, err := socketDrainCall(newDrainClient(path))(ctx, op, txn)
+ if err != nil {
+ return err
+ }
+ return json.NewEncoder(out).Encode(r)
+}
+
+// drainCallChildArgs is the child's argument list after the command: the
+// transaction is "-" for status.
+func drainCallChildArgs(op, txn string) []string {
+ if op == "status" {
+ txn = "-"
+ }
+ return []string{op, txn}
+}
+
+// parseDrainCall reads the child's answer: exactly one JSON object, at
+// most drainCallMax bytes, of the known shape.
+func parseDrainCall(b []byte) (drainCallResult, error) {
+ var r drainCallResult
+ if len(b) > drainCallMax {
+ return r, errors.New("the drain call's answer is too large")
+ }
+ dec := json.NewDecoder(bytes.NewReader(b))
+ dec.DisallowUnknownFields()
+ if err := dec.Decode(&r); err != nil || r.V != 1 {
+ return drainCallResult{}, errors.New("the drain call answered nothing usable")
+ }
+ if _, err := dec.Token(); err != io.EOF {
+ return drainCallResult{}, errors.New("the drain call answered nothing usable")
+ }
+ return r, nil
+}
+
+// cappedBuffer keeps at most max bytes and counts the rest as overflow, so
+// a child that writes too much is read as too large, never buffered.
+type cappedBuffer struct {
+ buf bytes.Buffer
+ max int
+ overflow bool
+}
+
+func (c *cappedBuffer) Write(p []byte) (int, error) {
+ if room := c.max - c.buf.Len(); len(p) > room {
+ c.overflow = true
+ if room > 0 {
+ c.buf.Write(p[:room])
+ }
+ return len(p), nil
+ }
+ return c.buf.Write(p)
+}
diff --git a/internal/host/hadrain_call_linux.go b/internal/host/hadrain_call_linux.go
new file mode 100644
index 000000000..1f7a06fc8
--- /dev/null
+++ b/internal/host/hadrain_call_linux.go
@@ -0,0 +1,101 @@
+//go:build linux
+
+package host
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "os/exec"
+ "time"
+)
+
+// execDrainCall is the production drainCaller: one child, run as the
+// agent's user, per call (hadrain_call.go).
+func execDrainCall(ctx context.Context, op, txn string) (drainCallResult, error) {
+ if !drainCallOp(op) {
+ return drainCallResult{}, errGroupMaintenance
+ }
+ cmd, err := drainCallExec(op, txn)
+ if err != nil {
+ return drainCallResult{}, err
+ }
+ return runDrainCallChild(ctx, cmd)
+}
+
+// drainCallExec is the child's command: the pinned executable (fd 3, as
+// the registry child), the private command, op and transaction, an empty
+// environment, "/" as its directory, and no stdin.
+func drainCallExec(op, txn string) (*exec.Cmd, error) {
+ if registryExecutableError != nil {
+ return nil, registryExecutableError
+ }
+ cmd := exec.Command("/proc/self/fd/3", append([]string{drainCallCommand}, drainCallChildArgs(op, txn)...)...)
+ cmd.ExtraFiles = []*os.File{registryExecutable}
+ cmd.Env = []string{}
+ cmd.Dir = "/"
+ cmd.Stdin = nil
+ return cmd, nil
+}
+
+// runDrainCallChild starts cmd with no new privileges, reads its answer
+// (bounded) and waits for it. ctx's end kills the child.
+func runDrainCallChild(ctx context.Context, cmd *exec.Cmd) (drainCallResult, error) {
+ if err := registryChildCloseExec(); err != nil {
+ return drainCallResult{}, err
+ }
+ out := &cappedBuffer{max: drainCallMax}
+ errOut := &cappedBuffer{max: 4096}
+ cmd.Stdout, cmd.Stderr = out, errOut
+ cmd.WaitDelay = 5 * time.Second
+ if err := registryChildStart(cmd); err != nil {
+ return drainCallResult{}, err
+ }
+ waited := make(chan error, 1)
+ go func() { waited <- cmd.Wait() }()
+ var err error
+ select {
+ case err = <-waited:
+ case <-ctx.Done():
+ _ = cmd.Process.Kill()
+ <-waited
+ return drainCallResult{}, ctx.Err()
+ }
+ if out.overflow {
+ return drainCallResult{}, errors.New("the drain call's answer is too large")
+ }
+ if err != nil {
+ return drainCallResult{}, fmt.Errorf("the drain call failed: %v: %s", err, bytesTrim(errOut.buf.Bytes()))
+ }
+ return parseDrainCall(out.buf.Bytes())
+}
+
+func bytesTrim(b []byte) string {
+ for len(b) > 0 && (b[len(b)-1] == '\n' || b[len(b)-1] == ' ') {
+ b = b[:len(b)-1]
+ }
+ return string(b)
+}
+
+// RunDrainCall is the child's private entry point, before CLI dispatch:
+// it drops to the agent's user first (registryChildHarden), then makes
+// one call over the agent's drain socket and prints the answer. It
+// refuses to run as root.
+func RunDrainCall(args []string, out io.Writer) int {
+ if err := registryChildHarden(); err != nil {
+ fmt.Fprintf(os.Stderr, "drain call: %v\n", err)
+ return 1
+ }
+ closeRegistryExecutable()
+ if os.Geteuid() == 0 {
+ fmt.Fprintln(os.Stderr, "drain call: still root")
+ return 1
+ }
+ if err := runDrainCallBody(context.Background(), args, haDrainSocketPath, out); err != nil {
+ fmt.Fprintf(os.Stderr, "drain call: %v\n", err)
+ return 1
+ }
+ return 0
+}
diff --git a/internal/host/hadrain_call_linux_test.go b/internal/host/hadrain_call_linux_test.go
new file mode 100644
index 000000000..928984dd8
--- /dev/null
+++ b/internal/host/hadrain_call_linux_test.go
@@ -0,0 +1,374 @@
+//go:build linux
+
+package host
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "regexp"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/groupadmission"
+)
+
+// The drain call child (hadrain_call.go), re-executed from this test
+// binary by TestDrainCallChildEndToEnd. Production drops to carlos first
+// (registryChildHarden), which needs root; here the body runs as the
+// test's own user against the test's socket, named in the environment
+// the test adds to production's empty one.
+func init() {
+ if len(os.Args) > 1 && os.Args[1] == drainCallCommand {
+ p := os.Getenv("HADRAIN_CALL_TEST_SOCKET")
+ if p == "" {
+ os.Exit(RunDrainCall(os.Args[2:], os.Stdout))
+ }
+ closeRegistryExecutable()
+ if err := runDrainCallBody(context.Background(), os.Args[2:], p, os.Stdout); err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
+ os.Exit(0)
+ }
+}
+
+// The child's command: the pinned executable, the private command, op and
+// transaction; an empty environment, "/" and no stdin. It runs through the
+// registry child's start (no new privileges) and drops to carlos itself.
+func TestDrainCallCommand(t *testing.T) {
+ cmd, err := drainCallExec("move", "t1")
+ must(t, err)
+ if cmd.Path != "/proc/self/fd/3" || strings.Join(cmd.Args, " ") != "/proc/self/fd/3 __drain-call move t1" {
+ t.Fatalf("command %q %q", cmd.Path, cmd.Args)
+ }
+ if cmd.Env == nil || len(cmd.Env) != 0 || cmd.Dir != "/" || cmd.Stdin != nil || len(cmd.ExtraFiles) != 1 || cmd.ExtraFiles[0] != registryExecutable {
+ t.Fatalf("env %q dir %q stdin %v extra %v", cmd.Env, cmd.Dir, cmd.Stdin, cmd.ExtraFiles)
+ }
+ if cmd, _ = drainCallExec("status", ""); strings.Join(cmd.Args[1:], " ") != "__drain-call status -" {
+ t.Fatalf("status args %q", cmd.Args)
+ }
+ if _, err := execDrainCall(context.Background(), "stop", "t1"); err == nil {
+ t.Fatal("an unknown op ran a child")
+ }
+}
+
+func TestDrainCallArgs(t *testing.T) {
+ for _, tc := range []struct {
+ args []string
+ op, txn string
+ bad bool
+ }{
+ {[]string{"withdraw", "t1"}, "withdraw", "t1", false},
+ {[]string{"move", "t1"}, "move", "t1", false},
+ {[]string{"cancel", "t1"}, "cancel", "t1", false},
+ {[]string{"status", "-"}, "status", "", false},
+ {[]string{"status", "t1"}, "", "", true},
+ {[]string{"stop", "t1"}, "", "", true},
+ {[]string{"move", "../x"}, "", "", true},
+ {[]string{"move", "-x"}, "", "", true},
+ {[]string{"move"}, "", "", true},
+ {[]string{"move", "t1", "x"}, "", "", true},
+ } {
+ op, txn, err := drainCallArgs(tc.args)
+ if (err != nil) != tc.bad || op != tc.op || txn != tc.txn {
+ t.Fatalf("%q: %q %q %v", tc.args, op, txn, err)
+ }
+ }
+}
+
+// Root reads exactly one known JSON object, bounded.
+func TestParseDrainCall(t *testing.T) {
+ if r, err := parseDrainCall([]byte(`{"v":1,"report":{"v":1,"transaction":"t1","result":"ok"}}` + "\n")); err != nil || r.Report == nil || r.Report.Result != "ok" {
+ t.Fatalf("good answer: %+v %v", r, err)
+ }
+ for _, bad := range []string{``, `{}`, `{"v":2}`, `{"v":1,"extra":1}`, `{"v":1}{"v":1}`, `{"v":1} x`, `[1]`, `{"v":1,"report":{"unknown":1}}`} {
+ if _, err := parseDrainCall([]byte(bad)); err == nil {
+ t.Fatalf("%q was accepted", bad)
+ }
+ }
+ if _, err := parseDrainCall(bytes.Repeat([]byte(" "), drainCallMax+1)); err == nil {
+ t.Fatal("an oversized answer was accepted")
+ }
+ c := &cappedBuffer{max: 4}
+ c.Write([]byte("abc"))
+ c.Write([]byte("de"))
+ if !c.overflow || c.buf.String() != "abcd" {
+ t.Fatalf("capped %q %v", c.buf.String(), c.overflow)
+ }
+}
+
+// End to end: root's caller runs the real child from the pinned
+// executable, which dials the agent's socket and answers; a refusal is an
+// answer, a missing agent is agent_down, and the verb's whole drain runs
+// through it.
+func TestDrainCallChildEndToEnd(t *testing.T) {
+ act, ed, marks := healthyDrain()
+ d := newDrainDriver(act, ed, marks, nil)
+ cmd, l := verbDrain(t, d)
+ d.fence = l.read
+ path := socketPathOf(t, cmd)
+ child := func(ctx context.Context, op, txn string) (drainCallResult, error) {
+ c, err := drainCallExec(op, txn)
+ if err != nil {
+ return drainCallResult{}, err
+ }
+ c.Env = []string{"HADRAIN_CALL_TEST_SOCKET=" + path}
+ return runDrainCallChild(ctx, c)
+ }
+ r, err := child(context.Background(), "status", "")
+ if err != nil || r.err() != nil || r.Status == nil || r.Status.Incarnation != agentIncarnation {
+ t.Fatalf("status through the child: %+v %v", r, err)
+ }
+ cmd.drainCall = child
+ rep, err := runDrainVerb(t, cmd, "drain", "t1")
+ if err != nil || rep.Result != "ok" || l.read().Transaction != "t1" {
+ t.Fatalf("drain through the child: %+v %v fence %+v", rep, err, l.read())
+ }
+ if !marks.startsClosed() {
+ t.Fatal("the agent's own start gate is open after the withdrawal")
+ }
+ // A refusal comes back as the agent's answer, not a caller failure.
+ if r, err = child(context.Background(), "cancel", "t2"); err != nil || !strings.Contains(r.Error, errDrainOtherTxn.Error()) || r.AgentDown {
+ t.Fatalf("refused cancel: %+v %v", r, err)
+ }
+ if _, err = runDrainVerb(t, cmd, "drain-cancel", "t1"); err != nil || l.read().Present || marks.startsClosed() {
+ t.Fatalf("cancel through the child: %v fence %+v closed %v", err, l.read(), marks.startsClosed())
+ }
+ // No agent: agent_down.
+ other := filepath.Join(filepath.Dir(path), "none.sock")
+ c, _ := drainCallExec("status", "")
+ c.Env = []string{"HADRAIN_CALL_TEST_SOCKET=" + other}
+ if r, err = runDrainCallChild(context.Background(), c); err != nil || !r.AgentDown {
+ t.Fatalf("no agent: %+v %v", r, err)
+ }
+ // A child that fails or is killed is a caller error, not an answer.
+ c, _ = drainCallExec("status", "")
+ c.Env = []string{"HADRAIN_CALL_TEST_SOCKET=" + path}
+ c.Args = []string{c.Args[0], drainCallCommand, "status", "t1"}
+ if _, err = runDrainCallChild(context.Background(), c); err == nil {
+ t.Fatal("a child that refused its arguments answered")
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ c, _ = drainCallExec("status", "")
+ c.Env = []string{"HADRAIN_CALL_TEST_SOCKET=" + path}
+ if _, err = runDrainCallChild(ctx, c); err == nil {
+ t.Fatal("a cancelled call answered")
+ }
+}
+
+// Without the test's socket the child is production's: as a non-root
+// user it cannot drop to carlos and refuses before dialing anything.
+func TestDrainCallChildRefusesWithoutDrop(t *testing.T) {
+ if os.Geteuid() == 0 {
+ t.Skip("as root the child would drop to carlos")
+ }
+ c, err := drainCallExec("status", "")
+ must(t, err)
+ out := &cappedBuffer{max: 4096}
+ errOut := &cappedBuffer{max: 4096}
+ c.Stdout, c.Stderr = out, errOut
+ must(t, registryChildCloseExec())
+ if err := registryChildStart(c); err != nil {
+ t.Fatal(err)
+ }
+ if err := c.Wait(); err == nil || out.buf.Len() != 0 {
+ t.Fatalf("the undropped child ran: %v %q", err, out.buf.String())
+ }
+ if _, ok := err.(*exec.ExitError); !ok && err != nil {
+ t.Logf("child: %v", err)
+ }
+}
+
+// Root never dials the agent's socket: outside the child's body
+// (hadrain_call.go) and the socket's own file, no production file builds a
+// drain socket client, and the verbs reach the agent only through
+// cmd.agent().
+func TestRootNeverDialsTheDrainSocket(t *testing.T) {
+ files, err := filepath.Glob("*.go")
+ must(t, err)
+ client := regexp.MustCompile(`newDrainClient\(|haDrainSocketPath`)
+ for _, f := range files {
+ if strings.HasSuffix(f, "_test.go") {
+ continue
+ }
+ b, err := os.ReadFile(f)
+ must(t, err)
+ if !client.Match(b) {
+ continue
+ }
+ switch f {
+ case "hadrain_call.go", "hadrain_call_linux.go", "hadrain_socket.go", "agent.go":
+ // the child's body and entry, the socket itself, the agent's listener
+ default:
+ t.Errorf("%s reaches the drain socket directly", f)
+ }
+ }
+ b, err := os.ReadFile("agent.go")
+ must(t, err)
+ if n := len(client.FindAll(b, -1)); n != 1 || !bytes.Contains(b, []byte("serveHADrainSocket(healthCtx, haDrainSocketPath, driver)")) {
+ t.Errorf("agent.go names the socket %d times; want only its listener", n)
+ }
+}
+
+// A rerun of drain joins the move step it finds running for its
+// transaction (branch review r1, Fable B1.2): the first verb's caller goes
+// away mid-move (a dropped session), the agent keeps moving, and drain
+// again asks for the move, not a withdraw it would refuse, and returns the
+// same drain's report.
+func TestDrainRerunJoinsTheRunningMove(t *testing.T) {
+ act, ed, marks := healthyDrain()
+ release := make(chan struct{})
+ entered := make(chan struct{}, 1)
+ act.onBeginMove = func(string) {
+ select {
+ case entered <- struct{}{}:
+ default:
+ }
+ <-release
+ }
+ d := newDrainDriver(act, ed, marks, nil)
+ cmd, l := verbDrain(t, d)
+ d.fence = l.read
+ ctx, cancel := context.WithCancel(context.Background())
+ first := make(chan error, 1)
+ go func() {
+ cmd.txn = "t1"
+ _, err := cmd.runDrainForTest(ctx)
+ first <- err
+ }()
+ select {
+ case <-entered:
+ case <-time.After(10 * time.Second):
+ t.Fatal("the move never started")
+ }
+ cancel() // the session drops
+ if err := <-first; err == nil {
+ t.Fatal("the dropped call reported success")
+ }
+ if s := d.status(); s.Step != "move" || s.Result != "running" {
+ t.Fatalf("the agent stopped moving when the caller went: %+v", s)
+ }
+ rerun := make(chan error, 1)
+ var out []byte
+ go func() {
+ var err error
+ out, err = cmd.runDrainForTest(context.Background())
+ rerun <- err
+ }()
+ time.Sleep(50 * time.Millisecond)
+ close(release)
+ if err := <-rerun; err != nil {
+ t.Fatalf("rerun: %v (%s)", err, out)
+ }
+ var rep drainReport
+ must(t, json.Unmarshal(out, &rep))
+ if rep.Result != "ok" || rep.Step != "move" || rep.Transaction != "t1" {
+ t.Fatalf("rerun report: %s", out)
+ }
+ if begun, _, _ := marks.counts(); begun != 1 {
+ t.Fatalf("the rerun withdrew again (%d withdrawals)", begun)
+ }
+ // A rerun after the move finished answers its report at once.
+ out, err := cmd.runDrainForTest(context.Background())
+ if err != nil || !bytes.Contains(out, []byte(`"result":"ok"`)) {
+ t.Fatalf("rerun after the move: %v %s", err, out)
+ }
+}
+
+// The agent's own start gate closes with an acknowledged withdrawal and
+// opens only at cancel: lifting the fence (fence-clear, or a cancel whose
+// agent call failed) never opens a drain in progress.
+func TestDrainStartGateFollowsTheAgentNotTheFence(t *testing.T) {
+ // The state itself: closeStarts until clear, nothing else opens it.
+ s := newHADrainState()
+ s.closeStarts()
+ must(t, s.begin("t1"))
+ must(t, s.setDrained())
+ s.setFenceSource(func() bool { return false })
+ if !s.startClosed() {
+ t.Fatal("the agent's start gate opened without clear")
+ }
+ s.clear()
+ if s.startClosed() {
+ t.Fatal("clear left the gate closed")
+ }
+
+ // Through the verbs and the start gate.
+ act, ed, marks := healthyDrain()
+ d := newDrainDriver(act, ed, marks, nil)
+ cmd, l := verbDrain(t, d)
+ d.fence = l.read
+ if marks.startsClosed() {
+ t.Fatal("closed before any drain")
+ }
+ if _, err := runDrainVerb(t, cmd, "drain", "t1"); err != nil {
+ t.Fatal(err)
+ }
+ if !marks.startsClosed() {
+ t.Fatal("the agent's start gate is open after the drain")
+ }
+ if _, err := runDrainVerb(t, cmd, "fence-clear", "t1"); err != nil || l.read().Present {
+ t.Fatalf("fence-clear: %v", err)
+ }
+ if !marks.startsClosed() {
+ t.Fatal("fence-clear opened a draining agent's start gate")
+ }
+ saved := drainStartsClosed
+ drainStartsClosed = marks.startsClosed
+ defer func() { drainStartsClosed = saved }()
+ savedFence := startFenced
+ startFenced = func() bool { return false }
+ defer func() { startFenced = savedFence }()
+ a := admittedGroupMember(t)
+ if a.startAllowed() {
+ t.Fatal("a draining agent with no fence allows starts")
+ }
+ if _, err := runDrainVerb(t, cmd, "drain-cancel", "t1"); err != nil {
+ t.Fatal(err)
+ }
+ if marks.startsClosed() || !a.startAllowed() {
+ t.Fatal("cancel did not open the agent's start gate")
+ }
+ // A withdrawal that fails closes nothing.
+ ed.ack = func(string) (bool, error) { return false, nil }
+ defer shorten(&drainAckBound, 50*time.Millisecond)()
+ defer shorten(&drainAckEvery, 10*time.Millisecond)()
+ if _, err := runDrainVerb(t, cmd, "drain", "t2"); err == nil || marks.startsClosed() {
+ t.Fatalf("failed withdraw: %v, closed %v", err, marks.startsClosed())
+ }
+}
+
+func socketPathOf(t *testing.T, cmd *groupMaintenanceCommand) string {
+ t.Helper()
+ p, ok := drainSocketPaths.Load(cmd)
+ if !ok {
+ t.Fatal("no socket recorded for the fixture")
+ }
+ return p.(string)
+}
+
+// drainSocketPaths records each verbDrain fixture's socket path.
+var drainSocketPaths sync.Map
+
+func (cmd *groupMaintenanceCommand) runDrainForTest(ctx context.Context) ([]byte, error) {
+ var out bytes.Buffer
+ err := cmd.run(ctx, "drain", bytes.NewReader(nil), &out)
+ return out.Bytes(), err
+}
+
+// admittedGroupMember is an admitted group member's admission.
+func admittedGroupMember(t *testing.T) *fixedAdmission {
+ t.Helper()
+ a := readyGroupAdmission(t)
+ a.observe(groupadmission.Facts{TerminationStarted: true})
+ a.tick(t.Context())
+ return a
+}
diff --git a/internal/host/hadrain_call_other.go b/internal/host/hadrain_call_other.go
new file mode 100644
index 000000000..3845266f9
--- /dev/null
+++ b/internal/host/hadrain_call_other.go
@@ -0,0 +1,21 @@
+//go:build !linux
+
+package host
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "os"
+)
+
+// execDrainCall: the drain verbs are Linux group members' only.
+func execDrainCall(context.Context, string, string) (drainCallResult, error) {
+ return drainCallResult{}, errSystemUnsupported
+}
+
+// RunDrainCall: the drain verbs are Linux group members' only.
+func RunDrainCall([]string, io.Writer) int {
+ fmt.Fprintln(os.Stderr, "drain call: requires Linux")
+ return 1
+}
diff --git a/internal/host/hadrain_socket.go b/internal/host/hadrain_socket.go
index 430870337..a57803042 100644
--- a/internal/host/hadrain_socket.go
+++ b/internal/host/hadrain_socket.go
@@ -1,10 +1,12 @@
package host
-// The agent's drain socket: how the root group-maintenance verbs reach the
+// The agent's drain socket: how the group-maintenance verbs reach the
// drain driver (hadrain.go). It is a unix socket in a directory only the
// agent's user can enter (0700), and the listener serves only a peer the
-// kernel reports as root (SO_PEERCRED). Instances never see it: their
-// namespaces replace /run/carlos with an empty tmpfs.
+// kernel reports as that user (SO_PEERCRED). The root verbs never dial it:
+// they run a child that drops to the agent's user and makes the call
+// (hadrain_call.go). Instances never see it: their namespaces replace
+// /run/carlos with an empty tmpfs.
//
// POST /v1/drain/withdraw {"transaction":T} step 1; answers the report
// POST /v1/drain/move {"transaction":T} steps 2-5; answers the report
@@ -107,7 +109,8 @@ func (d *drainDriver) handler() http.Handler {
})
}
-// drainClient is the root verbs' side of the socket.
+// drainClient is the caller's side of the socket: the drain call child,
+// running as the agent's user.
type drainClient struct {
c *http.Client
}
diff --git a/internal/host/hadrain_socket_linux.go b/internal/host/hadrain_socket_linux.go
index f8144d342..0abacb53e 100644
--- a/internal/host/hadrain_socket_linux.go
+++ b/internal/host/hadrain_socket_linux.go
@@ -17,16 +17,18 @@ import (
"golang.org/x/sys/unix"
)
-// drainPeerSeam replaces the root-only peer rule in tests; nil in
-// production.
+// drainPeerSeam replaces the peer rule in tests; nil in production.
var drainPeerSeam atomic.Pointer[func(uint32) bool]
-// drainPeerAllowed is whether the drain socket serves uid: root only.
+// drainPeerAllowed is whether the drain socket serves uid: the agent's own
+// user only. The root verbs reach it through a child that has dropped to
+// that user (hadrain_call.go); root itself never dials it. A process of
+// the agent's user gains nothing here it could not do as the agent.
func drainPeerAllowed(uid uint32) bool {
if f := drainPeerSeam.Load(); f != nil {
return (*f)(uid)
}
- return uid == 0
+ return uid == uint32(os.Geteuid())
}
type drainPeerKey struct{}
diff --git a/internal/host/hadrain_test.go b/internal/host/hadrain_test.go
index 60ad78d47..54ea74458 100644
--- a/internal/host/hadrain_test.go
+++ b/internal/host/hadrain_test.go
@@ -342,7 +342,7 @@ type fakeMarks struct {
mu sync.Mutex
id uint64
begun, drained, cleared int
- stuck bool
+ stuck, closed bool
}
func (f *fakeMarks) begin(string) error {
@@ -365,6 +365,17 @@ func (f *fakeMarks) clear() {
f.mu.Lock()
defer f.mu.Unlock()
f.cleared++
+ f.closed = false
+}
+func (f *fakeMarks) closeStarts() {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.closed = true
+}
+func (f *fakeMarks) startsClosed() bool {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.closed
}
func (f *fakeMarks) counts() (begun, drained, cleared int) {
f.mu.Lock()
diff --git a/internal/host/hadrainfence_linux_test.go b/internal/host/hadrainfence_linux_test.go
index 216467e4c..db71a364f 100644
--- a/internal/host/hadrainfence_linux_test.go
+++ b/internal/host/hadrainfence_linux_test.go
@@ -185,8 +185,13 @@ func TestStartFenceRefusesStartsAcrossRestart(t *testing.T) {
}
}
-// The drain socket serves root only.
-func TestDrainSocketServesRootOnly(t *testing.T) {
+// The drain socket serves the agent's own user only: the drain call child
+// after it dropped to that user (hadrain_call.go), never root.
+func TestDrainSocketServesTheAgentUserOnly(t *testing.T) {
+ me := uint32(os.Geteuid())
+ if !drainPeerAllowed(me) || drainPeerAllowed(me+1) || (me != 0 && drainPeerAllowed(0)) {
+ t.Fatalf("peer rule: self %v, another uid %v, root %v", drainPeerAllowed(me), drainPeerAllowed(me+1), drainPeerAllowed(0))
+ }
dir, err := os.MkdirTemp("", "hd")
must(t, err)
t.Cleanup(func() { os.RemoveAll(dir) })
@@ -198,12 +203,11 @@ func TestDrainSocketServesRootOnly(t *testing.T) {
t.Cleanup(func() { cancel(); <-done })
waitSocket(t, path)
c := newDrainClient(path)
- if os.Geteuid() == 0 {
- t.Log("running as root: the non-root refusal is not exercised")
- } else if _, err := c.status(context.Background()); err == nil {
- t.Fatal("a non-root peer was served")
+ setDrainPeer(t, func(uint32) bool { return false })
+ if _, err := c.status(context.Background()); err == nil {
+ t.Fatal("a refused peer was served")
}
- setDrainPeer(t, func(uid uint32) bool { return int(uid) == os.Geteuid() })
+ drainPeerSeam.Store(nil) // production's rule: this test's user is the agent's
s, err := c.status(context.Background())
if err != nil || s.Incarnation != agentIncarnation || s.Result != "none" {
t.Fatalf("status: %+v %v", s, err)
@@ -261,7 +265,9 @@ func verbDrain(t *testing.T, d *drainDriver) (*groupMaintenanceCommand, fenceLoc
t.Cleanup(func() { cancel(); <-done })
waitSocket(t, path)
}
- cmd.drain = newDrainClient(path)
+ cmd.drainCall = socketDrainCall(newDrainClient(path))
+ drainSocketPaths.Store(cmd, path)
+ t.Cleanup(func() { drainSocketPaths.Delete(cmd) })
cmd.txn = ""
return cmd, l
}
@@ -335,11 +341,13 @@ func TestDrainVerbFenceAndCancel(t *testing.T) {
}
must(t, d.cancel(context.Background(), "t1")) // the agent forgot t1...
must(t, d.startWithdrawForTest("t3")) // ...and now drains t3
+ // The agent refuses; the verb says so, but t1's fence goes: removing
+ // it reads only root's fence file, never the agent's answer.
if _, err := runDrainVerb(t, cmd, "drain-cancel", "t1"); err == nil || !strings.Contains(err.Error(), errDrainOtherTxn.Error()) {
t.Fatalf("cancel of t1 while the agent drains t3: %v", err)
}
- if s := l.read(); s.Transaction != "t1" {
- t.Fatal("a refused cancel removed the fence")
+ if l.read().Present {
+ t.Fatal("cancel kept t1's fence because the agent refused")
}
must(t, d.cancel(context.Background(), "t3"))
if _, err := runDrainVerb(t, cmd, "drain-cancel", "t1"); err != nil {
@@ -421,10 +429,12 @@ func TestDrainVerbArguments(t *testing.T) {
}
}
-// drain --cancel never lifts the fence of an agent it cannot reach unless
-// the edge is confirmed stopped: a running edge, or a probe that cannot
-// tell (timed out, a systemctl failure, a malformed MainPID, a failed
-// process-identity read), keeps the fence and exits non-zero.
+// drain --cancel removes its transaction's fence whatever the agent
+// answers (root's decision reads only its own file; an agent holding drain
+// state keeps its own start gate closed). It exits non-zero when it cannot
+// reach the agent unless the edge is confirmed stopped: a running edge, or
+// a probe that cannot tell (timed out, a systemctl failure, a malformed
+// MainPID, a failed process-identity read).
func TestDrainCancelNeedsAConfirmedStop(t *testing.T) {
for _, tc := range []struct {
name string
@@ -448,8 +458,8 @@ func TestDrainCancelNeedsAConfirmedStop(t *testing.T) {
if !errors.Is(err, tc.want) && !(tc.want == nil && err == nil) {
t.Fatalf("cancel: %v, want %v", err, tc.want)
}
- if kept := l.read().Present; kept != (tc.want != nil) {
- t.Fatalf("fence present %v after %s", kept, tc.name)
+ if l.read().Present {
+ t.Fatalf("fence kept after %s", tc.name)
}
})
}
diff --git a/internal/host/hadrainstate.go b/internal/host/hadrainstate.go
index bad0373bf..f77c43393 100644
--- a/internal/host/hadrainstate.go
+++ b/internal/host/hadrainstate.go
@@ -38,9 +38,14 @@ type haDrainState struct {
// boxes). fenced is its last reading.
fence func() bool
fenced bool
- mark *haDrainMark
- lastID uint64
- pub haDrainPublished
+ // startsClosed is the agent's own start gate: closed by the drain
+ // driver at an acknowledged withdrawal, opened only by clear (drain
+ // --cancel). Process memory: a restarted agent holds none, and the
+ // fence on disk gates it instead.
+ startsClosed bool
+ mark *haDrainMark
+ lastID uint64
+ pub haDrainPublished
// changed is closed and replaced at every reported publication.
changed chan struct{}
}
@@ -127,11 +132,28 @@ func (s *haDrainState) begin(txn string) error {
return nil
}
-// clear leaves the drain state, drained included.
+// clear leaves the drain state, drained included, and opens the agent's
+// own start gate.
func (s *haDrainState) clear() {
s.mu.Lock()
defer s.mu.Unlock()
s.draining, s.drained, s.mark = false, false, nil
+ s.startsClosed = false
+}
+
+// closeStarts closes the agent's own start gate until clear.
+func (s *haDrainState) closeStarts() {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.startsClosed = true
+}
+
+// startClosed is whether the agent's own start gate is closed: the start
+// gate refuses every tenant start then, as it does while fenced.
+func (s *haDrainState) startClosed() bool {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.startsClosed
}
// setDrained publishes drained (§25.4 step 4), which needs draining, under
diff --git a/main.go b/main.go
index 51f45701a..81a4c2aad 100644
--- a/main.go
+++ b/main.go
@@ -45,6 +45,11 @@ func main() {
}
return
}
+ // The drain verbs' agent call, run as the agent's user
+ // (internal/host/hadrain_call.go): plumbing, never typed.
+ if cmd == "__drain-call" {
+ os.Exit(host.RunDrainCall(args, os.Stdout))
+ }
if cmd == "__registry-child" {
if err := host.RunRegistryChild(args); err != nil {
log.Fatal(err)