Avoid QGA cooldown loop when guest-file commands are disabled (#5192) (#5196)

**Avoid QGA cooldown loop when guest-file commands are disabled
(#5192)**

Classify exact Proxmox HTTP 500 disabled-command rejections for
guest-file-open/read (and other endpoint-bound QGA commands) as terminal
command failures rather than uncertain responses, back off
vmAgentMemCache on disabled commands, and skip /agent/file-read when
/agent/info reports guest-file-open or guest-file-read disabled.

Contract-Neutral: Behavioral bug fix for disabled QGA commands (#5192);
preserves existing GuestAgentErrorReason fixed reasons and
backup-lock/deferral contracts.

**Preserve notified alert severity on resolved notifications (#5191)**

Carry the firing severity recorded on each destination's delivery
receipt into its resolved notification so silent critical-to-warning
demotion before clearing does not send a mismatched warning resolved
webhook.

Contract-Neutral: Behavioral bug fix for resolved notification severity
continuity (#5191); no schema, API, or template contract change.

**Fix helper method call in #5191 severity continuity test**

Use recordSuccessfulDelivery in the queue-less in-memory subtest of
TestFilterResolvedJobsAlignsSeverityPerDestinationAndHandlesLegacyAndMemoryModes.

Contract-Neutral: Test-only fix in resolved_severity_continuity_test.go
for #5191.

---
Fleet candidate `20261126T163233Z-core-runtime` from the `core-runtime`
lane. Reviewed tip `a26e44ab5449dfdaf752106be591919636aa4a31` on `main`.

[How Pulse handles
triage](https://github.com/rcourtman/Pulse/blob/main/docs/AI_TRANSPARENCY.md)
This commit is contained in:
pulse-triage[bot]
2026-11-26 17:57:29 +00:00
committed by GitHub
10 changed files with 946 additions and 41 deletions

View File

@@ -0,0 +1,175 @@
package monitoring
import (
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/rcourtman/pulse-go-rewrite/pkg/proxmox"
)
func TestGuestFileReadDisabledEvidenceBoundary(t *testing.T) {
t.Parallel()
now := time.Now()
key := guestMetadataCacheKey("pve", "node", 105)
for _, tc := range []struct {
name string
entry guestMetadataCacheEntry
want bool
}{
{"current", guestMetadataCacheEntry{fileReadDisabled: true, agentInfoObservedAt: now}, true},
{"just-inside", guestMetadataCacheEntry{fileReadDisabled: true, agentInfoObservedAt: now.Add(-vmAgentMemCleanupMaxAge + time.Nanosecond)}, true},
{"expired", guestMetadataCacheEntry{fileReadDisabled: true, agentInfoObservedAt: now.Add(-vmAgentMemCleanupMaxAge)}, false},
{"future", guestMetadataCacheEntry{fileReadDisabled: true, agentInfoObservedAt: now.Add(time.Nanosecond)}, false},
{"missing-origin", guestMetadataCacheEntry{fileReadDisabled: true, fetchedAt: now}, false},
{"enabled", guestMetadataCacheEntry{fileReadDisabled: false, agentInfoObservedAt: now}, false},
} {
t.Run(tc.name, func(t *testing.T) {
m := &Monitor{guestMetadataCache: map[string]guestMetadataCacheEntry{key: tc.entry}}
if got := m.guestFileReadDisabled("pve", "node", 105, now); got != tc.want {
t.Fatalf("guestFileReadDisabled = %t, want %t", got, tc.want)
}
for _, other := range []struct {
instance, node string
vmid int
}{{"other", "node", 105}, {"pve", "other", 105}, {"pve", "node", 106}} {
if m.guestFileReadDisabled(other.instance, other.node, other.vmid, now) {
t.Fatal("file-read disabled evidence crossed guest identity")
}
}
})
}
}
func TestGuestFileReadDisabledSkipsMeminfoAndPreventsCooldownLoop(t *testing.T) {
for _, kind := range []string{"client", "cluster-client"} {
t.Run(kind, func(t *testing.T) {
var fileReadEnabled atomic.Bool
var fileReadCalls, fsInfoCalls, infoCalls atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch {
case strings.HasSuffix(r.URL.Path, "/nodes"):
fmt.Fprint(w, `{"data":[]}`)
case strings.HasSuffix(r.URL.Path, "/config"):
fmt.Fprint(w, `{"data":{}}`)
case strings.HasSuffix(r.URL.Path, "/agent/file-read"):
fileReadCalls.Add(1)
if !fileReadEnabled.Load() {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, `{"data":null,"message":"VM 105 qmp command 'guest-file-open' failed - The command guest-file-open has been disabled for this instance\n"}`)
return
}
fmt.Fprint(w, `{"data":{"content":"MemTotal: 8388608 kB\nMemAvailable: 5242880 kB\n","truncated":false}}`)
case strings.HasSuffix(r.URL.Path, "/agent/get-fsinfo"):
fsInfoCalls.Add(1)
fmt.Fprint(w, `{"data":{"result":[{"name":"vda1","mountpoint":"/","type":"ext4","total-bytes":1000000000,"used-bytes":300000000}]}}`)
case strings.HasSuffix(r.URL.Path, "/agent/network-get-interfaces"):
fmt.Fprint(w, `{"data":{"result":[{"name":"eth0","hardware-address":"02:00:00:00:00:10","ip-addresses":[{"ip-address":"192.0.2.10","ip-address-type":"ipv4","prefix":24}]}]}}`)
case strings.HasSuffix(r.URL.Path, "/agent/get-osinfo"):
fmt.Fprint(w, `{"data":{"result":{"id":"debian","name":"Debian GNU/Linux","version-id":"12"}}}`)
case strings.HasSuffix(r.URL.Path, "/agent/info"):
infoCalls.Add(1)
enabled := fileReadEnabled.Load()
fmt.Fprintf(w, `{"data":{"result":{"version":"10.1.0","supported_commands":[{"name":"guest-ping","enabled":true},{"name":"guest-get-fsinfo","enabled":true},{"name":"guest-file-open","enabled":%t},{"name":"guest-file-read","enabled":%t}]}}}`, enabled, enabled)
default:
http.NotFound(w, r)
}
}))
defer server.Close()
client := windowsBootstrapClient(t, server.URL, kind)
m := windowsBootstrapMonitor(t)
m.guestMetadataLimiter = make(map[string]time.Time)
status := &proxmox.VMStatus{
MaxMem: 8 * 1024 * 1024 * 1024,
Mem: 4 * 1024 * 1024 * 1024,
Agent: proxmox.VMAgentField{Value: 1},
}
// Step 1: If meminfo runs before /agent/info, disabled guest-file-open must
// neither return ErrGuestAgentDeferred nor trigger cooldown for get-fsinfo.
_, err := m.getVMAgentMemoryAvailability(context.Background(), client, "pve", "node", 105)
if err == nil {
t.Fatal("expected error when guest-file-open is disabled")
}
if errors.Is(err, proxmox.ErrGuestAgentDeferred) {
t.Fatalf("disabled guest-file-open returned ErrGuestAgentDeferred: %v", err)
}
if !proxmox.IsGuestAgentCommandDisabled(err) {
t.Fatalf("expected IsGuestAgentCommandDisabled(err)=true: %v", err)
}
if got := fileReadCalls.Load(); got != 1 {
t.Fatalf("file-read calls = %d, want 1", got)
}
// get-fsinfo succeeds immediately with no agent-cooldown fence.
fs, err := client.GetVMFSInfo(context.Background(), "node", 105)
if err != nil || len(fs) != 1 || fsInfoCalls.Load() != 1 {
t.Fatalf("GetVMFSInfo after disabled file-read = %+v, %v (calls=%d)", fs, err, fsInfoCalls.Load())
}
// Step 2: Even after known-Linux negative TTL (30s) expires, commandDisabled
// keeps long 30m backoff instead of probing every 30s.
memKey := guestMemoryCacheKey("pve", "node", 105)
m.rrdCacheMu.Lock()
entry := m.vmAgentMemCache[memKey]
entry.fetchedAt = time.Now().Add(-vmAgentMemNegativeKnownGuestTTL - time.Second)
m.vmAgentMemCache[memKey] = entry
m.rrdCacheMu.Unlock()
// Populate Linux metadata (with guest-file-open disabled in /agent/info).
_, _, osName, _, agentVersion, deferred := m.fetchGuestAgentMetadata(context.Background(), client, "pve", "node", "linux-vm", 105, status, false)
if deferred || osName != "Debian GNU/Linux" || agentVersion != "10.1.0" || infoCalls.Load() != 1 {
t.Fatalf("fetchGuestAgentMetadata = os=%q ver=%q deferred=%t infoCalls=%d", osName, agentVersion, deferred, infoCalls.Load())
}
// Step 3: With /agent/info reporting guest-file-* disabled, resolveGuestStatusMemory
// skips /agent/file-read completely (even if vmAgentMemCache is empty) and does not defer.
m.rrdCacheMu.Lock()
delete(m.vmAgentMemCache, memKey)
m.rrdCacheMu.Unlock()
total, used, source, memDeferred := m.resolveGuestStatusMemory(
context.Background(), client, "pve", "linux-vm", "node", 105, "pve:node:105",
status, nil, status.MaxMem, "", &VMMemoryRaw{},
)
if memDeferred || total != status.MaxMem || used != status.Mem || source != "status-mem" {
t.Fatalf("resolveGuestStatusMemory = total=%d used=%d source=%q deferred=%t", total, used, source, memDeferred)
}
if got := fileReadCalls.Load(); got != 1 {
t.Fatalf("file-read should be skipped after /agent/info disabled report, calls = %d", got)
}
// Step 4: If the operator re-enables guest-file-* and /agent/info refreshes,
// meminfo reads resume cleanly.
fileReadEnabled.Store(true)
metaKey := guestMetadataCacheKey("pve", "node", 105)
m.guestMetadataMu.Lock()
meta := m.guestMetadataCache[metaKey]
meta.fetchedAt = time.Now().Add(-2 * guestMetadataCacheTTL)
m.guestMetadataCache[metaKey] = meta
m.guestMetadataMu.Unlock()
m.guestMetadataLimiterMu.Lock()
m.guestMetadataLimiter[metaKey] = time.Now().Add(-time.Second)
m.guestMetadataLimiterMu.Unlock()
_, _, _, _, _, deferred = m.fetchGuestAgentMetadata(context.Background(), client, "pve", "node", "linux-vm", 105, status, false)
if deferred || infoCalls.Load() != 2 {
t.Fatalf("refreshed fetchGuestAgentMetadata deferred=%t infoCalls=%d", deferred, infoCalls.Load())
}
info, err := m.getVMAgentMemoryAvailability(context.Background(), client, "pve", "node", 105)
if err != nil || info.Source != "meminfo-available" || fileReadCalls.Load() != 2 {
t.Fatalf("recovered getVMAgentMemoryAvailability = %+v, %v (fileReadCalls=%d)", info, err, fileReadCalls.Load())
}
})
}
}

View File

@@ -26,6 +26,7 @@ type agentMemCacheEntry struct {
info proxmox.LinuxMemoryAvailability
negative bool
permissionDenied bool // Only an observed HTTP 403 overrides known-Linux retry cadence.
commandDisabled bool // QGA explicitly disabled guest-file-open/read for this instance.
fetchedAt time.Time
}
@@ -102,6 +103,12 @@ func (m *Monitor) getVMAgentMemoryAvailability(ctx context.Context, client PVECl
// independent status/balloon/linked-agent memory remains usable.
return proxmox.LinuxMemoryAvailability{}, fmt.Errorf("guest agent Linux meminfo unavailable for Windows")
}
if m.guestFileReadDisabled(instanceName, node, vmid, now) {
// /agent/info reported guest-file-open or guest-file-read disabled for
// this VM instance. Skip /agent/file-read rather than repeatedly
// issuing a command QGA is configured to reject.
return proxmox.LinuxMemoryAvailability{}, fmt.Errorf("guest agent file-read disabled for this instance")
}
// Cache admission and read ownership share the invalidation lock. A miss
// never grants permission to overlap another read, even after cancellation.
@@ -113,7 +120,7 @@ func (m *Monitor) getVMAgentMemoryAvailability(ctx context.Context, client PVECl
if entry, ok := m.vmAgentMemCache[cacheKey]; ok {
ttl := vmAgentMemCacheTTL
if entry.negative {
if entry.permissionDenied {
if entry.permissionDenied || entry.commandDisabled {
ttl = vmAgentMemPermissionDeniedTTL
} else {
ttl = m.vmAgentMemNegativeCacheTTL(instanceName, node, vmid)
@@ -190,6 +197,7 @@ func (m *Monitor) getVMAgentMemoryAvailability(ctx context.Context, client PVECl
m.vmAgentMemCache[cacheKey] = agentMemCacheEntry{
negative: true,
permissionDenied: known && status == http.StatusForbidden,
commandDisabled: proxmox.IsGuestAgentCommandDisabled(err),
fetchedAt: now,
}
if err == nil {
@@ -224,6 +232,15 @@ func (m *Monitor) guestWindowsMeminfoUnsupported(instanceName, node string, vmid
now.Sub(entry.osInfoObservedAt) < vmAgentMemCleanupMaxAge
}
func (m *Monitor) guestFileReadDisabled(instanceName, node string, vmid int, now time.Time) bool {
key := guestMetadataCacheKey(instanceName, node, vmid)
m.guestMetadataMu.RLock()
entry := m.guestMetadataCache[key]
m.guestMetadataMu.RUnlock()
return entry.fileReadDisabled && !entry.agentInfoObservedAt.IsZero() && !entry.agentInfoObservedAt.After(now) &&
now.Sub(entry.agentInfoObservedAt) < vmAgentMemCleanupMaxAge
}
func (m *Monitor) vmAgentMemNegativeCacheTTL(instanceName, node string, vmid int) time.Duration {
if m == nil {
return vmAgentMemNegativeTTL

View File

@@ -39,16 +39,22 @@ const (
// guestMetadataCacheEntry holds cached guest agent metadata for a VM.
type guestMetadataCacheEntry struct {
ipAddresses []string
networkInterfaces []models.GuestNetworkInterface
osName string
osVersion string
agentVersion string
fetchedAt time.Time // Last accepted useful metadata, not the last attempt.
windowsGuest bool // An actual OS reply, not retained display identity.
osInfoObservedAt time.Time // Network/version refreshes cannot renew OS evidence.
osInfoFailureCount int // Track consecutive OS info failures
osInfoSkip bool // Skip OS info calls after repeated failures (refs #692)
ipAddresses []string
networkInterfaces []models.GuestNetworkInterface
osName string
osVersion string
agentVersion string
fetchedAt time.Time // Last accepted useful metadata, not the last attempt.
windowsGuest bool // An actual OS reply, not retained display identity.
osInfoObservedAt time.Time // Network/version refreshes cannot renew OS evidence.
fileReadDisabled bool // /agent/info reported guest-file-open or guest-file-read disabled.
agentInfoObservedAt time.Time // Independent of other metadata refresh timestamps.
osInfoFailureCount int // Track consecutive OS info failures
osInfoSkip bool // Skip OS info calls after repeated failures (refs #692)
}
type guestAgentInfoSummaryClient interface {
GetVMAgentInfoSummary(ctx context.Context, node string, vmid int) (proxmox.VMAgentInfo, error)
}
// A cancelled fetch still owns its key until it returns. Cancellation cannot
@@ -554,13 +560,23 @@ func (m *Monitor) fetchGuestAgentMetadata(ctx context.Context, client PVEClientI
Msg("Skipping guest agent OS info call (disabled after repeated failures)")
}
// Agent version with configurable timeout and retry (refs #592)
// Agent version and command capabilities with configurable timeout and retry (refs #592)
if m.guestMetadataFetchInvalidated(key) {
return nil, nil, "", "", "", true
}
versionRaw, err := m.retryGuestAgentCall(ctx, m.guestAgentVersionTimeout, m.guestAgentRetries, func(ctx context.Context) (interface{}, error) {
return client.GetVMAgentVersion(ctx, nodeName, vmid)
})
fileReadDisabled, agentInfoObservedAt := cached.fileReadDisabled, cached.agentInfoObservedAt
var versionRaw interface{}
var usedSummary bool
if summaryClient, ok := client.(guestAgentInfoSummaryClient); ok {
usedSummary = true
versionRaw, err = m.retryGuestAgentCall(ctx, m.guestAgentVersionTimeout, m.guestAgentRetries, func(ctx context.Context) (interface{}, error) {
return summaryClient.GetVMAgentInfoSummary(ctx, nodeName, vmid)
})
} else {
versionRaw, err = m.retryGuestAgentCall(ctx, m.guestAgentVersionTimeout, m.guestAgentRetries, func(ctx context.Context) (interface{}, error) {
return client.GetVMAgentVersion(ctx, nodeName, vmid)
})
}
if m.guestMetadataFetchInvalidated(key) {
return nil, nil, "", "", "", true
}
@@ -585,6 +601,23 @@ func (m *Monitor) fetchGuestAgentMetadata(ctx context.Context, client PVEClientI
Int("vmid", vmid).
Err(err).
Msg("Guest agent version unavailable")
} else if usedSummary {
if summary, ok := versionRaw.(proxmox.VMAgentInfo); ok {
if summary.Version != "" {
agentVersion = summary.Version
metadataObserved = true
} else if cached.agentVersion == "" {
agentVersion = ""
}
if summary.HasSupportedCommands {
fileReadDisabled = summary.FileReadDisabled
agentInfoObservedAt = time.Now()
} else {
fileReadDisabled, agentInfoObservedAt = false, time.Time{}
}
} else if cached.agentVersion == "" {
agentVersion = ""
}
} else if version, ok := versionRaw.(string); ok && version != "" {
agentVersion = version
metadataObserved = true
@@ -600,16 +633,18 @@ func (m *Monitor) fetchGuestAgentMetadata(ctx context.Context, client PVEClientI
fetchedAt = time.Now()
}
entry := guestMetadataCacheEntry{
ipAddresses: cloneStringSlice(ipAddresses),
networkInterfaces: cloneGuestNetworkInterfaces(networkIfaces),
osName: osName,
osVersion: osVersion,
agentVersion: agentVersion,
fetchedAt: fetchedAt,
windowsGuest: windowsGuest,
osInfoObservedAt: osInfoObservedAt,
osInfoFailureCount: osInfoFailureCount,
osInfoSkip: osInfoSkip,
ipAddresses: cloneStringSlice(ipAddresses),
networkInterfaces: cloneGuestNetworkInterfaces(networkIfaces),
osName: osName,
osVersion: osVersion,
agentVersion: agentVersion,
fetchedAt: fetchedAt,
windowsGuest: windowsGuest,
osInfoObservedAt: osInfoObservedAt,
fileReadDisabled: fileReadDisabled,
agentInfoObservedAt: agentInfoObservedAt,
osInfoFailureCount: osInfoFailureCount,
osInfoSkip: osInfoSkip,
}
if !m.updateGuestMetadataFetch(key, func(current *guestMetadataCacheEntry) { *current = entry }) {
@@ -827,6 +862,9 @@ func isGuestAgentOSInfoUnsupportedError(err error) bool {
if err == nil {
return false
}
if proxmox.IsGuestAgentCommandDisabled(err) {
return true
}
msg := strings.ToLower(err.Error())

View File

@@ -331,6 +331,7 @@ func (n *NotificationManager) retireMemoryDestinationsLocked(keys []string) {
for key := range n.deliveryReceipts {
if strings.HasSuffix(key, "\x00"+old) {
delete(n.deliveryReceipts, key)
delete(n.deliveryReceiptLevels, key)
}
}
}

View File

@@ -437,10 +437,17 @@ func (n *NotificationManager) recordSuccessfulDelivery(job notificationDeliveryJ
if n.deliveryReceipts == nil {
n.deliveryReceipts = make(map[string]struct{})
}
if n.deliveryReceiptLevels == nil {
n.deliveryReceiptLevels = make(map[string]alerts.AlertLevel)
}
if job.Event == eventResolved {
delete(n.deliveryReceipts, key)
delete(n.deliveryReceiptLevels, key)
} else {
n.deliveryReceipts[key] = struct{}{}
if notificationSeverityRank(alert.Level) > notificationSeverityRank(n.deliveryReceiptLevels[key]) {
n.deliveryReceiptLevels[key] = alerts.NormalizeAlertLevel(alert.Level)
}
}
n.mu.Unlock()
n.cacheDeliveryReceipt(alert, destinationKey, deliveredAt, job.Event)
@@ -479,26 +486,43 @@ func (n *NotificationManager) filterResolvedJobsByDeliveryReceipt(jobs []notific
}
eligible := false
epoch := ""
var notifiedLevel alerts.AlertLevel
if queue != nil {
var record notificationRecord
var err error
_, epoch, eligible, err = queue.deliveryReceiptWithEpoch(alert, key)
record, epoch, eligible, err = queue.deliveryReceiptWithEpoch(alert, key)
if err != nil {
log.Error().Err(err).Msg("Failed to read notification delivery receipt; suppressing recovery")
queue.rehearsalReceiptUnavailable(alert, notificationDestinationIDForJob(job))
continue
}
notifiedLevel = record.level
} else {
receiptKey := notificationDeliveryReceiptKey(alert, key)
n.mu.RLock()
_, eligible = n.deliveryReceipts[notificationDeliveryReceiptKey(alert, key)]
_, eligible = n.deliveryReceipts[receiptKey]
if eligible {
notifiedLevel = n.deliveryReceiptLevels[receiptKey]
}
n.mu.RUnlock()
}
if !eligible {
continue
}
// Keep each destination's resolved severity aligned with the firing
// notification it actually received (e.g. when an active metric alert
// silently demotes from critical to warning before clearing, #5191).
resolvedAlert := alert
if notificationSeverityRank(notifiedLevel) > 0 && alerts.NormalizeAlertLevel(resolvedAlert.Level) != notifiedLevel {
if cloned := resolvedAlert.Clone(); cloned != nil {
cloned.Level = notifiedLevel
resolvedAlert = cloned
}
}
if _, found := groups[epoch]; !found {
order = append(order, epoch)
}
groups[epoch] = append(groups[epoch], alert)
groups[epoch] = append(groups[epoch], resolvedAlert)
}
for _, epoch := range order {
copy := job

View File

@@ -215,8 +215,9 @@ type NotificationManager struct {
deliveryCooldown map[string]notificationRecord
initialTarget notificationDeliveryTarget
notifyOnResolve bool
lastNotified map[string]notificationRecord
deliveryReceipts map[string]struct{}
lastNotified map[string]notificationRecord
deliveryReceipts map[string]struct{}
deliveryReceiptLevels map[string]alerts.AlertLevel
groupWindow time.Duration
groupingEnabled bool
pendingAlerts []*alerts.Alert
@@ -314,8 +315,9 @@ func newNotificationManagerWithDataDir(publicURL string, dataDir string, deferQu
cooldown: 5 * time.Minute,
initialTarget: notificationDeliveryTargetAll,
notifyOnResolve: true,
lastNotified: make(map[string]notificationRecord),
deliveryReceipts: make(map[string]struct{}),
lastNotified: make(map[string]notificationRecord),
deliveryReceipts: make(map[string]struct{}),
deliveryReceiptLevels: make(map[string]alerts.AlertLevel),
webhooks: []WebhookConfig{},
appriseConfig: AppriseConfig{
Enabled: false,

View File

@@ -0,0 +1,257 @@
package notifications
import (
"encoding/json"
"net/http"
"testing"
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/alerts"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/stretchr/testify/require"
)
// Regression test for Pulse #5191: when an alert fires as critical, silently
// demotes to warning without re-notifying, and then clears, the resolved
// webhook (both custom templated {{.Level}} and generic JSON) must preserve
// the critical severity that the destination actually received.
func TestResolvedWebhookPreservesNotifiedCriticalLevelAfterSilentDemotion(t *testing.T) {
type customPayload struct {
ID string `json:"id"`
Event string `json:"event"`
Level string `json:"level"`
}
type genericPayload struct {
Event string `json:"event"`
Alerts []*alerts.Alert `json:"alerts"`
}
customCh := make(chan customPayload, 4)
genericCh := make(chan genericPayload, 4)
customServer := newIPv4HTTPServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
var p customPayload
if err := json.NewDecoder(r.Body).Decode(&p); err != nil {
t.Errorf("decode custom payload: %v", err)
w.WriteHeader(http.StatusBadRequest)
return
}
customCh <- p
w.WriteHeader(http.StatusOK)
}))
t.Cleanup(customServer.Close)
genericServer := newIPv4HTTPServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
var p genericPayload
if err := json.NewDecoder(r.Body).Decode(&p); err != nil {
t.Errorf("decode generic payload: %v", err)
w.WriteHeader(http.StatusBadRequest)
return
}
genericCh <- p
w.WriteHeader(http.StatusOK)
}))
t.Cleanup(genericServer.Close)
customHook := WebhookConfig{
ID: "home-assistant",
Name: "Home Assistant",
URL: customServer.URL,
Enabled: true,
Service: "custom",
Template: `{"id":"{{.ID}}","event":"{{.Event}}","level":"{{.Level}}"}`,
}
genericHook := WebhookConfig{
ID: "generic-ops",
Name: "Generic",
URL: genericServer.URL,
Enabled: true,
Service: "generic",
}
nm := NewNotificationManagerWithDataDir("", t.TempDir())
t.Cleanup(nm.Stop)
nm.SetGroupingConfig(false, 0, false, false)
nm.SetNotifyOnResolve(true)
require.NoError(t, nm.UpdateAllowedPrivateCIDRs("127.0.0.1/32"))
nm.AddWebhook(customHook)
nm.AddWebhook(genericHook)
am := alerts.NewManagerWithDataDir(t.TempDir())
t.Cleanup(am.Stop)
cfg := am.GetConfig()
cfg.ActivationState = alerts.ActivationActive
cfg.TimeThresholds["guest"] = 0
cfg.GuestDefaults.CPU = &alerts.HysteresisThreshold{Trigger: 80, Clear: 75}
cfg.Schedule.Cooldown = 60 // Prevent cooldown re-notify on silent demotion
am.UpdateConfig(cfg)
am.SubscribeAlertCallback(nm.SendAlert)
am.SetResolvedAlertCallback(nm.SendResolvedAlert)
container := models.Container{
ID: "pve1:node1:105",
VMID: 105,
Name: "app-ct",
Node: "node1",
Instance: "pve1",
Status: "running",
CPU: 0.995, // 99.5% -> critical (trigger 80, critical 90)
}
// Step 1: Fire at critical.
am.CheckGuest(container, "pve1")
active := am.GetActiveAlerts()
require.Len(t, active, 1)
require.Equal(t, alerts.AlertLevelCritical, active[0].Level)
alertID := active[0].ID
select {
case msg := <-customCh:
require.Equal(t, alertID, msg.ID)
require.Equal(t, "alert", msg.Event)
require.Equal(t, "critical", msg.Level)
case <-time.After(5 * time.Second):
t.Fatal("timed out waiting for custom firing webhook")
}
select {
case msg := <-genericCh:
require.Len(t, msg.Alerts, 1)
require.Equal(t, alerts.AlertLevelCritical, msg.Alerts[0].Level)
case <-time.After(5 * time.Second):
t.Fatal("timed out waiting for generic firing webhook")
}
// Wait until both destinations have recorded their durable delivery receipts.
for _, hook := range []WebhookConfig{customHook, genericHook} {
hookCopy := hook
require.Eventually(t, func() bool {
job := notificationDeliveryJob{
Type: "webhook",
Event: eventResolved,
Alerts: []*alerts.Alert{&active[0]},
WebhookConfig: &hookCopy,
}
return len(nm.filterResolvedJobsByDeliveryReceipt([]notificationDeliveryJob{job})) == 1
}, 5*time.Second, 5*time.Millisecond)
}
// Step 2: Drop into warning band (85% -> between trigger 80 and critical 90).
// Active alert silently demotes to warning without sending a new firing webhook.
container.CPU = 0.85
am.CheckGuest(container, "pve1")
active = am.GetActiveAlerts()
require.Len(t, active, 1)
require.Equal(t, alerts.AlertLevelWarning, active[0].Level)
select {
case extra := <-customCh:
t.Fatalf("unexpected re-notification on silent demotion: %+v", extra)
case <-time.After(150 * time.Millisecond):
}
// Step 3: Clear below clear threshold (70% < 75%).
// Resolved webhooks must still report level: "critical" to match the firing notification.
container.CPU = 0.70
am.CheckGuest(container, "pve1")
require.Empty(t, am.GetActiveAlerts())
select {
case msg := <-customCh:
require.Equal(t, alertID, msg.ID)
require.Equal(t, "resolved", msg.Event)
require.Equal(t, "critical", msg.Level)
case <-time.After(5 * time.Second):
t.Fatal("timed out waiting for custom resolved webhook")
}
select {
case msg := <-genericCh:
require.Equal(t, "resolved", msg.Event)
require.Len(t, msg.Alerts, 1)
require.Equal(t, alerts.AlertLevelCritical, msg.Alerts[0].Level)
case <-time.After(5 * time.Second):
t.Fatal("timed out waiting for generic resolved webhook")
}
}
func TestFilterResolvedJobsAlignsSeverityPerDestinationAndHandlesLegacyAndMemoryModes(t *testing.T) {
t.Run("queued-per-destination-and-legacy-fallback", func(t *testing.T) {
nm := NewNotificationManagerWithDataDir("", t.TempDir())
t.Cleanup(nm.Stop)
q := nm.GetQueue()
require.NotNil(t, q)
hookA := WebhookConfig{ID: "dest-a", URL: "https://example.invalid/a", Enabled: true}
hookB := WebhookConfig{ID: "dest-b", URL: "https://example.invalid/b", Enabled: true}
hookLegacy := WebhookConfig{ID: "dest-legacy", URL: "https://example.invalid/legacy", Enabled: true}
nm.AddWebhook(hookA)
nm.AddWebhook(hookB)
nm.AddWebhook(hookLegacy)
start := time.Now().Add(-10 * time.Minute).Truncate(time.Millisecond)
demoted := &alerts.Alert{
ID: "ct-cpu-105",
Type: "cpu",
Level: alerts.AlertLevelWarning,
StartTime: start,
}
jobs := []notificationDeliveryJob{
{Type: "webhook", Event: eventResolved, Alerts: []*alerts.Alert{demoted}, WebhookConfig: &hookA},
{Type: "webhook", Event: eventResolved, Alerts: []*alerts.Alert{demoted}, WebhookConfig: &hookB},
{Type: "webhook", Event: eventResolved, Alerts: []*alerts.Alert{demoted}, WebhookConfig: &hookLegacy},
}
nm.destinationMu.Lock()
bound := nm.bindDeliveryEpochsLocked(jobs)
nm.destinationMu.Unlock()
// dest-a was notified at critical, dest-b at warning, dest-legacy has legacy unknown severity (0).
require.NoError(t, q.recordDeliveryReceipt(demoted.ID, demoted.StartTime, notificationDeliveryDestinationKey(bound[0]), start.Add(time.Second), notificationSeverityRank(alerts.AlertLevelCritical), bound[0].ReceiptEpoch))
require.NoError(t, q.recordDeliveryReceipt(demoted.ID, demoted.StartTime, notificationDeliveryDestinationKey(bound[1]), start.Add(time.Second), notificationSeverityRank(alerts.AlertLevelWarning), bound[1].ReceiptEpoch))
require.NoError(t, q.recordDeliveryReceipt(demoted.ID, demoted.StartTime, notificationDeliveryDestinationKey(bound[2]), start.Add(time.Second), 0, bound[2].ReceiptEpoch))
filtered := nm.filterResolvedJobsByDeliveryReceipt(jobs)
require.Len(t, filtered, 3)
levelsByID := map[string]alerts.AlertLevel{}
for _, job := range filtered {
require.Len(t, job.Alerts, 1)
levelsByID[job.WebhookConfig.ID] = job.Alerts[0].Level
}
require.Equal(t, alerts.AlertLevelCritical, levelsByID["dest-a"])
require.Equal(t, alerts.AlertLevelWarning, levelsByID["dest-b"])
require.Equal(t, alerts.AlertLevelWarning, levelsByID["dest-legacy"])
// Original input alert must not be mutated across destinations.
require.Equal(t, alerts.AlertLevelWarning, demoted.Level)
})
t.Run("queue-less-in-memory-preserves-notified-level", func(t *testing.T) {
nm := &NotificationManager{
enabled: true,
notifyOnResolve: true,
lastNotified: make(map[string]notificationRecord),
deliveryReceipts: make(map[string]struct{}),
deliveryReceiptLevels: make(map[string]alerts.AlertLevel),
}
hook := WebhookConfig{ID: "mem-hook", URL: "https://example.invalid/mem", Enabled: true}
start := time.Now().Add(-5 * time.Minute)
firing := &alerts.Alert{ID: "mem-alert", Level: alerts.AlertLevelCritical, StartTime: start}
firingJob := notificationDeliveryJob{Type: "webhook", Event: eventAlert, Alerts: []*alerts.Alert{firing}, WebhookConfig: &hook}
require.NoError(t, nm.recordSuccessfulDelivery(firingJob, time.Now()))
demoted := &alerts.Alert{ID: "mem-alert", Level: alerts.AlertLevelWarning, StartTime: start}
resolvedJob := notificationDeliveryJob{Type: "webhook", Event: eventResolved, Alerts: []*alerts.Alert{demoted}, WebhookConfig: &hook}
filtered := nm.filterResolvedJobsByDeliveryReceipt([]notificationDeliveryJob{resolvedJob})
require.Len(t, filtered, 1)
require.Len(t, filtered[0].Alerts, 1)
require.Equal(t, alerts.AlertLevelCritical, filtered[0].Alerts[0].Level)
require.Equal(t, alerts.AlertLevelWarning, demoted.Level)
// Recording resolved delivery clears both receipt presence and level.
require.NoError(t, nm.recordSuccessfulDelivery(filtered[0], time.Now()))
require.Empty(t, nm.filterResolvedJobsByDeliveryReceipt([]notificationDeliveryJob{resolvedJob}))
})
}

View File

@@ -0,0 +1,259 @@
package proxmox
import (
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
)
func TestGuestAgentDisabledCommandErrorReason(t *testing.T) {
const fileReadPath = "/nodes/node/qemu/105/agent/file-read?file=%2Fproc%2Fmeminfo"
const fsInfoPath = "/nodes/node/qemu/105/agent/get-fsinfo"
const osInfoPath = "/nodes/node/qemu/105/agent/get-osinfo"
cases := []struct {
name string
path string
status int
body string
rejected bool
disabled bool
reason string
}{
{
name: "file-open-disabled-plain",
path: fileReadPath,
status: http.StatusInternalServerError,
body: "VM 105 qmp command 'guest-file-open' failed - The command guest-file-open has been disabled for this instance",
rejected: true,
disabled: true,
reason: "agent-error",
},
{
name: "file-open-disabled-json",
path: fileReadPath,
status: http.StatusInternalServerError,
body: `{"data":null,"message":"VM 105 qmp command 'guest-file-open' failed - The command guest-file-open has been disabled for this instance\n"}`,
rejected: true,
disabled: true,
reason: "agent-error",
},
{
name: "file-read-disabled-json",
path: fileReadPath,
status: http.StatusInternalServerError,
body: `{"data":null,"message":"VM 105 qmp command 'guest-file-read' failed - The command guest-file-read has been disabled for this instance"}`,
rejected: true,
disabled: true,
reason: "agent-error",
},
{
name: "file-open-agent-not-running",
path: fileReadPath,
status: http.StatusInternalServerError,
body: `{"data":null,"message":"VM 105 qmp command 'guest-file-open' failed - QEMU guest agent is not running"}`,
rejected: true,
disabled: false,
reason: "agent-not-running",
},
{
name: "osinfo-disabled",
path: osInfoPath,
status: http.StatusInternalServerError,
body: `{"data":null,"message":"VM 105 qmp command 'guest-get-osinfo' failed - The command guest-get-osinfo has been disabled for this instance"}`,
rejected: true,
disabled: true,
reason: "agent-error",
},
{
name: "frozen-guest-stays-uncertain",
path: fileReadPath,
status: http.StatusInternalServerError,
body: `{"data":null,"message":"VM 105 qmp command 'guest-file-open' failed - Command guest-file-open has been disabled: the command is not allowed while guest is frozen"}`,
rejected: false,
disabled: false,
reason: "agent-error",
},
{
name: "wrong-vmid-stays-uncertain",
path: fileReadPath,
status: http.StatusInternalServerError,
body: `{"data":null,"message":"VM 106 qmp command 'guest-file-open' failed - The command guest-file-open has been disabled for this instance"}`,
rejected: false,
disabled: false,
reason: "agent-error",
},
{
name: "wrong-endpoint-stays-uncertain",
path: fsInfoPath,
status: http.StatusInternalServerError,
body: `{"data":null,"message":"VM 105 qmp command 'guest-file-open' failed - The command guest-file-open has been disabled for this instance"}`,
rejected: false,
disabled: false,
reason: "agent-error",
},
{
name: "gateway-502-quoting-disabled-stays-uncertain",
path: fileReadPath,
status: http.StatusBadGateway,
body: `{"data":null,"message":"VM 105 qmp command 'guest-file-open' failed - The command guest-file-open has been disabled for this instance"}`,
rejected: false,
disabled: false,
reason: "agent-error",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
reason := guestAgentTerminalFailureReason(tc.path, []byte(tc.body))
err := &apiResponseError{
statusCode: tc.status,
guestCommandRejected: tc.status == http.StatusInternalServerError && reason != "",
guestFailureReason: reason,
cause: errors.New(tc.body),
}
wrapped := fmt.Errorf("wrapped: %w", err)
if err.guestCommandRejected != tc.rejected {
t.Fatalf("guestCommandRejected = %t, want %t (reason=%q)", err.guestCommandRejected, tc.rejected, reason)
}
if got := IsGuestAgentCommandDisabled(wrapped); got != tc.disabled {
t.Fatalf("IsGuestAgentCommandDisabled = %t, want %t", got, tc.disabled)
}
if got := GuestAgentErrorReason(wrapped); got != tc.reason {
t.Fatalf("GuestAgentErrorReason = %q, want %q", got, tc.reason)
}
})
}
}
func TestGuestAgentFileReadDisabledDoesNotTriggerCooldownAndPreservesBackupLock(t *testing.T) {
var locked atomic.Bool
var agentCalls atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch {
case strings.HasSuffix(r.URL.Path, "/config"):
if locked.Load() {
fmt.Fprint(w, `{"data":{"lock":"backup"}}`)
} else {
fmt.Fprint(w, `{"data":{}}`)
}
case strings.HasSuffix(r.URL.Path, "/agent/file-read"):
agentCalls.Add(1)
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, `{"data":null,"message":"VM 105 qmp command 'guest-file-open' failed - The command guest-file-open has been disabled for this instance\n"}`)
case strings.HasSuffix(r.URL.Path, "/agent/get-fsinfo"):
agentCalls.Add(1)
fmt.Fprint(w, `{"data":{"result":[{"name":"vda1","mountpoint":"/","type":"ext4","total-bytes":1000000,"used-bytes":400000}]}}`)
case strings.HasSuffix(r.URL.Path, "/agent/get-osinfo"):
agentCalls.Add(1)
fmt.Fprint(w, `{"data":{"result":{"id":"debian","name":"Debian GNU/Linux","version-id":"12"}}}`)
case strings.HasSuffix(r.URL.Path, "/agent/info"):
agentCalls.Add(1)
fmt.Fprint(w, `{"data":{"result":{"version":"10.1.0","supported_commands":[{"name":"guest-ping","enabled":true,"success-response":true},{"name":"guest-get-fsinfo","enabled":true,"success-response":true},{"name":"guest-file-open","enabled":false,"success-response":true},{"name":"guest-file-read","enabled":false,"success-response":true}]}}}`)
default:
http.NotFound(w, r)
}
}))
defer server.Close()
c := backupTestClient(t, guestAgentFixtureEndpoint(t, server.URL))
// 1. Disabled guest-file-open HTTP 500 must be a terminal rejection, not ErrGuestAgentDeferred.
if _, err := c.GetVMMemoryAvailabilityFromAgent(context.Background(), "node", 105); err == nil {
t.Fatal("expected error from disabled file-read")
} else {
if errors.Is(err, ErrGuestAgentDeferred) {
t.Fatalf("disabled guest-file-open triggered deferral/cooldown: %v", err)
}
if !IsGuestAgentCommandDisabled(err) {
t.Fatalf("expected IsGuestAgentCommandDisabled(err)=true, got false: %v", err)
}
if reason := GuestAgentErrorReason(err); reason != "agent-error" {
t.Fatalf("GuestAgentErrorReason = %q, want agent-error", reason)
}
}
// 2. Subsequent QGA reads on the same VM must succeed immediately (no 60s agent-cooldown).
fs, err := c.GetVMFSInfo(context.Background(), "node", 105)
if err != nil || len(fs) != 1 || fs[0].Mountpoint != "/" {
t.Fatalf("GetVMFSInfo after disabled file-read = %+v, %v", fs, err)
}
osInfo, err := c.GetVMAgentInfo(context.Background(), "node", 105)
if err != nil || osInfo == nil {
t.Fatalf("GetVMAgentInfo after disabled file-read = %+v, %v", osInfo, err)
}
summary, err := c.GetVMAgentInfoSummary(context.Background(), "node", 105)
if err != nil {
t.Fatalf("GetVMAgentInfoSummary failed: %v", err)
}
if summary.Version != "10.1.0" || !summary.HasSupportedCommands || !summary.FileReadDisabled {
t.Fatalf("GetVMAgentInfoSummary = %+v, want version 10.1.0, HasSupportedCommands=true, FileReadDisabled=true", summary)
}
// 3. Backup lock must still block GetVMAgentInfoSummary and file-read before any QGA call.
beforeLocked := agentCalls.Load()
locked.Store(true)
if _, err := c.GetVMAgentInfoSummary(context.Background(), "node", 105); GuestAgentDeferredReason(err) != "vm-locked" {
t.Fatalf("locked GetVMAgentInfoSummary err = %v, want vm-locked", err)
}
if _, err := c.GetVMMemoryAvailabilityFromAgent(context.Background(), "node", 105); GuestAgentDeferredReason(err) != "vm-locked" {
t.Fatalf("locked GetVMMemoryAvailabilityFromAgent err = %v, want vm-locked", err)
}
if agentCalls.Load() != beforeLocked {
t.Fatalf("agent calls increased while VM was backup-locked: %d -> %d", beforeLocked, agentCalls.Load())
}
}
func TestParseVMAgentInfoResultBoundaries(t *testing.T) {
t.Parallel()
cases := []struct {
name string
raw string
want VMAgentInfo
}{
{
name: "enabled-file-commands",
raw: `{"version":"10.1.0","supported_commands":[{"name":"guest-file-open","enabled":true},{"name":"guest-file-read","enabled":true}]}`,
want: VMAgentInfo{Version: "10.1.0", HasSupportedCommands: true, FileReadDisabled: false},
},
{
name: "only-file-read-disabled",
raw: `{"version":"10.1.0","supported_commands":[{"name":"guest-file-open","enabled":true},{"name":"guest-file-read","enabled":false}]}`,
want: VMAgentInfo{Version: "10.1.0", HasSupportedCommands: true, FileReadDisabled: true},
},
{
name: "hyphenated-key",
raw: `{"qemu-ga":{"version":"9.2.0"},"supported-commands":[{"name":"guest-file-open","enabled":false}]}`,
want: VMAgentInfo{Version: "9.2.0", HasSupportedCommands: true, FileReadDisabled: true},
},
{
name: "omitted-supported-commands",
raw: `{"version":"10.1.0"}`,
want: VMAgentInfo{Version: "10.1.0", HasSupportedCommands: false, FileReadDisabled: false},
},
{
name: "null-supported-commands",
raw: `{"version":"10.1.0","supported_commands":null}`,
want: VMAgentInfo{Version: "10.1.0", HasSupportedCommands: false, FileReadDisabled: false},
},
{
name: "empty-supported-commands",
raw: `{"version":"10.1.0","supported_commands":[]}`,
want: VMAgentInfo{Version: "10.1.0", HasSupportedCommands: true, FileReadDisabled: false},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := parseVMAgentInfoResult([]byte(tc.raw)); got != tc.want {
t.Fatalf("parseVMAgentInfoResult = %+v, want %+v", got, tc.want)
}
})
}
}

View File

@@ -0,0 +1,106 @@
package proxmox
import (
"bytes"
"context"
"encoding/json"
"fmt"
"strings"
)
// VMAgentInfo summarizes the bounded version and file-read capability reported
// by the QEMU guest agent's /agent/info endpoint.
type VMAgentInfo struct {
Version string
HasSupportedCommands bool
FileReadDisabled bool
}
// GetVMAgentInfoSummary returns the guest agent version and whether /agent/info
// explicitly reports guest-file-open or guest-file-read disabled for this VM.
func (c *Client) GetVMAgentInfoSummary(ctx context.Context, node string, vmid int) (VMAgentInfo, error) {
resp, err := c.get(ctx, fmt.Sprintf("/nodes/%s/qemu/%d/agent/info", node, vmid))
if err != nil {
return VMAgentInfo{}, fmt.Errorf("guest agent info: %w", err)
}
defer resp.Body.Close()
var result struct {
Data struct {
Result json.RawMessage `json:"result"`
} `json:"data"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return VMAgentInfo{}, err
}
return parseVMAgentInfoResult(result.Data.Result), nil
}
// GetVMAgentInfoSummary executes the /agent/info read through the cluster
// client's single-attempt guest-agent admission path.
func (cc *ClusterClient) GetVMAgentInfoSummary(ctx context.Context, node string, vmid int) (VMAgentInfo, error) {
var info VMAgentInfo
err := cc.executeGuestAgent(ctx, func(c *Client) error {
var callErr error
info, callErr = c.GetVMAgentInfoSummary(ctx, node, vmid)
return callErr
})
return info, err
}
func parseVMAgentInfoResult(raw json.RawMessage) VMAgentInfo {
fields, ok := guestAgentFields(raw, "version", "qemu-ga", "supported_commands", "supported-commands")
if !ok {
return VMAgentInfo{}
}
extractVersion := func(val json.RawMessage) string {
if v, ok := guestAgentScalar(val).(string); ok {
return strings.TrimSpace(v)
}
nested, _ := guestAgentScalarFields(val, "version")
if s, ok := nested["version"].(string); ok {
return strings.TrimSpace(s)
}
return ""
}
var summary VMAgentInfo
if version := extractVersion(fields["version"]); version != "" {
summary.Version = version
} else if version := extractVersion(fields["qemu-ga"]); version != "" {
summary.Version = version
}
rawCommands := fields["supported_commands"]
if len(rawCommands) == 0 {
rawCommands = fields["supported-commands"]
}
rawCommands = bytes.TrimSpace(rawCommands)
if len(rawCommands) == 0 || bytes.Equal(rawCommands, []byte("null")) {
return summary
}
var commands guestAgentList
if err := json.Unmarshal(rawCommands, &commands); err != nil || commands == nil {
return summary
}
summary.HasSupportedCommands = true
for _, entry := range commands {
scalars, ok := guestAgentScalarFields(entry, "name", "enabled")
if !ok {
continue
}
name, ok := scalars["name"].(string)
if !ok || (name != "guest-file-open" && name != "guest-file-read") {
continue
}
if enabled, ok := scalars["enabled"].(bool); ok && !enabled {
summary.FileReadDisabled = true
break
}
}
return summary
}

View File

@@ -24,6 +24,8 @@ type apiResponseError struct {
func (e *apiResponseError) Error() string { return e.cause.Error() }
func (e *apiResponseError) Unwrap() error { return e.cause }
const guestAgentReasonCommandDisabled = "agent-command-disabled"
// GuestAgentErrorReason preserves observed HTTP/command evidence for callers
// without treating numbers or instructions quoted in an error body as status.
// It returns only existing fixed disk-status reasons, never provider text.
@@ -40,12 +42,25 @@ func GuestAgentErrorReason(err error) string {
return "permission-denied"
case http.StatusInternalServerError:
if response.guestCommandRejected {
if response.guestFailureReason == guestAgentReasonCommandDisabled {
return "agent-error"
}
return response.guestFailureReason
}
}
return "agent-error"
}
// IsGuestAgentCommandDisabled reports whether a Proxmox HTTP 500 explicitly
// rejected the requested guest-agent command as disabled for that VM instance.
func IsGuestAgentCommandDisabled(err error) bool {
var response *apiResponseError
return errors.As(err, &response) &&
response.statusCode == http.StatusInternalServerError &&
response.guestCommandRejected &&
response.guestFailureReason == guestAgentReasonCommandDisabled
}
// Only specific, complete terminal failures from the command endpoint allow
// another command after an HTTP 500. An unexplained 5xx, even with a complete
// body, does not establish that a serial QGA command has finished.
@@ -60,20 +75,31 @@ func guestAgentTerminalFailureReason(path string, body []byte) string {
}
commandPath := strings.SplitN(path, "?", 2)[0]
command := "guest-" + commandPath[strings.LastIndex(commandPath, "/")+1:]
message = strings.TrimPrefix(message, fmt.Sprintf("VM %d qmp command '%s' failed - ", vmid, command))
switch message {
case "QEMU guest agent is not running":
return "agent-not-running"
case "unsupported command: " + command,
"The command " + command + " has not been found":
return "agent-error"
// PVE's /agent/file-read endpoint runs guest-file-open before
// guest-file-read, so a disabled or stopped agent rejects on guest-file-open.
commands := []string{command}
if command == "guest-file-read" {
commands = []string{"guest-file-read", "guest-file-open"}
}
for _, qmpCommand := range commands {
trimmed := strings.TrimPrefix(message, fmt.Sprintf("VM %d qmp command '%s' failed - ", vmid, qmpCommand))
switch trimmed {
case "QEMU guest agent is not running":
return "agent-not-running"
case "unsupported command: " + qmpCommand,
"The command " + qmpCommand + " has not been found":
return "agent-error"
case "The command " + qmpCommand + " has been disabled for this instance":
return guestAgentReasonCommandDisabled
}
}
// Preserve the existing OpenBSD OS-info skip rather than repeatedly probing
// its missing os-release file. Do not apply it to another guest command.
if command == "guest-get-osinfo" {
message = strings.TrimPrefix(message, "guest agent command failed: ")
trimmed := strings.TrimPrefix(message, fmt.Sprintf("VM %d qmp command '%s' failed - ", vmid, command))
trimmed = strings.TrimPrefix(trimmed, "guest agent command failed: ")
for _, filename := range []string{"/etc/os-release", "/usr/lib/os-release"} {
if message == "Failed to open file '"+filename+"': No such file or directory" {
if trimmed == "Failed to open file '"+filename+"': No such file or directory" {
return "agent-error"
}
}