Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Drive executing-action restart recovery at startup and agent registration

rcourtmanacd56374853f
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 00efee35fe..302f59cedf 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -485,6 +485,15 @@ module attests the first mutating step (the backup rename), so failures before
it report an unmutated tree, and restore attempts with their outcome ride the
result so the server-side executor reports declared compensation truth instead
of guessing.
+Agent (re)registration on the `internal/agentexec` command server is also the
+durable-dispatch recovery trigger: after a successful registration the server
+fires a router-installed notifier that re-drives the API-owned
+executing-action recovery pass, because a receipt-pending dispatch attempt
+can only be reconciled against the agent's durable operation receipt while
+that agent is connected. The notifier is observation-only wiring; it grants
+no command authority, fires only after token validation admits the agent, and
+a rejected or replaced registration must not synthesize receipts or resend
+transport.
Host OS package updates follow a stricter adjacent boundary. The Unified Agent
may report a bounded, read-only APT upgrade simulation through
`pkg/agents/host/report.go`, but installation authority is available only via
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 23ac1c5b62..4e89f30f69 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -7449,6 +7449,15 @@ consumption remain separate work; no mobile or relay-local workaround may
compensate for a missing core API. Claims 16 and 17 remain open pending Task 09
resumption, real browser/lab evidence, and Task 12 certification.
+That callable reconciliation path is production-driven, not merely callable:
+the API server runs `RecoverExecutingActions` for every organization from a
+startup background worker and again whenever an agent (re)registers on the
+agentexec command server, because a receipt-pending attempt can only be
+answered while the owning agent is connected. Both triggers reuse the same
+bounded, serialized pass; neither introduces a new resend authority, and a
+disconnected agent simply leaves the action `executing`/`receipt_pending`
+until its next registration re-drives reconciliation.
+
Typed Docker / Podman container start, stop, and restart operations extend that
same durable boundary rather than creating a provider-local action protocol.
The agent wire request is closed and binds the exact action, dispatch attempt,
diff --git a/internal/agentexec/server.go b/internal/agentexec/server.go
index a236ce4af4..8da97f9f9c 100644
--- a/internal/agentexec/server.go
+++ b/internal/agentexec/server.go
@@ -81,6 +81,7 @@ type Server struct {
commandAuthorizationVerifier func(CommandAuthorizationRequest) error
newCommandApprovalGrant func([]byte, string, ExecuteCommandPayload, time.Time, time.Duration) (*CommandApprovalGrant, error)
now func() time.Time
+ agentRegisteredNotifier func(agentID string)
}
// CommandAuthorizationRequest is the complete server-side approval scope
@@ -172,6 +173,20 @@ func (s *Server) SetCommandAuthorizationVerifier(verifier func(CommandAuthorizat
s.commandAuthorizationVerifier = verifier
}
+// SetAgentRegisteredNotifier installs a callback fired after an agent
+// completes registration (including a reconnect that replaces an existing
+// connection). Durable-dispatch recovery hangs off this: receipt-pending
+// reconciliation can only query an agent while it is connected, so the
+// registration itself is the recovery trigger. The callback runs on its own
+// goroutine because the query response can only be read once this server
+// enters the connection's read loop.
+func (s *Server) SetAgentRegisteredNotifier(notify func(agentID string)) {
+ if s == nil {
+ return
+ }
+ s.agentRegisteredNotifier = notify
+}
+
func (s *Server) isShuttingDown() bool {
select {
case <-s.shutdown:
@@ -817,6 +832,10 @@ func (s *Server) HandleWebSocket(w http.ResponseWriter, r *http.Request) {
go s.pingLoop(ac, pingDone)
defer close(pingDone)
+ if notify := s.agentRegisteredNotifier; notify != nil {
+ go notify(reg.AgentID)
+ }
+
// Run read loop (blocking) - don't use goroutine, or HTTP handler will close connection
s.readLoop(ac)
}
diff --git a/internal/agentexec/server_websocket_test.go b/internal/agentexec/server_websocket_test.go
index d150f7615f..a2b1700dae 100644
--- a/internal/agentexec/server_websocket_test.go
+++ b/internal/agentexec/server_websocket_test.go
@@ -285,6 +285,52 @@ func TestHandleWebSocket_RejectsPerIPConnectionFlood(t *testing.T) {
}
}
+func TestHandleWebSocket_RegistrationFiresAgentRegisteredNotifier(t *testing.T) {
+ s := NewServer(func(token string, agentID string, hostname string) bool { return token == "ok" })
+ notified := make(chan string, 2)
+ s.SetAgentRegisteredNotifier(func(agentID string) { notified <- agentID })
+ ts := newWSServer(t, s)
+ defer ts.Close()
+
+ rejectedConn, _, err := dialAgentExecWebSocket(t, ts.URL)
+ if err != nil {
+ t.Fatalf("Dial: %v", err)
+ }
+ defer rejectedConn.Close()
+ wsWriteMessage(t, rejectedConn, mustNewMessage(t, MsgTypeAgentRegister, "", AgentRegisterPayload{
+ AgentID: "a-rejected", Hostname: "host-rejected", Token: "bad",
+ }))
+ if reg := wsReadRegisteredPayload(t, rejectedConn); reg.Success {
+ t.Fatalf("expected registration to be rejected")
+ }
+
+ conn, _, err := dialAgentExecWebSocket(t, ts.URL)
+ if err != nil {
+ t.Fatalf("Dial: %v", err)
+ }
+ defer conn.Close()
+ wsWriteMessage(t, conn, mustNewMessage(t, MsgTypeAgentRegister, "", AgentRegisterPayload{
+ AgentID: "a1", Hostname: "host1", Token: "ok",
+ }))
+ if reg := wsReadRegisteredPayload(t, conn); !reg.Success {
+ t.Fatalf("registration failed: %q", reg.Message)
+ }
+
+ select {
+ case agentID := <-notified:
+ if agentID != "a1" {
+ t.Fatalf("notified agent = %q, want a1 (rejected registration must not notify)", agentID)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("agent-registered notifier did not fire")
+ }
+ select {
+ case agentID := <-notified:
+ t.Fatalf("unexpected second notification for agent %q", agentID)
+ case <-time.After(100 * time.Millisecond):
+ }
+}
+
func TestHandleWebSocket_InvalidTokenRejected(t *testing.T) {
s := NewServer(func(string, string, string) bool { return false })
ts := newWSServer(t, s)
diff --git a/internal/api/router.go b/internal/api/router.go
index af7cd8ca01..877332c48a 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -179,6 +179,7 @@ type Router struct {
stripeWebhookHandlers *StripeWebhookHandlers
patrolLifecycleMu sync.Mutex
startedPatrolOrgs map[string]bool
+ actionRecoveryMu sync.Mutex
aiAutoFixEndpoints extensions.AIAutoFixEndpoints
aiAlertAnalysisEndpoints extensions.AIAlertAnalysisEndpoints
@@ -646,6 +647,12 @@ func (r *Router) setupRoutes() {
newHostStorageCleanupActionExecutor(r.resourceHandlers, r.agentExecServer),
newHostUpdateActionExecutor(r.resourceHandlers, r.agentExecServer),
))
+ // Receipt-pending dispatch attempts can only reconcile while the
+ // owning agent is connected, so each agent (re)registration re-drives
+ // the durable-dispatch recovery pass that startup begins.
+ r.agentExecServer.SetAgentRegisteredNotifier(func(string) {
+ r.recoverExecutingActions("system:agent-reconnect-recovery")
+ })
}
if r.monitor != nil {
r.configureProxmoxGuestDockerDetection(r.monitor)
@@ -1335,6 +1342,9 @@ func (r *Router) StartBackgroundWorkers() {
r.startLifecycleWorker(func() {
r.backgroundUpdateChecker(r.lifecycleCtx)
})
+ r.startLifecycleWorker(func() {
+ r.recoverExecutingActions("system:restart-recovery")
+ })
if r.reportingHandlers != nil {
r.startLifecycleWorker(func() {
r.reportingHandlers.RunReportScheduleScheduler(r.lifecycleCtx)
@@ -1343,6 +1353,66 @@ func (r *Router) StartBackgroundWorkers() {
})
}
+// maxExecutingActionRecoveryBatch bounds one durable-dispatch recovery pass
+// per org. Recovery re-runs on every agent (re)registration, so a bounded
+// pass still converges when more actions are stuck than one batch covers.
+const maxExecutingActionRecoveryBatch = 100
+
+// recoverExecutingActions reconciles actions left in the executing state by a
+// server restart or a lost agent callback. Every org routes through
+// Service.RecoverExecutingActions: receipt-pending attempts reconcile
+// query-only against the durable agent operation receipt, a committed-but-
+// never-sent dispatch may be re-driven once, and nothing is blindly
+// re-executed. It runs at startup and again whenever an agent (re)registers,
+// because receipt reconciliation can only answer while the owning agent is
+// connected.
+func (r *Router) recoverExecutingActions(actor string) {
+ if r == nil || r.resourceHandlers == nil || mock.IsMockEnabled() {
+ return
+ }
+ // Serialize passes: an agent reconnect storm after a restart would
+ // otherwise run redundant overlapping passes over the same records.
+ r.actionRecoveryMu.Lock()
+ defer r.actionRecoveryMu.Unlock()
+ ctx := r.lifecycleCtx
+ if ctx == nil {
+ ctx = context.Background()
+ }
+ orgIDs := []string{"default"}
+ if r.multiTenant != nil {
+ if orgs, err := r.multiTenant.ListOrganizations(); err != nil {
+ log.Warn().Err(err).Msg("Executing-action recovery could not list organizations; recovering default org only")
+ } else {
+ orgIDs = orgIDs[:0]
+ for _, org := range orgs {
+ if org != nil {
+ orgIDs = append(orgIDs, org.ID)
+ }
+ }
+ }
+ }
+ lifecycle := r.resourceHandlers.ActionLifecycle()
+ for _, orgID := range orgIDs {
+ if ctx.Err() != nil {
+ return
+ }
+ recovered, err := lifecycle.RecoverExecutingActions(ctx, orgID, actor, maxExecutingActionRecoveryBatch)
+ if err != nil {
+ log.Warn().Err(err).Str("org_id", orgID).Str("actor", actor).Msg("Executing-action recovery pass failed")
+ continue
+ }
+ terminal := 0
+ for _, record := range recovered {
+ if record.State == unifiedresources.ActionStateCompleted || record.State == unifiedresources.ActionStateFailed {
+ terminal++
+ }
+ }
+ if terminal > 0 {
+ log.Info().Int("recovered", terminal).Int("examined", len(recovered)).Str("org_id", orgID).Str("actor", actor).Msg("Recovered executing actions from durable dispatch state")
+ }
+ }
+}
+
func (r *Router) startLifecycleWorker(worker func()) {
if r == nil || worker == nil {
return
diff --git a/internal/api/router_action_recovery_test.go b/internal/api/router_action_recovery_test.go
new file mode 100644
index 0000000000..f8a6ab9cb4
--- /dev/null
+++ b/internal/api/router_action_recovery_test.go
@@ -0,0 +1,128 @@
+package api
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+ "github.com/rcourtman/pulse-go-rewrite/internal/operationreceipt"
+ unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+)
+
+// callbackLossDockerExecutor simulates a server that dies (or loses the agent
+// connection) after the typed operation reaches the transport: the dispatch
+// is committed and bound, but the callback never lands. Binding and
+// reconciliation delegate to the real docker executor so recovery exercises
+// the production receipt path.
+type callbackLossDockerExecutor struct {
+ inner dockerContainerActionExecutor
+ executions int
+}
+
+func (e *callbackLossDockerExecutor) ExecuteAction(ctx context.Context, record unified.ActionAuditRecord) (*unified.ExecutionResult, error) {
+ e.executions++
+ return nil, errors.New("simulated callback loss after transport send")
+}
+
+func (e *callbackLossDockerExecutor) BindActionDispatch(ctx context.Context, record unified.ActionAuditRecord, attempt unified.ActionDispatchAttempt) (unified.ActionDispatchAttempt, error) {
+ return e.inner.BindActionDispatch(ctx, record, attempt)
+}
+
+func (e *callbackLossDockerExecutor) ReconcileActionDispatch(ctx context.Context, record unified.ActionAuditRecord, attempt unified.ActionDispatchAttempt) (*unified.ExecutionResult, unified.ActionDispatchReceipt, bool, error) {
+ return e.inner.ReconcileActionDispatch(ctx, record, attempt)
+}
+
+// TestRouterRecoverExecutingActionsReconcilesDurableReceipt pins the
+// production recovery pass shared by the startup lifecycle worker and the
+// agentexec agent-registered notifier: an action stuck in the executing state
+// with a receipt-pending dispatch attempt is completed query-only from the
+// agent's durable operation receipt, without a second dispatch.
+func TestRouterRecoverExecutingActionsReconcilesDurableReceipt(t *testing.T) {
+ now := time.Now().UTC()
+ resource := dockerContainerActionResource("app-container:api", "docker", "running", now)
+ startedAt := now.Add(-time.Minute)
+ resource.Docker.StartedAt = &startedAt
+ h := newActionTestResourceHandlers(t, &config.Config{DataPath: t.TempDir()})
+ h.SetStateProvider(resourceUnifiedSeedProvider{snapshot: models.StateSnapshot{LastUpdate: now}, resources: []unified.Resource{resource}})
+ agents := &fakeDockerActionAgentCommander{}
+ executor := &callbackLossDockerExecutor{inner: newDockerContainerActionExecutor(h, agents).(dockerContainerActionExecutor)}
+ h.SetActionExecutor(executor)
+
+ planRec := httptest.NewRecorder()
+ planReq := httptest.NewRequest(http.MethodPost, "/api/actions/plan", bytes.NewBufferString(`{
+ "requestId":"req-restart-recovery",
+ "resourceId":"app-container:api",
+ "capabilityName":"restart",
+ "reason":"exercise restart recovery"
+ }`))
+ h.HandlePlanAction(planRec, actionHandlerTestRequest(planReq, "[email protected]"))
+ if planRec.Code != http.StatusOK {
+ t.Fatalf("plan status=%d body=%s", planRec.Code, planRec.Body.String())
+ }
+ var plan unified.ActionPlan
+ if err := json.Unmarshal(planRec.Body.Bytes(), &plan); err != nil || plan.ActionID == "" {
+ t.Fatalf("plan decode err=%v plan=%#v", err, plan)
+ }
+
+ decisionRec := httptest.NewRecorder()
+ decisionReq := httptest.NewRequest(http.MethodPost, "/api/actions/"+plan.ActionID+"/decision", bytes.NewBufferString(`{"outcome":"approved","reason":"controlled recovery proof"}`))
+ decisionReq.SetPathValue("id", plan.ActionID)
+ h.HandleDecideAction(decisionRec, actionHandlerTestRequest(decisionReq, "[email protected]"))
+ if decisionRec.Code != http.StatusOK {
+ t.Fatalf("decision status=%d body=%s", decisionRec.Code, decisionRec.Body.String())
+ }
+
+ executionReq := httptest.NewRequest(http.MethodPost, "/api/actions/"+plan.ActionID+"/execute", bytes.NewBufferString(`{"reason":"controlled callback loss"}`))
+ executionReq.SetPathValue("id", plan.ActionID)
+ h.HandleExecuteAction(httptest.NewRecorder(), actionHandlerTestRequest(executionReq, "[email protected]"))
+
+ store, err := h.getStore("default")
+ if err != nil {
+ t.Fatal(err)
+ }
+ attempt, found, err := store.GetActionDispatchAttempt(plan.ActionID)
+ if err != nil || !found || attempt.State != unified.ActionDispatchReceiptPending {
+ t.Fatalf("pending attempt found=%v err=%v attempt=%#v", found, err, attempt)
+ }
+ if executor.executions != 1 {
+ t.Fatalf("executions before recovery = %d, want 1", executor.executions)
+ }
+
+ facts := agentexec.DockerContainerLifecycleResultPayload{
+ RequestID: attempt.ID, ActionID: attempt.ActionID, Operation: attempt.OperationKind, OperationVersion: attempt.OperationVersion, RequestDigest: attempt.RequestDigest, ContainerID: resource.Docker.ContainerID,
+ ExecutionPhase: agentexec.DockerContainerPhaseComplete, MutationStarted: true, MutationCompleted: true, ReadbackRan: true,
+ Before: agentexec.DockerContainerLifecycleSnapshot{ContainerID: resource.Docker.ContainerID, State: "running", Running: true, StartedAt: startedAt, ObservedAt: now.Add(-2 * time.Second)},
+ After: agentexec.DockerContainerLifecycleSnapshot{ContainerID: resource.Docker.ContainerID, State: "running", Running: true, StartedAt: now.Add(-time.Second), ObservedAt: now.Add(-time.Second)},
+ }
+ raw, err := json.Marshal(facts)
+ if err != nil {
+ t.Fatal(err)
+ }
+ identity := operationreceipt.Identity{AttemptID: attempt.ID, ActionID: attempt.ActionID, OperationKind: attempt.OperationKind, OperationVersion: attempt.OperationVersion, RequestDigest: attempt.RequestDigest, AgentID: attempt.AgentID}
+ agents.queryResult = operationreceipt.QueryResult{Version: operationreceipt.ProtocolVersion, Status: operationreceipt.QueryFoundTerminal, Record: &operationreceipt.Record{Identity: identity, State: operationreceipt.StateTerminal, AcceptedAt: now.Add(-4 * time.Second), StartedAt: now.Add(-3 * time.Second), TerminalAt: now, ResultKind: agentexec.DockerContainerLifecycleReceiptKind, ResultVersion: agentexec.DockerContainerLifecycleReceiptVersion, Result: raw}}
+
+ router := &Router{resourceHandlers: h}
+ router.recoverExecutingActions("system:restart-recovery")
+
+ audit, found, err := store.GetActionAudit(plan.ActionID)
+ if err != nil || !found || audit.State != unified.ActionStateCompleted {
+ t.Fatalf("recovered audit found=%v err=%v audit=%#v", found, err, audit)
+ }
+ if audit.Result == nil || audit.Result.ActionResultV2 == nil || audit.Result.ActionResultV2.Execution.Status != unified.ActionExecutionSucceeded {
+ t.Fatalf("recovered action truth=%#v", audit.Result)
+ }
+ if executor.executions != 1 {
+ t.Fatalf("executions after recovery = %d, want 1 (recovery must not redispatch)", executor.executions)
+ }
+ if len(agents.queries) != 1 {
+ t.Fatalf("receipt queries = %d, want exactly 1", len(agents.queries))
+ }
+}