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.

Add governed Proxmox guest lifecycle actions

rcourtman11e034799154
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 18ed120d12..e5844a00e8 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -240,6 +240,14 @@ mark its vetted container lifecycle dispatch as a trusted agent command after
the API action has entered execution; lifecycle surfaces still consume only the
resource payload, action readiness, and action-audit result rather than issuing
or approving command-agent grants themselves.
+Proxmox VM and LXC lifecycle affordances follow the same adjacent boundary:
+lifecycle and fleet surfaces may consume backend-advertised `start`,
+`shutdown`, `reboot`, and `stop` capabilities and typed `actionReadiness`, but
+the only execution path is the API-owned action executor that resolves a
+connected Proxmox node command agent and records action audit plus verification.
+Lifecycle surfaces must not run `qm` / `pct`, SSH to a node, call Proxmox
+mutation APIs, or substitute a guest-local agent to perform VM/LXC lifecycle
+control.
Disconnected command-agent state is also API-owned readiness: lifecycle
surfaces may reflect missing backend-advertised capabilities, but must not
reconnect, substitute, or directly address an agent to make a stale container
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 554f6d3c4b..b0783791d9 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -33,6 +33,9 @@ product API routes free of maintainer commercial analytics.
3. `internal/api/alerts.go`
4. `internal/api/activity_audit_handlers.go`
5. `internal/api/actions.go`
+5a. `internal/api/action_executor.go`
+5b. `internal/api/docker_container_action_executor.go`
+5c. `internal/api/proxmox_guest_action_executor.go`
6. `internal/actionplanner/planner.go`
7. `pkg/pulsecli/api_client.go`
8. `pkg/pulsecli/actions.go`
@@ -1021,6 +1024,20 @@ the canonical monitored-system blocked payload.
commands as trusted agent commands; the host-agent hard-block policy still
applies, and the action audit remains the approval and lifecycle source of
truth.
+ Proxmox QEMU VM and LXC lifecycle execution is part of that same API-owned
+ action contract. Proxmox guest resources may expose only conservative
+ lifecycle operations (`start`, `shutdown`, `reboot`, `stop`) and execution
+ must route through the registered action executor, not through platform
+ tables, Assistant tool shortcuts, direct Proxmox API mutation, SSH, or
+ guest-local agents. The executor must resolve a connected Proxmox node
+ command agent from the unified resource's linked node agent first, then the
+ canonical Proxmox node hostname, dispatch only vetted `qm` / `pct`
+ lifecycle commands as trusted action-owned agent commands after the API
+ action enters execution, and verify the resulting Proxmox state with
+ `qm status` / `pct status` before recording success. Templates, locked
+ guests, stale Proxmox inventory, incomplete VMID/node metadata, unsupported
+ handlers, and disconnected node command agents must fail closed through the
+ same readiness and audit model.
Resource payloads may expose the same executor-owned unavailable state as
`actionReadiness[]` entries with stable `name`, `available`, `reasonCode`,
and `reason` fields so browser and agent clients can explain disabled
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
index 8cc47e8e35..f98486667f 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -283,6 +283,11 @@ regression protection.
while per-action resource refresh, policy validation, agent command dispatch,
polling verification, and audit completion must occur inside the route-local
execute handler path.
+ Proxmox VM/LXC lifecycle execution follows that same routed-executor budget:
+ router setup may register the Proxmox executor alongside Docker / Podman,
+ but it must not resolve guests, probe node agents, call `qm` / `pct`, poll
+ verification state, or refresh inventory outside the route-local action
+ plan/execute path.
Retiring self-hosted trial acquisition follows that same rule: removing
`/auth/trial-activate` and `POST /api/license/trial/start` from public-path
and CSRF inventories must stay as constant-time route-table absence rather
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index b65487d2b0..b429215616 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -604,6 +604,13 @@ handoff: the executor may use agent command execution only after scope,
approval/policy, stale-plan, operator-lock, source-freshness, and runtime
posture checks pass, and it must record redacted audit and verification facts
instead of exposing raw command text through monitoring-readable surfaces.
+Proxmox VM/LXC lifecycle execution is governed by the same privileged action
+handoff: `start`, `shutdown`, `reboot`, and `stop` may use a Proxmox node
+command agent only after the API action scope, approval/policy, stale-plan,
+operator-lock, fresh resource capability, and connected-agent checks pass. Raw
+`qm` / `pct` command text and command output must remain action-executor/audit
+implementation detail, with monitoring-readable surfaces receiving only
+redacted result, verification, and readiness facts.
That same token-scope boundary now also governs Pulse Mobile relay runtime
credentials: `internal/api/security_tokens.go` must mint only the dedicated
backend-owned `relay:mobile:access` scope for new mobile relay tokens, and the
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index ae44c044bf..a8d8ba9e50 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -423,6 +423,12 @@ recovery scope, or a storage/recovery-owned secret source.
for host-side Docker-in-LXC collection must not be reinterpreted as backup
freshness, restore coverage, storage protection evidence, or remediation
authority for the LXC guest.
+ Adjacent Proxmox VM/LXC lifecycle actions may also pass through the shared
+ API action executor and Proxmox node command-agent path, but storage and
+ recovery may consume their audit and refreshed resource state only as
+ operator context. Start, shutdown, reboot, or hard stop capability must not
+ be reinterpreted as backup freshness, restore safety, recovery entitlement,
+ or storage-local remediation authority.
Proxmox auto-registration dedupe for cluster-member endpoints is likewise
adjacent API/lifecycle continuity: treating a non-primary cluster endpoint
as already registered prevents accidental shared-token rotation, but it does
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index 297ef724fb..d88ecf86d1 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -267,6 +267,13 @@ dense platform table rendering must use `PlatformTableRelativeTimeValue` /
`formatPlatformTableRelativeTimeValue` for relative labels, compact defaults,
invalid/empty markers, and tabular styling instead of importing
`formatRelativeTime` or declaring local timestamp-age helpers in table files.
+Duration and interval cells keep the same split: unified-resource or
+source-specific consumers own which elapsed duration, human fallback, or poll
+interval field is meaningful, while dense platform table rendering must use
+`PlatformTableDurationValue` / `formatPlatformTableDurationValue` for
+seconds/minutes/hours labels, fallback text, invalid/empty markers, and
+tabular styling instead of declaring local seconds/minutes helpers in table
+files.
Optional numeric table cells follow the same split: unified-resource consumers
own which count or replica field is meaningful, whether the domain should
zero-default an absent scheduler/service/inventory count, whether a
@@ -531,6 +538,17 @@ container inventory table.
`command_agent_disconnected`, and operator-safe copy. Frontend consumers may
use that field to explain disabled controls, while `capabilities` remains
the executable action set.
+ Proxmox VM and LXC lifecycle actions are also part of that governed
+ resource contract. `resourceFromVM` and `resourceFromContainer` may advertise
+ `start` only for stopped guests and `shutdown`, `reboot`, and `stop` only
+ for running guests, and must fail closed for templates, locked guests, and
+ unknown transition states. The API action executor consumes those
+ capabilities through `/api/actions/*`, resolves the Proxmox node command
+ agent from the unified resource's linked node context, and records
+ `actionReadiness` when that command path is not currently connected.
+ Unified-resource consumers must not infer Proxmox lifecycle affordances from
+ table row status alone or issue direct `qm` / `pct`, SSH, provider API, or
+ guest-agent calls outside the governed action contract.
TrueNAS app inventory enters the model as native `TrueNASData.App`
metadata on canonical `app-container` resources. The facet is sourced from
the TrueNAS API app inventory (`app.query` plus active workload/stat
@@ -1349,6 +1367,13 @@ lifecycle controls from runtime-shaped metadata alone. After a governed request
completes, the owning surface may ask its existing `useUnifiedResources` query
to refetch the resource snapshot, but refresh is not an alternate execution,
verification, or provider-control path.
+Proxmox VM and LXC lifecycle affordances follow the same resource-owned rule:
+the backend advertises only status-appropriate `start`, `shutdown`, `reboot`,
+and `stop` capabilities for non-template, unlocked Proxmox guests, filters them
+when the owning node command agent is disconnected, and records disabled-state
+context in `actionReadiness`. Proxmox platform pages and detail drawers may
+consume those fields, but they must not treat row status, VMID, node name, or
+guest metadata as separate permission to run `qm` / `pct` or provider calls.
`InfrastructureSummary.tsx` and `infrastructureSummaryModel.ts` now surface
`degraded` and `alerting` resource counts alongside the existing `online` and
diff --git a/internal/api/action_executor.go b/internal/api/action_executor.go
new file mode 100644
index 0000000000..574400c63f
--- /dev/null
+++ b/internal/api/action_executor.go
@@ -0,0 +1,124 @@
+package api
+
+import (
+ "context"
+ "fmt"
+ "strings"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
+ unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+)
+
+type actionAgentCommander interface {
+ ExecuteCommand(ctx context.Context, agentID string, cmd agentexec.ExecuteCommandPayload) (*agentexec.CommandResultPayload, error)
+ GetAgentForHost(hostname string) (string, bool)
+ IsAgentConnected(agentID string) bool
+}
+
+type actionHandlerProvider interface {
+ ActionHandlerNames() []string
+}
+
+type routedActionExecutor struct {
+ resources *ResourceHandlers
+ byHandler map[string]ActionExecutor
+}
+
+func newRoutedActionExecutor(resources *ResourceHandlers, executors ...ActionExecutor) ActionExecutor {
+ if resources == nil {
+ return nil
+ }
+ routed := routedActionExecutor{
+ resources: resources,
+ byHandler: map[string]ActionExecutor{},
+ }
+ for _, executor := range executors {
+ if executor == nil {
+ continue
+ }
+ provider, ok := executor.(actionHandlerProvider)
+ if !ok {
+ continue
+ }
+ for _, handler := range provider.ActionHandlerNames() {
+ handler = strings.TrimSpace(handler)
+ if handler != "" {
+ routed.byHandler[handler] = executor
+ }
+ }
+ }
+ if len(routed.byHandler) == 0 {
+ return nil
+ }
+ return routed
+}
+
+func (e routedActionExecutor) ExecuteAction(ctx context.Context, record unified.ActionAuditRecord) (*unified.ExecutionResult, error) {
+ normalized, err := unified.NormalizeActionAuditRecord(record)
+ if err != nil {
+ return nil, err
+ }
+ executor, err := e.executorForAction(ctx, normalized.Request)
+ if err != nil {
+ return nil, err
+ }
+ return executor.ExecuteAction(ctx, normalized)
+}
+
+func (e routedActionExecutor) CheckActionAvailable(ctx context.Context, req unified.ActionRequest, resource unified.Resource) unified.ResourceActionReadiness {
+ capability, ok := resourceCapabilityByName(resource.Capabilities, req.CapabilityName)
+ if !ok || strings.TrimSpace(capability.InternalHandler) == "" {
+ return unified.ResourceActionReadiness{}
+ }
+ executor := e.byHandler[strings.TrimSpace(capability.InternalHandler)]
+ if executor == nil {
+ return unified.ResourceActionReadiness{
+ Name: strings.TrimSpace(req.CapabilityName),
+ Available: false,
+ ReasonCode: "unsupported_handler",
+ Reason: "This action is not routed through a supported executor.",
+ }
+ }
+ checker, ok := executor.(ActionAvailabilityChecker)
+ if !ok {
+ return unified.ResourceActionReadiness{}
+ }
+ return checker.CheckActionAvailable(ctx, req, resource)
+}
+
+func (e routedActionExecutor) executorForAction(ctx context.Context, req unified.ActionRequest) (ActionExecutor, error) {
+ if e.resources == nil {
+ return nil, fmt.Errorf("resource handler unavailable")
+ }
+ registry, err := e.resources.buildRegistry(GetOrgID(ctx))
+ if err != nil {
+ return nil, err
+ }
+ resource, ok := registry.Get(req.ResourceID)
+ if !ok || resource == nil {
+ return nil, fmt.Errorf("resource %q is no longer present", req.ResourceID)
+ }
+ capability, ok := resourceCapabilityByName(resource.Capabilities, req.CapabilityName)
+ if !ok {
+ return nil, fmt.Errorf("resource %q does not currently advertise %s capability", req.ResourceID, req.CapabilityName)
+ }
+ handler := strings.TrimSpace(capability.InternalHandler)
+ if handler == "" {
+ return nil, fmt.Errorf("resource %q capability %s has no executor handler", req.ResourceID, req.CapabilityName)
+ }
+ executor := e.byHandler[handler]
+ if executor == nil {
+ return nil, fmt.Errorf("resource %q capability %s is routed through unsupported handler %q", req.ResourceID, req.CapabilityName, handler)
+ }
+ return executor, nil
+}
+
+func resourceCapabilityByName(capabilities []unified.ResourceCapability, name string) (unified.ResourceCapability, bool) {
+ name = strings.TrimSpace(name)
+ for _, capability := range capabilities {
+ if strings.TrimSpace(capability.Name) == name {
+ return capability, true
+ }
+ }
+ return unified.ResourceCapability{}, false
+}
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 0163bfaec4..e096df5538 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -15193,8 +15193,12 @@ func TestContract_DockerLifecycleActionsResolveCommandAgentAndDispatchTrusted(t
t.Fatalf("read docker_container_action_executor.go: %v", err)
}
src := string(source)
+ sharedSource, err := os.ReadFile("action_executor.go")
+ if err != nil {
+ t.Fatalf("read action_executor.go: %v", err)
+ }
+ sharedSrc := string(sharedSource)
for _, snippet := range []string{
- "GetAgentForHost(hostname string) (string, bool)",
"func (e dockerContainerActionExecutor) connectedDockerCommandAgentID(resource unified.Resource) (string, error)",
"resource.Docker.AgentID",
"e.agents.GetAgentForHost(strings.TrimSpace(resource.Docker.Hostname))",
@@ -15204,12 +15208,55 @@ func TestContract_DockerLifecycleActionsResolveCommandAgentAndDispatchTrusted(t
t.Fatalf("docker lifecycle executor must pin command-agent/trusted dispatch snippet %q", snippet)
}
}
+ if !strings.Contains(sharedSrc, "GetAgentForHost(hostname string) (string, bool)") {
+ t.Fatal("shared action command interface must keep hostname-based command-agent resolution available")
+ }
if strings.Index(src, "if agentID := strings.TrimSpace(resource.Docker.AgentID)") >
strings.Index(src, "e.agents.GetAgentForHost(strings.TrimSpace(resource.Docker.Hostname))") {
t.Fatal("docker lifecycle executor must try the Docker reporting agent id before falling back to hostname resolution")
}
}
+func TestContract_ProxmoxLifecycleActionsResolveNodeCommandAgentAndVerifyState(t *testing.T) {
+ source, err := os.ReadFile("proxmox_guest_action_executor.go")
+ if err != nil {
+ t.Fatalf("read proxmox_guest_action_executor.go: %v", err)
+ }
+ src := string(source)
+ for _, snippet := range []string{
+ "func (e proxmoxGuestActionExecutor) connectedProxmoxNodeCommandAgentID(resource unified.Resource) (string, error)",
+ "resource.Proxmox.LinkedAgentID",
+ "e.agents.GetAgentForHost(strings.TrimSpace(resource.Proxmox.NodeName))",
+ "Trusted: true",
+ "func (e proxmoxGuestActionExecutor) verifyProxmoxGuestState(",
+ "proxmoxGuestStatusCommand(kind, vmid)",
+ "parseProxmoxGuestStatus(lastOutput) == expected",
+ } {
+ if !strings.Contains(src, snippet) {
+ t.Fatalf("proxmox lifecycle executor must pin command-agent/trusted verification snippet %q", snippet)
+ }
+ }
+ if strings.Index(src, "if agentID := strings.TrimSpace(resource.Proxmox.LinkedAgentID)") >
+ strings.Index(src, "e.agents.GetAgentForHost(strings.TrimSpace(resource.Proxmox.NodeName))") {
+ t.Fatal("proxmox lifecycle executor must try the linked Proxmox node agent before falling back to node hostname resolution")
+ }
+
+ router, err := os.ReadFile("router.go")
+ if err != nil {
+ t.Fatalf("read router.go: %v", err)
+ }
+ routerSrc := string(router)
+ for _, snippet := range []string{
+ "newRoutedActionExecutor(",
+ "newDockerContainerActionExecutor(r.resourceHandlers, r.agentExecServer)",
+ "newProxmoxGuestActionExecutor(r.resourceHandlers, r.agentExecServer)",
+ } {
+ if !strings.Contains(routerSrc, snippet) {
+ t.Fatalf("router must register Docker and Proxmox action executors through routed action executor; missing %q", snippet)
+ }
+ }
+}
+
// TestContract_AgentCapabilitiesManifestIsPublic pins the auth
// contract for the discovery surface: the manifest must be in the
// router's publicPaths list so it serves without a token. The
diff --git a/internal/api/docker_container_action_executor.go b/internal/api/docker_container_action_executor.go
index 3afbca2428..08d206681b 100644
--- a/internal/api/docker_container_action_executor.go
+++ b/internal/api/docker_container_action_executor.go
@@ -13,24 +13,22 @@ import (
const dockerContainerLifecycleHandler = "docker.container.lifecycle"
-type dockerActionAgentCommander interface {
- ExecuteCommand(ctx context.Context, agentID string, cmd agentexec.ExecuteCommandPayload) (*agentexec.CommandResultPayload, error)
- GetAgentForHost(hostname string) (string, bool)
- IsAgentConnected(agentID string) bool
-}
-
type dockerContainerActionExecutor struct {
resources *ResourceHandlers
- agents dockerActionAgentCommander
+ agents actionAgentCommander
}
-func newDockerContainerActionExecutor(resources *ResourceHandlers, agents dockerActionAgentCommander) ActionExecutor {
+func newDockerContainerActionExecutor(resources *ResourceHandlers, agents actionAgentCommander) ActionExecutor {
if resources == nil || agents == nil {
return nil
}
return dockerContainerActionExecutor{resources: resources, agents: agents}
}
+func (e dockerContainerActionExecutor) ActionHandlerNames() []string {
+ return []string{dockerContainerLifecycleHandler}
+}
+
func (e dockerContainerActionExecutor) ExecuteAction(ctx context.Context, record unified.ActionAuditRecord) (*unified.ExecutionResult, error) {
record, err := unified.NormalizeActionAuditRecord(record)
if err != nil {
diff --git a/internal/api/proxmox_guest_action_executor.go b/internal/api/proxmox_guest_action_executor.go
new file mode 100644
index 0000000000..fe8108669a
--- /dev/null
+++ b/internal/api/proxmox_guest_action_executor.go
@@ -0,0 +1,373 @@
+package api
+
+import (
+ "context"
+ "fmt"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
+ unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+)
+
+const (
+ proxmoxVMLifecycleHandler = "proxmox.vm.lifecycle"
+ proxmoxCTLifecycleHandler = "proxmox.ct.lifecycle"
+)
+
+type proxmoxGuestKind string
+
+const (
+ proxmoxGuestVM proxmoxGuestKind = "vm"
+ proxmoxGuestCT proxmoxGuestKind = "ct"
+)
+
+type proxmoxGuestActionExecutor struct {
+ resources *ResourceHandlers
+ agents actionAgentCommander
+}
+
+func newProxmoxGuestActionExecutor(resources *ResourceHandlers, agents actionAgentCommander) ActionExecutor {
+ if resources == nil || agents == nil {
+ return nil
+ }
+ return proxmoxGuestActionExecutor{resources: resources, agents: agents}
+}
+
+func (e proxmoxGuestActionExecutor) ActionHandlerNames() []string {
+ return []string{proxmoxVMLifecycleHandler, proxmoxCTLifecycleHandler}
+}
+
+func (e proxmoxGuestActionExecutor) ExecuteAction(ctx context.Context, record unified.ActionAuditRecord) (*unified.ExecutionResult, error) {
+ record, err := unified.NormalizeActionAuditRecord(record)
+ if err != nil {
+ return nil, err
+ }
+ operation := strings.TrimSpace(record.Request.CapabilityName)
+ if !isProxmoxGuestLifecycleOperation(operation) {
+ return nil, fmt.Errorf("unsupported proxmox guest lifecycle capability %q", operation)
+ }
+
+ resource, kind, err := e.currentProxmoxGuestResource(ctx, record.Request.ResourceID, operation)
+ if err != nil {
+ return nil, err
+ }
+ vmid := resource.Proxmox.VMID
+ agentID, err := e.connectedProxmoxNodeCommandAgentID(resource)
+ if err != nil {
+ return nil, err
+ }
+
+ command := proxmoxGuestLifecycleCommand(kind, operation, vmid)
+ result, err := e.agents.ExecuteCommand(ctx, agentID, agentexec.ExecuteCommandPayload{
+ RequestID: record.ID,
+ Command: command,
+ ApprovalID: record.ID,
+ TargetType: "agent",
+ Timeout: proxmoxGuestLifecycleTimeout(operation),
+ Trusted: true,
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ output := redactActionOutput(commandOutput(result))
+ execution := &unified.ExecutionResult{
+ Success: result.ExitCode == 0,
+ Output: output,
+ }
+ if result.ExitCode != 0 {
+ execution.ErrorMessage = strings.TrimSpace(firstNonEmpty(result.Error, output, fmt.Sprintf("proxmox guest %s exited with status %d", operation, result.ExitCode)))
+ return execution, nil
+ }
+
+ verification := e.verifyProxmoxGuestState(ctx, agentID, record.ID, kind, vmid, operation)
+ execution.Verification = verification
+ if verification != nil && verification.Ran && !verification.Success {
+ execution.Success = false
+ execution.ErrorMessage = "proxmox guest lifecycle action completed but verification did not confirm the expected state"
+ }
+ return execution, nil
+}
+
+func (e proxmoxGuestActionExecutor) CheckActionAvailable(ctx context.Context, req unified.ActionRequest, resource unified.Resource) unified.ResourceActionReadiness {
+ operation := strings.TrimSpace(req.CapabilityName)
+ if _, ok := findProxmoxLifecycleCapability(resource.Capabilities, operation); !ok {
+ return unified.ResourceActionReadiness{}
+ }
+ readiness := unified.ResourceActionReadiness{Name: operation, Available: true}
+ if e.agents == nil {
+ return unavailableProxmoxActionReadiness(operation, "command_agent_unavailable", "Proxmox command execution is not available.")
+ }
+ if _, _, err := e.executableProxmoxGuestResource(resource, operation); err != nil {
+ return unavailableProxmoxActionReadiness(operation, proxmoxActionUnavailableReasonCode(err), proxmoxActionUnavailableReason(err))
+ }
+ if _, err := e.connectedProxmoxNodeCommandAgentID(resource); err != nil {
+ return unavailableProxmoxActionReadiness(operation, "command_agent_disconnected", "Proxmox node command agent is not connected.")
+ }
+ return readiness
+}
+
+func (e proxmoxGuestActionExecutor) currentProxmoxGuestResource(ctx context.Context, resourceID, operation string) (unified.Resource, proxmoxGuestKind, error) {
+ if e.resources == nil {
+ return unified.Resource{}, "", fmt.Errorf("resource handler unavailable")
+ }
+ registry, err := e.resources.buildRegistry(GetOrgID(ctx))
+ if err != nil {
+ return unified.Resource{}, "", err
+ }
+ resource, ok := registry.Get(resourceID)
+ if !ok || resource == nil {
+ return unified.Resource{}, "", fmt.Errorf("resource %q is no longer present", resourceID)
+ }
+ return e.executableProxmoxGuestResource(*resource, operation)
+}
+
+func (e proxmoxGuestActionExecutor) executableProxmoxGuestResource(resource unified.Resource, operation string) (unified.Resource, proxmoxGuestKind, error) {
+ kind, handler, err := proxmoxGuestKindAndHandler(resource)
+ if err != nil {
+ return unified.Resource{}, "", err
+ }
+ if resource.Proxmox == nil {
+ return unified.Resource{}, "", fmt.Errorf("proxmox resource metadata missing")
+ }
+ if resource.Proxmox.VMID <= 0 {
+ return unified.Resource{}, "", fmt.Errorf("proxmox guest resource %q has no executable vmid", resource.ID)
+ }
+ if strings.TrimSpace(resource.Proxmox.NodeName) == "" {
+ return unified.Resource{}, "", fmt.Errorf("proxmox guest resource %q has no owning node", resource.ID)
+ }
+ if resource.Proxmox.Template {
+ return unified.Resource{}, "", fmt.Errorf("proxmox guest resource %q is a template", resource.ID)
+ }
+ if lock := strings.TrimSpace(resource.Proxmox.Lock); lock != "" {
+ return unified.Resource{}, "", fmt.Errorf("proxmox guest resource %q is locked: %s", resource.ID, lock)
+ }
+ if status := resource.SourceStatus[unified.SourceProxmox]; strings.EqualFold(strings.TrimSpace(status.Status), "stale") || strings.EqualFold(strings.TrimSpace(status.Status), "offline") || strings.EqualFold(strings.TrimSpace(status.Status), "missing") {
+ return unified.Resource{}, "", fmt.Errorf("proxmox inventory for resource %q is %s", resource.ID, status.Status)
+ }
+ capability, ok := findProxmoxLifecycleCapability(resource.Capabilities, operation)
+ if !ok {
+ return unified.Resource{}, "", fmt.Errorf("resource %q does not currently advertise %s capability", resource.ID, operation)
+ }
+ if capability.InternalHandler != handler {
+ return unified.Resource{}, "", fmt.Errorf("resource %q advertises %s through unsupported handler %q", resource.ID, operation, capability.InternalHandler)
+ }
+ return resource, kind, nil
+}
+
+func (e proxmoxGuestActionExecutor) connectedProxmoxNodeCommandAgentID(resource unified.Resource) (string, error) {
+ if e.agents == nil {
+ return "", fmt.Errorf("proxmox node command agent is not connected")
+ }
+ if resource.Proxmox == nil {
+ return "", fmt.Errorf("proxmox resource metadata missing")
+ }
+ if agentID := strings.TrimSpace(resource.Proxmox.LinkedAgentID); agentID != "" && e.agents.IsAgentConnected(agentID) {
+ return agentID, nil
+ }
+ if agentID, ok := e.agents.GetAgentForHost(strings.TrimSpace(resource.Proxmox.NodeName)); ok {
+ agentID = strings.TrimSpace(agentID)
+ if agentID != "" && e.agents.IsAgentConnected(agentID) {
+ return agentID, nil
+ }
+ }
+ return "", fmt.Errorf("proxmox node command agent is not connected")
+}
+
+func proxmoxGuestKindAndHandler(resource unified.Resource) (proxmoxGuestKind, string, error) {
+ switch resource.Type {
+ case unified.ResourceTypeVM:
+ return proxmoxGuestVM, proxmoxVMLifecycleHandler, nil
+ case unified.ResourceTypeSystemContainer:
+ return proxmoxGuestCT, proxmoxCTLifecycleHandler, nil
+ default:
+ return "", "", fmt.Errorf("resource %q is not a Proxmox VM or LXC", resource.ID)
+ }
+}
+
+func unavailableProxmoxActionReadiness(operation, reasonCode, reason string) unified.ResourceActionReadiness {
+ return unified.ResourceActionReadiness{
+ Name: strings.TrimSpace(operation),
+ Available: false,
+ ReasonCode: strings.TrimSpace(reasonCode),
+ Reason: strings.TrimSpace(reason),
+ }
+}
+
+func proxmoxActionUnavailableReasonCode(err error) string {
+ if err == nil {
+ return "unavailable"
+ }
+ message := strings.ToLower(err.Error())
+ switch {
+ case strings.Contains(message, "not a proxmox vm or lxc"):
+ return "unsupported_resource"
+ case strings.Contains(message, "inventory") && (strings.Contains(message, "stale") || strings.Contains(message, "offline") || strings.Contains(message, "missing")):
+ return "stale_inventory"
+ case strings.Contains(message, "template"):
+ return "template"
+ case strings.Contains(message, "locked"):
+ return "guest_locked"
+ case strings.Contains(message, "does not currently advertise"):
+ return "capability_unavailable"
+ case strings.Contains(message, "unsupported handler"):
+ return "unsupported_handler"
+ case strings.Contains(message, "vmid") || strings.Contains(message, "owning node"):
+ return "incomplete_metadata"
+ default:
+ return "unavailable"
+ }
+}
+
+func proxmoxActionUnavailableReason(err error) string {
+ switch proxmoxActionUnavailableReasonCode(err) {
+ case "unsupported_resource":
+ return "Resource is not a Proxmox VM or LXC."
+ case "stale_inventory":
+ return "Proxmox inventory is not fresh enough to run lifecycle actions."
+ case "template":
+ return "Proxmox templates cannot run lifecycle actions."
+ case "guest_locked":
+ return "Proxmox reports this guest is locked."
+ case "capability_unavailable":
+ return "Pulse does not currently advertise a fresh Proxmox lifecycle capability for this guest."
+ case "unsupported_handler":
+ return "This Proxmox action is not routed through the supported lifecycle executor."
+ case "incomplete_metadata":
+ return "Proxmox guest metadata is missing the VMID or owning node needed for command execution."
+ default:
+ return "Proxmox lifecycle action is not currently available."
+ }
+}
+
+func findProxmoxLifecycleCapability(capabilities []unified.ResourceCapability, operation string) (unified.ResourceCapability, bool) {
+ operation = strings.TrimSpace(operation)
+ for _, capability := range capabilities {
+ if strings.TrimSpace(capability.Name) == operation && isProxmoxLifecycleHandler(capability.InternalHandler) {
+ return capability, true
+ }
+ }
+ return unified.ResourceCapability{}, false
+}
+
+func isProxmoxLifecycleHandler(handler string) bool {
+ switch strings.TrimSpace(handler) {
+ case proxmoxVMLifecycleHandler, proxmoxCTLifecycleHandler:
+ return true
+ default:
+ return false
+ }
+}
+
+func isProxmoxGuestLifecycleOperation(operation string) bool {
+ switch strings.TrimSpace(operation) {
+ case "start", "shutdown", "reboot", "stop":
+ return true
+ default:
+ return false
+ }
+}
+
+func proxmoxGuestLifecycleCommand(kind proxmoxGuestKind, operation string, vmid int) string {
+ tool := "qm"
+ if kind == proxmoxGuestCT {
+ tool = "pct"
+ }
+ return strings.Join([]string{tool, strings.TrimSpace(operation), strconv.Itoa(vmid)}, " ")
+}
+
+func proxmoxGuestStatusCommand(kind proxmoxGuestKind, vmid int) string {
+ tool := "qm"
+ if kind == proxmoxGuestCT {
+ tool = "pct"
+ }
+ return strings.Join([]string{tool, "status", strconv.Itoa(vmid)}, " ")
+}
+
+func proxmoxGuestLifecycleTimeout(operation string) int {
+ switch strings.TrimSpace(operation) {
+ case "shutdown", "reboot":
+ return 180
+ default:
+ return 120
+ }
+}
+
+func (e proxmoxGuestActionExecutor) verifyProxmoxGuestState(ctx context.Context, agentID, actionID string, kind proxmoxGuestKind, vmid int, operation string) *unified.ActionVerificationResult {
+ expected := proxmoxExpectedGuestStatus(operation)
+ if expected == "" {
+ return &unified.ActionVerificationResult{Ran: false}
+ }
+ command := proxmoxGuestStatusCommand(kind, vmid)
+
+ var lastOutput string
+ for attempt := 0; attempt < 5; attempt++ {
+ if attempt > 0 {
+ timer := time.NewTimer(1 * time.Second)
+ select {
+ case <-ctx.Done():
+ timer.Stop()
+ return &unified.ActionVerificationResult{Ran: false}
+ case <-timer.C:
+ }
+ }
+
+ result, err := e.agents.ExecuteCommand(ctx, agentID, agentexec.ExecuteCommandPayload{
+ RequestID: fmt.Sprintf("%s-verify-%d", actionID, attempt+1),
+ Command: command,
+ ApprovalID: actionID,
+ TargetType: "agent",
+ Timeout: 30,
+ Trusted: true,
+ })
+ if err != nil {
+ return &unified.ActionVerificationResult{Ran: false}
+ }
+ lastOutput = redactActionOutput(commandOutput(result))
+ if result.ExitCode == 0 && parseProxmoxGuestStatus(lastOutput) == expected {
+ return &unified.ActionVerificationResult{
+ Ran: true,
+ Command: command,
+ Output: lastOutput,
+ Success: true,
+ RanAt: time.Now().UTC(),
+ }
+ }
+ }
+
+ return &unified.ActionVerificationResult{
+ Ran: true,
+ Command: command,
+ Output: lastOutput,
+ Success: false,
+ RanAt: time.Now().UTC(),
+ Note: "expected status " + expected,
+ }
+}
+
+func proxmoxExpectedGuestStatus(operation string) string {
+ switch strings.TrimSpace(operation) {
+ case "start", "reboot":
+ return "running"
+ case "shutdown", "stop":
+ return "stopped"
+ default:
+ return ""
+ }
+}
+
+func parseProxmoxGuestStatus(output string) string {
+ fields := strings.Fields(strings.ToLower(strings.TrimSpace(output)))
+ for i, field := range fields {
+ field = strings.TrimSuffix(field, ":")
+ if field == "status" && i+1 < len(fields) {
+ return strings.Trim(strings.TrimSuffix(fields[i+1], ":"), " \t\r\n")
+ }
+ if field == "running" || field == "stopped" {
+ return field
+ }
+ }
+ return ""
+}
diff --git a/internal/api/proxmox_guest_action_executor_test.go b/internal/api/proxmox_guest_action_executor_test.go
new file mode 100644
index 0000000000..8d4c16b871
--- /dev/null
+++ b/internal/api/proxmox_guest_action_executor_test.go
@@ -0,0 +1,360 @@
+package api
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "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"
+ unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+)
+
+func TestProxmoxGuestActionExecutorDispatchesVMShutdownAndVerification(t *testing.T) {
+ now := time.Now().UTC()
+ h := NewResourceHandlers(&config.Config{DataPath: t.TempDir()})
+ h.SetStateProvider(resourceUnifiedSeedProvider{
+ snapshot: models.StateSnapshot{LastUpdate: now},
+ resources: []unified.Resource{
+ proxmoxGuestActionResource("vm:160", unified.ResourceTypeVM, "running", now),
+ },
+ })
+ agents := &fakeDockerActionAgentCommander{results: []*agentexec.CommandResultPayload{
+ {RequestID: "act_vm", Success: true, ExitCode: 0, Stdout: "shutdown requested"},
+ {RequestID: "act_vm-verify-1", Success: true, ExitCode: 0, Stdout: "status: stopped"},
+ }}
+ executor := newProxmoxGuestActionExecutor(h, agents)
+
+ result, err := executor.ExecuteAction(context.Background(), proxmoxGuestActionRecord("act_vm", "vm:160", "shutdown"))
+ if err != nil {
+ t.Fatalf("ExecuteAction: %v", err)
+ }
+ if result == nil || !result.Success || result.Verification == nil || !result.Verification.Success {
+ t.Fatalf("result = %#v, want successful execution and verification", result)
+ }
+ if len(agents.calls) != 2 {
+ t.Fatalf("agent calls = %d, want dispatch and verification", len(agents.calls))
+ }
+ if got := agents.calls[0].Command; got != "qm shutdown 160" {
+ t.Fatalf("dispatch command = %q", got)
+ }
+ if agents.calls[0].ApprovalID != "act_vm" || !agents.calls[0].Trusted || agents.calls[0].Timeout != 180 {
+ t.Fatalf("dispatch approval/trust/timeout = %q/%v/%d", agents.calls[0].ApprovalID, agents.calls[0].Trusted, agents.calls[0].Timeout)
+ }
+ if got := agents.calls[1].Command; got != "qm status 160" {
+ t.Fatalf("verification command = %q", got)
+ }
+ for _, agentID := range agents.callAgents {
+ if agentID != "node-agent-1" {
+ t.Fatalf("called agent %q, want node-agent-1; all calls %#v", agentID, agents.callAgents)
+ }
+ }
+}
+
+func TestProxmoxGuestActionExecutorDispatchesLXCStartAndVerification(t *testing.T) {
+ now := time.Now().UTC()
+ h := NewResourceHandlers(&config.Config{DataPath: t.TempDir()})
+ h.SetStateProvider(resourceUnifiedSeedProvider{
+ snapshot: models.StateSnapshot{LastUpdate: now},
+ resources: []unified.Resource{
+ proxmoxGuestActionResource("system-container:101", unified.ResourceTypeSystemContainer, "stopped", now),
+ },
+ })
+ agents := &fakeDockerActionAgentCommander{results: []*agentexec.CommandResultPayload{
+ {RequestID: "act_ct", Success: true, ExitCode: 0, Stdout: "start requested"},
+ {RequestID: "act_ct-verify-1", Success: true, ExitCode: 0, Stdout: "status: running"},
+ }}
+ executor := newProxmoxGuestActionExecutor(h, agents)
+
+ result, err := executor.ExecuteAction(context.Background(), proxmoxGuestActionRecord("act_ct", "system-container:101", "start"))
+ if err != nil {
+ t.Fatalf("ExecuteAction: %v", err)
+ }
+ if result == nil || !result.Success || result.Verification == nil || !result.Verification.Success {
+ t.Fatalf("result = %#v, want successful execution and verification", result)
+ }
+ if got := agents.calls[0].Command; got != "pct start 101" {
+ t.Fatalf("dispatch command = %q", got)
+ }
+ if got := agents.calls[1].Command; got != "pct status 101" {
+ t.Fatalf("verification command = %q", got)
+ }
+}
+
+func TestProxmoxGuestActionExecutorResolvesCommandAgentByNodeHostname(t *testing.T) {
+ now := time.Now().UTC()
+ resource := proxmoxGuestActionResource("vm:160", unified.ResourceTypeVM, "running", now)
+ resource.Proxmox.LinkedAgentID = "stale-agent"
+ h := NewResourceHandlers(&config.Config{DataPath: t.TempDir()})
+ h.SetStateProvider(resourceUnifiedSeedProvider{
+ snapshot: models.StateSnapshot{LastUpdate: now},
+ resources: []unified.Resource{resource},
+ })
+ agents := &fakeDockerActionAgentCommander{
+ results: []*agentexec.CommandResultPayload{
+ {RequestID: "act_vm", Success: true, ExitCode: 0, Stdout: "reboot requested"},
+ {RequestID: "act_vm-verify-1", Success: true, ExitCode: 0, Stdout: "status: running"},
+ },
+ connected: map[string]bool{
+ "stale-agent": false,
+ "command-agent-1": true,
+ },
+ agentByHost: map[string]string{"delly": "command-agent-1"},
+ }
+ executor := newProxmoxGuestActionExecutor(h, agents).(proxmoxGuestActionExecutor)
+
+ readiness := executor.CheckActionAvailable(context.Background(), unified.ActionRequest{
+ RequestID: "req-availability",
+ ResourceID: "vm:160",
+ CapabilityName: "reboot",
+ Reason: "operator requested reboot",
+ RequestedBy: "operator",
+ }, resource)
+ if !readiness.Available {
+ t.Fatalf("CheckActionAvailable readiness = %#v, want available through node hostname fallback", readiness)
+ }
+
+ result, err := executor.ExecuteAction(context.Background(), proxmoxGuestActionRecord("act_vm", "vm:160", "reboot"))
+ if err != nil {
+ t.Fatalf("ExecuteAction: %v", err)
+ }
+ if result == nil || !result.Success {
+ t.Fatalf("result = %#v, want successful execution", result)
+ }
+ for _, agentID := range agents.callAgents {
+ if agentID != "command-agent-1" {
+ t.Fatalf("called agent %q, want command-agent-1; all calls %#v", agentID, agents.callAgents)
+ }
+ }
+}
+
+func TestProxmoxGuestActionExecutorVerificationFailureFailsAction(t *testing.T) {
+ now := time.Now().UTC()
+ h := NewResourceHandlers(&config.Config{DataPath: t.TempDir()})
+ h.SetStateProvider(resourceUnifiedSeedProvider{
+ snapshot: models.StateSnapshot{LastUpdate: now},
+ resources: []unified.Resource{
+ proxmoxGuestActionResource("vm:160", unified.ResourceTypeVM, "running", now),
+ },
+ })
+ agents := &fakeDockerActionAgentCommander{results: []*agentexec.CommandResultPayload{
+ {RequestID: "act_vm", Success: true, ExitCode: 0, Stdout: "shutdown requested"},
+ {RequestID: "act_vm-verify-1", Success: true, ExitCode: 0, Stdout: "status: running"},
+ {RequestID: "act_vm-verify-2", Success: true, ExitCode: 0, Stdout: "status: running"},
+ {RequestID: "act_vm-verify-3", Success: true, ExitCode: 0, Stdout: "status: running"},
+ {RequestID: "act_vm-verify-4", Success: true, ExitCode: 0, Stdout: "status: running"},
+ {RequestID: "act_vm-verify-5", Success: true, ExitCode: 0, Stdout: "status: running"},
+ }}
+ executor := newProxmoxGuestActionExecutor(h, agents)
+
+ result, err := executor.ExecuteAction(context.Background(), proxmoxGuestActionRecord("act_vm", "vm:160", "shutdown"))
+ if err != nil {
+ t.Fatalf("ExecuteAction: %v", err)
+ }
+ if result == nil || result.Success || result.Verification == nil || result.Verification.Success {
+ t.Fatalf("result = %#v, want failed verification to fail action", result)
+ }
+ if !strings.Contains(result.ErrorMessage, "verification did not confirm") {
+ t.Fatalf("error = %q, want verification failure", result.ErrorMessage)
+ }
+}
+
+func TestHandlePlanActionRejectsDisconnectedProxmoxNodeCommandAgent(t *testing.T) {
+ now := time.Now().UTC()
+ h := NewResourceHandlers(&config.Config{DataPath: t.TempDir()})
+ h.SetStateProvider(resourceUnifiedSeedProvider{
+ snapshot: models.StateSnapshot{LastUpdate: now},
+ resources: []unified.Resource{
+ proxmoxGuestActionResource("vm:160", unified.ResourceTypeVM, "running", now),
+ },
+ })
+ h.SetActionExecutor(newRoutedActionExecutor(
+ h,
+ newProxmoxGuestActionExecutor(h, &fakeDockerActionAgentCommander{
+ connected: map[string]bool{"node-agent-1": false},
+ }),
+ ))
+
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodPost, "/api/actions/plan", bytes.NewBufferString(`{
+ "requestId":"req-disconnected-proxmox-agent",
+ "resourceId":"vm:160",
+ "capabilityName":"reboot",
+ "reason":"operator requested reboot",
+ "requestedBy":"operator"
+ }`))
+ h.HandlePlanAction(rec, req)
+
+ if rec.Code != http.StatusConflict {
+ t.Fatalf("plan status = %d, want %d, body=%s", rec.Code, http.StatusConflict, rec.Body.String())
+ }
+ if !strings.Contains(rec.Body.String(), `"error":"action_execution_unavailable"`) ||
+ !strings.Contains(rec.Body.String(), `"reason":"Proxmox node command agent is not connected."`) ||
+ !strings.Contains(rec.Body.String(), `"reasonCode":"command_agent_disconnected"`) {
+ t.Fatalf("unexpected response body: %s", rec.Body.String())
+ }
+ store, err := h.getStore("default")
+ if err != nil {
+ t.Fatalf("get store: %v", err)
+ }
+ audits, err := store.GetActionAudits("vm:160", time.Time{}, 10)
+ if err != nil {
+ t.Fatalf("GetActionAudits: %v", err)
+ }
+ if len(audits) != 0 {
+ t.Fatalf("audits = %#v, want none for refused plan", audits)
+ }
+}
+
+func TestResourceResponsesFilterDisconnectedProxmoxLifecycleCapabilities(t *testing.T) {
+ now := time.Now().UTC()
+ h := NewResourceHandlers(&config.Config{DataPath: t.TempDir()})
+ h.SetStateProvider(resourceUnifiedSeedProvider{
+ snapshot: models.StateSnapshot{LastUpdate: now},
+ resources: []unified.Resource{
+ proxmoxGuestActionResource("vm:160", unified.ResourceTypeVM, "running", now),
+ },
+ })
+ h.SetActionExecutor(newRoutedActionExecutor(
+ h,
+ newProxmoxGuestActionExecutor(h, &fakeDockerActionAgentCommander{
+ connected: map[string]bool{"node-agent-1": false},
+ }),
+ ))
+
+ listRec := httptest.NewRecorder()
+ listReq := httptest.NewRequest(http.MethodGet, "/api/resources?type=vm", nil)
+ h.HandleListResources(listRec, listReq)
+ if listRec.Code != http.StatusOK {
+ t.Fatalf("list status = %d, body=%s", listRec.Code, listRec.Body.String())
+ }
+ var list ResourcesResponse
+ if err := json.Unmarshal(listRec.Body.Bytes(), &list); err != nil {
+ t.Fatalf("decode list: %v", err)
+ }
+ if len(list.Data) != 1 {
+ t.Fatalf("list data len = %d, want 1", len(list.Data))
+ }
+ if got := dockerActionCapabilityNames(list.Data[0].Capabilities); len(got) != 0 {
+ t.Fatalf("list capabilities = %#v, want none", got)
+ }
+ readiness, ok := dockerActionReadinessByName(list.Data[0].ActionReadiness, "reboot")
+ if !ok || readiness.Available || readiness.ReasonCode != "command_agent_disconnected" {
+ t.Fatalf("list action readiness = %#v, ok=%v; want disconnected reboot", list.Data[0].ActionReadiness, ok)
+ }
+}
+
+func proxmoxGuestActionResource(id string, typ unified.ResourceType, state string, now time.Time) unified.Resource {
+ handler := proxmoxVMLifecycleHandler
+ technology := "qemu"
+ vmid := 160
+ capabilities := []unified.ResourceCapability{
+ {
+ Name: "shutdown",
+ Type: unified.CapabilityTypeCommon,
+ Description: "Gracefully shut down this Proxmox VM",
+ MinimumApprovalLevel: unified.ApprovalAdmin,
+ Platform: "qemu",
+ InternalHandler: proxmoxVMLifecycleHandler,
+ },
+ {
+ Name: "reboot",
+ Type: unified.CapabilityTypeCommon,
+ Description: "Reboot this Proxmox VM",
+ MinimumApprovalLevel: unified.ApprovalAdmin,
+ Platform: "qemu",
+ InternalHandler: proxmoxVMLifecycleHandler,
+ },
+ {
+ Name: "stop",
+ Type: unified.CapabilityTypeCommon,
+ Description: "Hard stop this Proxmox VM",
+ MinimumApprovalLevel: unified.ApprovalAdmin,
+ Platform: "qemu",
+ InternalHandler: proxmoxVMLifecycleHandler,
+ },
+ }
+ if typ == unified.ResourceTypeSystemContainer {
+ handler = proxmoxCTLifecycleHandler
+ technology = "lxc"
+ vmid = 101
+ capabilities = []unified.ResourceCapability{
+ {
+ Name: "start",
+ Type: unified.CapabilityTypeCommon,
+ Description: "Start this Proxmox LXC",
+ MinimumApprovalLevel: unified.ApprovalAdmin,
+ Platform: "lxc",
+ InternalHandler: handler,
+ },
+ }
+ }
+ return unified.Resource{
+ ID: id,
+ Type: typ,
+ Technology: technology,
+ Name: "guest",
+ Status: proxmoxGuestResourceStatus(state),
+ LastSeen: now,
+ UpdatedAt: now,
+ Sources: []unified.DataSource{unified.SourceProxmox},
+ SourceStatus: map[unified.DataSource]unified.SourceStatus{
+ unified.SourceProxmox: {Status: "online", LastSeen: now},
+ },
+ Proxmox: &unified.ProxmoxData{
+ SourceID: "homelab:delly:" + strings.TrimPrefix(id, "vm:"),
+ NodeName: "delly",
+ Instance: "homelab",
+ ClusterName: "homelab",
+ VMID: vmid,
+ LinkedAgentID: "node-agent-1",
+ },
+ Capabilities: capabilities,
+ }
+}
+
+func proxmoxGuestResourceStatus(state string) unified.ResourceStatus {
+ switch state {
+ case "running":
+ return unified.StatusOnline
+ case "stopped":
+ return unified.StatusOffline
+ default:
+ return unified.StatusUnknown
+ }
+}
+
+func proxmoxGuestActionRecord(actionID, resourceID, operation string) unified.ActionAuditRecord {
+ return unified.ActionAuditRecord{
+ ID: actionID,
+ CreatedAt: time.Now().UTC(),
+ UpdatedAt: time.Now().UTC(),
+ State: unified.ActionStateExecuting,
+ Request: unified.ActionRequest{
+ RequestID: "req-" + actionID,
+ ResourceID: resourceID,
+ CapabilityName: operation,
+ Reason: "test execution",
+ RequestedBy: "agent:oncall-helper",
+ Params: map[string]any{},
+ },
+ Plan: unified.ActionPlan{
+ ActionID: actionID,
+ RequestID: "req-" + actionID,
+ Allowed: true,
+ RequiresApproval: true,
+ ApprovalPolicy: unified.ApprovalAdmin,
+ PlannedAt: time.Now().UTC().Add(-time.Minute),
+ ExpiresAt: time.Now().UTC().Add(time.Minute),
+ ResourceVersion: "resource:sha256:test",
+ PolicyVersion: "policy:sha256:test",
+ PlanHash: "sha256:test",
+ },
+ }
+}
diff --git a/internal/api/router.go b/internal/api/router.go
index 3b35b95752..6949c5efea 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -563,7 +563,11 @@ func (r *Router) setupRoutes() {
// Agent execution server for AI tool use
r.agentExecServer = agentexec.NewServer(r.validateAgentExecToken)
if r.resourceHandlers != nil {
- r.resourceHandlers.SetActionExecutor(newDockerContainerActionExecutor(r.resourceHandlers, r.agentExecServer))
+ r.resourceHandlers.SetActionExecutor(newRoutedActionExecutor(
+ r.resourceHandlers,
+ newDockerContainerActionExecutor(r.resourceHandlers, r.agentExecServer),
+ newProxmoxGuestActionExecutor(r.resourceHandlers, r.agentExecServer),
+ ))
}
if r.monitor != nil {
r.configureProxmoxGuestDockerDetection(r.monitor)
diff --git a/internal/unifiedresources/adapters.go b/internal/unifiedresources/adapters.go
index c718360f26..43b6592c8d 100644
--- a/internal/unifiedresources/adapters.go
+++ b/internal/unifiedresources/adapters.go
@@ -1528,6 +1528,7 @@ func resourceFromVM(vm models.VM) (Resource, ResourceIdentity) {
Proxmox: proxmox,
Tags: vm.Tags,
}
+ resource.Capabilities = proxmoxGuestLifecycleCapabilities("vm", "qemu", vm.Status, vm.Template, vm.Lock)
identity := ResourceIdentity{
Hostnames: uniqueStrings([]string{vm.Name}),
IPAddresses: uniqueStrings(vm.IPAddresses),
@@ -1573,6 +1574,7 @@ func resourceFromContainer(ct models.Container) (Resource, ResourceIdentity) {
Proxmox: proxmox,
Tags: ct.Tags,
}
+ resource.Capabilities = proxmoxGuestLifecycleCapabilities("ct", "lxc", ct.Status, ct.Template, ct.Lock)
identity := ResourceIdentity{
Hostnames: uniqueStrings([]string{ct.Name}),
IPAddresses: uniqueStrings(ct.IPAddresses),
@@ -1580,6 +1582,63 @@ func resourceFromContainer(ct models.Container) (Resource, ResourceIdentity) {
return resource, identity
}
+func proxmoxGuestLifecycleCapabilities(kind, platform, status string, template bool, lock string) []ResourceCapability {
+ if template || strings.TrimSpace(lock) != "" {
+ return nil
+ }
+ handler := ""
+ subject := ""
+ switch strings.ToLower(strings.TrimSpace(kind)) {
+ case "vm", "qemu":
+ handler = "proxmox.vm.lifecycle"
+ subject = "VM"
+ case "ct", "lxc", "container":
+ handler = "proxmox.ct.lifecycle"
+ subject = "LXC"
+ default:
+ return nil
+ }
+
+ status = strings.ToLower(strings.TrimSpace(status))
+ operations := []string{}
+ switch status {
+ case "running", "online":
+ operations = []string{"shutdown", "reboot", "stop"}
+ case "stopped", "offline":
+ operations = []string{"start"}
+ default:
+ return nil
+ }
+
+ capabilities := make([]ResourceCapability, 0, len(operations))
+ for _, operation := range operations {
+ capabilities = append(capabilities, ResourceCapability{
+ Name: operation,
+ Type: CapabilityTypeCommon,
+ Description: proxmoxGuestLifecycleDescription(subject, operation),
+ MinimumApprovalLevel: ApprovalAdmin,
+ Platform: strings.TrimSpace(platform),
+ InternalHandler: handler,
+ })
+ }
+ return capabilities
+}
+
+func proxmoxGuestLifecycleDescription(subject, operation string) string {
+ switch operation {
+ case "start":
+ return "Start this Proxmox " + subject
+ case "shutdown":
+ return "Gracefully shut down this Proxmox " + subject
+ case "reboot":
+ return "Reboot this Proxmox " + subject
+ case "stop":
+ return "Hard stop this Proxmox " + subject
+ default:
+ return "Run Proxmox " + subject + " lifecycle action"
+ }
+}
+
func convertGuestInterfaces(in []models.GuestNetworkInterface) []NetworkInterface {
if len(in) == 0 {
return nil
diff --git a/internal/unifiedresources/adapters_test.go b/internal/unifiedresources/adapters_test.go
index 33efba2a3e..c25570a31b 100644
--- a/internal/unifiedresources/adapters_test.go
+++ b/internal/unifiedresources/adapters_test.go
@@ -174,6 +174,102 @@ func TestResourceFromDockerContainerPodmanLifecycleCapabilities(t *testing.T) {
}
}
+func TestResourceFromProxmoxGuestAdvertisesLifecycleCapabilities(t *testing.T) {
+ now := time.Now().UTC()
+
+ vm, _ := resourceFromVM(models.VM{
+ ID: "homelab:delly:160",
+ VMID: 160,
+ Name: "windows-runner",
+ Node: "delly",
+ Instance: "homelab",
+ Status: "running",
+ LastSeen: now,
+ })
+ if got := capabilityNames(vm.Capabilities); !reflect.DeepEqual(got, []string{"shutdown", "reboot", "stop"}) {
+ t.Fatalf("running VM capabilities = %#v, want shutdown/reboot/stop", got)
+ }
+ for _, capability := range vm.Capabilities {
+ if capability.MinimumApprovalLevel != ApprovalAdmin {
+ t.Fatalf("VM capability %q approval = %q, want admin", capability.Name, capability.MinimumApprovalLevel)
+ }
+ if capability.Platform != "qemu" || capability.InternalHandler != "proxmox.vm.lifecycle" {
+ t.Fatalf("VM capability %q platform/handler = %q/%q", capability.Name, capability.Platform, capability.InternalHandler)
+ }
+ }
+
+ stoppedCT, _ := resourceFromContainer(models.Container{
+ ID: "homelab:delly:101",
+ VMID: 101,
+ Name: "homeassistant",
+ Node: "delly",
+ Instance: "homelab",
+ Status: "stopped",
+ LastSeen: now,
+ })
+ if got := capabilityNames(stoppedCT.Capabilities); !reflect.DeepEqual(got, []string{"start"}) {
+ t.Fatalf("stopped LXC capabilities = %#v, want start", got)
+ }
+ if stoppedCT.Capabilities[0].Platform != "lxc" || stoppedCT.Capabilities[0].InternalHandler != "proxmox.ct.lifecycle" {
+ t.Fatalf("LXC platform/handler = %q/%q", stoppedCT.Capabilities[0].Platform, stoppedCT.Capabilities[0].InternalHandler)
+ }
+}
+
+func TestResourceFromProxmoxGuestLifecycleCapabilitiesFailClosed(t *testing.T) {
+ now := time.Now().UTC()
+ cases := []struct {
+ name string
+ vm models.VM
+ }{
+ {
+ name: "template",
+ vm: models.VM{
+ ID: "homelab:delly:9000",
+ VMID: 9000,
+ Name: "template",
+ Node: "delly",
+ Instance: "homelab",
+ Status: "stopped",
+ Template: true,
+ LastSeen: now,
+ },
+ },
+ {
+ name: "locked",
+ vm: models.VM{
+ ID: "homelab:delly:161",
+ VMID: 161,
+ Name: "locked",
+ Node: "delly",
+ Instance: "homelab",
+ Status: "running",
+ Lock: "backup",
+ LastSeen: now,
+ },
+ },
+ {
+ name: "unknown transition state",
+ vm: models.VM{
+ ID: "homelab:delly:162",
+ VMID: 162,
+ Name: "transitioning",
+ Node: "delly",
+ Instance: "homelab",
+ Status: "migrating",
+ LastSeen: now,
+ },
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ resource, _ := resourceFromVM(tc.vm)
+ if len(resource.Capabilities) != 0 {
+ t.Fatalf("capabilities = %#v, want none", resource.Capabilities)
+ }
+ })
+ }
+}
+
func capabilityNames(capabilities []ResourceCapability) []string {
names := make([]string, 0, len(capabilities))
for _, capability := range capabilities {
diff --git a/scripts/release_control/subsystem_lookup_test.py b/scripts/release_control/subsystem_lookup_test.py
index cdb90e2e78..b567761d87 100644
--- a/scripts/release_control/subsystem_lookup_test.py
+++ b/scripts/release_control/subsystem_lookup_test.py
@@ -2857,14 +2857,14 @@ class SubsystemLookupTest(unittest.TestCase):
self.assertEqual(
api_match["matched_contract_references"],
[
- {
- "heading": "## Shared Boundaries",
- "path": "internal/api/access_control_handlers.go",
- "line": 458,
- "heading_line": 120,
- }
- ],
- )
+ {
+ "heading": "## Shared Boundaries",
+ "path": "internal/api/access_control_handlers.go",
+ "line": 461,
+ "heading_line": 123,
+ }
+ ],
+ )
organization_match = by_subsystem["organization-settings"]
self.assertEqual(