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.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
fix outstanding integration and agent regressions
[email protected]ad054defaf3e
diff --git a/frontend-modern/src/components/Settings/__tests__/useTrueNASSettingsPanelState.test.tsx b/frontend-modern/src/components/Settings/__tests__/useTrueNASSettingsPanelState.test.tsxindex ea676f5f0a..7dd014cf7e 100644--- a/frontend-modern/src/components/Settings/__tests__/useTrueNASSettingsPanelState.test.tsx+++ b/frontend-modern/src/components/Settings/__tests__/useTrueNASSettingsPanelState.test.tsx@@ -84,6 +84,7 @@ describe('useTrueNASSettingsPanelState', () => {pollIntervalSeconds: 90,useHttps: true,insecureSkipVerify: false,+ fingerprint: 'SHA256:stored-fingerprint',enabled: true,},] as never);@@ -122,6 +123,7 @@ describe('useTrueNASSettingsPanelState', () => {result.openEditDialog(result.connections()[0]);expect(result.dialogOpen()).toBe(true);expect(result.form().pollIntervalSeconds).toBe('90');+ result.updateForm({ fingerprint: '' });await result.previewCurrentForm();await result.saveCurrentForm();@@ -142,6 +144,7 @@ describe('useTrueNASSettingsPanelState', () => {pollIntervalSeconds: 90,username: 'pulse-readonly',password: '',+ fingerprint: '',}),);expect(result.dialogOpen()).toBe(false);diff --git a/frontend-modern/src/components/Settings/useTrueNASSettingsPanelState.ts b/frontend-modern/src/components/Settings/useTrueNASSettingsPanelState.tsindex 76337788d3..3a1c8add4e 100644--- a/frontend-modern/src/components/Settings/useTrueNASSettingsPanelState.ts+++ b/frontend-modern/src/components/Settings/useTrueNASSettingsPanelState.ts@@ -154,7 +154,10 @@ const buildConnectionInput = (form: TrueNASConnectionFormState): TrueNASConnectipollIntervalSeconds,useHttps: form.useHttps,insecureSkipVerify: form.insecureSkipVerify,- ...(fingerprint ? { fingerprint } : {}),+ // Empty is meaningful when editing: it explicitly clears a previously+ // pinned certificate fingerprint. Omitting the field makes the backend's+ // merge preserve the stored value (#1631).+ fingerprint,enabled: form.enabled,monitorDatasets: form.monitorDatasets,monitorPools: form.monitorPools,diff --git a/internal/dockeragent/container_update_typed.go b/internal/dockeragent/container_update_typed.goindex 90124df81b..0f83688089 100644--- a/internal/dockeragent/container_update_typed.go+++ b/internal/dockeragent/container_update_typed.go@@ -29,8 +29,22 @@ func (a *Agent) TypedContainerUpdate(ctx context.Context, runtime, containerID,if err != nil {return agentexec.DockerContainerUpdateOutcome{}, fmt.Errorf("container preflight inspect unavailable: %v", annotateDockerConnectionError(err))}- if expectedImageDigest != "" && !strings.EqualFold(strings.TrimSpace(inspect.Image), expectedImageDigest) {- return agentexec.DockerContainerUpdateOutcome{}, fmt.Errorf("container image digest no longer matches the planned update")+ if expectedImageDigest != "" {+ expectedImageDigest = strings.TrimSpace(expectedImageDigest)+ localImageID := strings.TrimSpace(inspect.Image)+ matchesLocalID := strings.EqualFold(localImageID, expectedImageDigest)+ matchesRepoDigest := false+ if !matchesLocalID {+ imageName := ""+ if inspect.Config != nil {+ imageName = inspect.Config.Image+ }+ repoDigest, _, _, _ := a.getImageRepoDigest(ctx, localImageID, imageName)+ matchesRepoDigest = strings.EqualFold(strings.TrimSpace(repoDigest), expectedImageDigest)+ }+ if !matchesLocalID && !matchesRepoDigest {+ return agentexec.DockerContainerUpdateOutcome{}, fmt.Errorf("container image digest no longer matches the planned update")+ }}result := a.updateContainerWithProgress(ctx, containerID, progress)diff --git a/internal/dockeragent/container_update_typed_test.go b/internal/dockeragent/container_update_typed_test.goindex 5cba31962b..646bed64e6 100644--- a/internal/dockeragent/container_update_typed_test.go+++ b/internal/dockeragent/container_update_typed_test.go@@ -8,6 +8,7 @@ import ("time"containertypes "github.com/moby/moby/api/types/container"+ "github.com/moby/moby/api/types/image""github.com/moby/moby/api/types/network"v1 "github.com/opencontainers/image-spec/specs-go/v1""github.com/rs/zerolog"@@ -75,6 +76,11 @@ func TestTypedContainerUpdateDelegatesToProductionRecreatePath(t *testing.T) {imagePullFn: func(context.Context, string, dockerImagePullOptions) (io.ReadCloser, error) {return io.NopCloser(strings.NewReader("{}")), nil},+ imageInspectWithRawFn: func(context.Context, string) (image.InspectResponse, []byte, error) {+ return image.InspectResponse{+ RepoDigests: []string{"docker.io/library/nginx@sha256:registry-old"},+ }, nil, nil+ },containerStopFn: func(context.Context, string, dockerContainerStopOptions) error {return nil},@@ -101,7 +107,7 @@ func TestTypedContainerUpdateDelegatesToProductionRecreatePath(t *testing.T) {context.Background(),"docker","container-id",- "sha256:old0000000000",+ "sha256:registry-old",func(step string) { progress = append(progress, step) },)if err != nil {diff --git a/internal/hostagent/agent.go b/internal/hostagent/agent.goindex 47f79537bf..ca5018302a 100644--- a/internal/hostagent/agent.go+++ b/internal/hostagent/agent.go@@ -1095,11 +1095,10 @@ func (a *Agent) buildReport(ctx context.Context) (agentshost.Report, error) {// Collect Ceph cluster data (best effort - only on Ceph nodes)cephData := a.collectCephStatus(collectCtx, runtimeConfig.disableCeph)- // Collect S.M.A.R.T. disk data after topology owners and on its own- // deadline. Unsupported diagnostics must not starve RAID/Unraid/Ceph state.- smartCtx, cancelSMART := context.WithTimeout(ctx, 10*time.Second)- smartData := a.collectSMARTData(smartCtx, runtimeConfig.diskExclude, unraidData)- cancelSMART()+ // Collect S.M.A.R.T. disk data after topology owners. Enumeration and each+ // device probe have their own deadlines; a single shared 10-second budget+ // caused later disks on larger arrays to be cancelled before their probe.+ smartData := a.collectSMARTData(ctx, runtimeConfig.diskExclude, unraidData)if len(smartData) > 0 {annotateSMARTWithDiskIO(smartData, snapshot.DiskIO)sensorData.SMART = smartDatadiff --git a/internal/hostagent/issue1653_synology_smart_test.go b/internal/hostagent/issue1653_synology_smart_test.gonew file mode 100644index 0000000000..a1ab60092b--- /dev/null+++ b/internal/hostagent/issue1653_synology_smart_test.go@@ -0,0 +1,111 @@+package hostagent++import (+ "context"+ "errors"+ "os/exec"+ "slices"+ "strings"+ "testing"+)++func TestIssue1653OldSmartctlRetriesWithoutJSON(t *testing.T) {+ originalRun := smartRunCommandOutput+ originalLookPath := execLookPath+ t.Cleanup(func() {+ smartRunCommandOutput = originalRun+ execLookPath = originalLookPath+ })++ execLookPath = func(string) (string, error) { return "/usr/sbin/smartctl", nil }+ var calls [][]string+ smartRunCommandOutput = func(_ context.Context, _ string, args ...string) ([]byte, error) {+ calls = append(calls, slices.Clone(args))+ if slices.Contains(args, "--json=o") {+ return nil, errors.New("smartctl: unrecognized option '--json=o'")+ }+ return []byte(strings.Join([]string{+ "Device Model: Synology SATA Disk",+ "Serial Number: DSM1653",+ "SMART overall-health self-assessment test result: PASSED",+ "194 Temperature_Celsius 0x0022 100 100 000 Old_age Always - 31",+ }, "\n")), nil+ }++ result, err := collectSMARTTarget(context.Background(), smartctlTarget{Path: "/dev/sata1"})+ if err != nil {+ t.Fatalf("collectSMARTTarget() error = %v", err)+ }+ if result.Serial != "DSM1653" || result.Temperature != 31 || result.Health != "PASSED" {+ t.Fatalf("legacy text result = %+v", result)+ }+ if len(calls) != 2 || !slices.Contains(calls[0], "--json=o") || slices.Contains(calls[1], "--json=o") {+ t.Fatalf("smartctl calls = %v, want JSON attempt followed by text-compatible retry", calls)+ }+}++func TestIssue1653DSMDeviceGetsSATRetry(t *testing.T) {+ originalGOOS := runtimeGOOS+ t.Cleanup(func() { runtimeGOOS = originalGOOS })+ runtimeGOOS = "linux"++ attempts := smartctlProbeAttempts(smartctlTarget{Path: "/dev/sata7"})+ if len(attempts) < 2 {+ t.Fatalf("smartctlProbeAttempts(/dev/sata7) = %v, want untyped and SAT probes", attempts)+ }+ foundSAT := false+ for _, args := range attempts {+ for i := 0; i+1 < len(args); i++ {+ if args[i] == "-d" && args[i+1] == "sat" {+ foundSAT = true+ }+ }+ }+ if !foundSAT {+ t.Fatalf("smartctlProbeAttempts(/dev/sata7) = %v, want -d sat retry", attempts)+ }+}++func TestIssue1653SmartctlPathOverride(t *testing.T) {+ t.Setenv("PULSE_SMARTCTL_PATH", "/opt/syno/bin/smartctl")+ originalLookPath := execLookPath+ t.Cleanup(func() { execLookPath = originalLookPath })+ execLookPath = func(string) (string, error) {+ return "", errors.New("PATH lookup must not run")+ }++ path, err := resolveSmartctlPath()+ if err != nil {+ t.Fatalf("resolveSmartctlPath() error = %v", err)+ }+ if path != "/opt/syno/bin/smartctl" {+ t.Fatalf("resolveSmartctlPath() = %q", path)+ }+}++func TestIssue1653StandbyOSIsRecognized(t *testing.T) {+ fallback := parseSMARTTextFallback("Device is in STANDBY (OS) mode")+ if !fallback.Standby {+ t.Fatal("STANDBY (OS) text was not recognized")+ }+}++func TestIssue1653CommandErrorIncludesStderr(t *testing.T) {+ if _, err := exec.LookPath("sh"); err != nil {+ t.Skip("sh is unavailable")+ }+ _, err := runCommandOutputLimited(+ context.Background(),+ 1024,+ "sh",+ "-c",+ "printf 'smartctl: unrecognized option --json=o' >&2; exit 2",+ )+ if err == nil || !strings.Contains(err.Error(), "unrecognized option") {+ t.Fatalf("runCommandOutputLimited() error = %v, want captured stderr", err)+ }+ var exitErr *exec.ExitError+ if !errors.As(err, &exitErr) {+ t.Fatalf("wrapped error %T does not preserve exec.ExitError", err)+ }+}diff --git a/internal/hostagent/smartctl.go b/internal/hostagent/smartctl.goindex d1b2354a76..63d8e5b494 100644--- a/internal/hostagent/smartctl.go+++ b/internal/hostagent/smartctl.go@@ -1,6 +1,7 @@package hostagentimport (+ "bytes""context""encoding/json""errors"@@ -221,7 +222,7 @@ var (smartTextTempAttributeRE = regexp.MustCompile(`^\s*(190|194)\s+\S+.*-\s+(\d{1,3})\b`)smartTextCurrentTempRE = regexp.MustCompile(`(?i)^current(?: drive)? temperature:\s*(\d{1,3})\b`)smartTextTemperatureRE = regexp.MustCompile(`(?i)^temperature:\s*(\d{1,3})\b`)- linuxDirectSATDeviceRE = regexp.MustCompile(`^(sd|hd)[a-z]+$`)+ linuxDirectSATDeviceRE = regexp.MustCompile(`^((sd|hd)[a-z]+|sata[0-9]+)$`)pciControllerAddressRE = regexp.MustCompile(`(?i)^[0-9a-f]{4}:[0-9a-f]{2}:[0-9a-f]{2}\.[0-7]$`))@@ -252,7 +253,9 @@ func CollectSMARTLocal(ctx context.Context, diskExclude []string) ([]DiskSMART,// Unraid membership, transport, and spin state as authoritative hints. Native// array state is never derived from SMART success or failure.func CollectSMARTLocalWithUnraid(ctx context.Context, diskExclude []string, unraid *agentshost.UnraidStorage) ([]DiskSMART, error) {- targets, err := listSMARTTargets(ctx, diskExclude)+ enumerationCtx, cancelEnumeration := context.WithTimeout(ctx, 10*time.Second)+ targets, err := listSMARTTargets(enumerationCtx, diskExclude)+ cancelEnumeration()if err != nil {log.Debug().Err(err).Msg("failed to list block devices for SMART collection")return nil, fmt.Errorf("list block devices for SMART collection: %w", err)@@ -529,7 +532,7 @@ func unionSMARTTargets(scanTargets []smartctlTarget, devices []string) []smartct}func listSMARTTargetsLinuxFromScan(ctx context.Context, diskExclude []string) ([]smartctlTarget, error) {- smartctlPath, err := execLookPath("smartctl")+ smartctlPath, err := resolveSmartctlPath()if err != nil {return nil, fmt.Errorf("look up smartctl binary: %w", err)}@@ -1369,7 +1372,7 @@ func collectSMARTTarget(ctx context.Context, target smartctlTarget) (*DiskSMART,cmdCtx, cancel := context.WithTimeout(ctx, 10*time.Second)defer cancel()- smartctlPath, err := execLookPath("smartctl")+ smartctlPath, err := resolveSmartctlPath()if err != nil {return nil, fmt.Errorf("look up smartctl binary: %w", err)}@@ -1380,7 +1383,7 @@ func collectSMARTTarget(ctx context.Context, target smartctlTarget) (*DiskSMART,var lastErr errorfor i, args := range attempts {- output, err := smartRunCommandOutput(cmdCtx, smartctlPath, args...)+ output, err := runSmartctlCompatible(cmdCtx, smartctlPath, args)if err != nil {var exitErr *exec.ExitErrorif errors.As(err, &exitErr) {@@ -1477,6 +1480,59 @@ func collectSMARTTarget(ctx context.Context, target smartctlTarget) (*DiskSMART,return nil, errSMARTDataUnavailable}+func resolveSmartctlPath() (string, error) {+ if configured := strings.TrimSpace(os.Getenv("PULSE_SMARTCTL_PATH")); configured != "" {+ if !filepath.IsAbs(configured) {+ return "", fmt.Errorf("PULSE_SMARTCTL_PATH must be an absolute path")+ }+ return configured, nil+ }+ return execLookPath("smartctl")+}++// runSmartctlCompatible keeps JSON output on supported smartmontools releases,+// but retries in text mode for older vendor builds (notably DSM's 6.5 build)+// that reject --json=o before examining the device.+func runSmartctlCompatible(ctx context.Context, smartctlPath string, args []string) ([]byte, error) {+ output, err := smartRunCommandOutput(ctx, smartctlPath, args...)+ if err == nil || !smartctlRejectsJSONOption(output, err) {+ return output, err+ }++ legacyArgs := make([]string, 0, len(args))+ for _, arg := range args {+ if arg != "--json=o" {+ legacyArgs = append(legacyArgs, arg)+ }+ }+ return smartRunCommandOutput(ctx, smartctlPath, legacyArgs...)+}++func smartctlRejectsJSONOption(output []byte, err error) bool {+ message := strings.ToLower(strings.TrimSpace(string(output) + " " + errorString(err)))+ if !strings.Contains(message, "json") {+ return false+ }+ for _, marker := range []string{+ "unrecognized option",+ "unknown option",+ "invalid option",+ "unrecognized command line option",+ } {+ if strings.Contains(message, marker) {+ return true+ }+ }+ return false+}++func errorString(err error) string {+ if err == nil {+ return ""+ }+ return err.Error()+}+func smartctlArgsUseStandbyExitStatus(args []string) bool {want := "standby," + strconv.Itoa(smartctlStandbyExitStatus)for index := 0; index+1 < len(args); index++ {@@ -1977,7 +2033,8 @@ func parseSMARTTextFallback(text string) smartTextFallback {}case strings.HasPrefix(lower, "serial number:"):fallback.Serial = strings.TrimSpace(line[len("Serial Number:"):])- case strings.Contains(lower, "device is in standby mode"):+ case strings.Contains(lower, "device is in standby mode"),+ strings.Contains(lower, "standby (os)"):fallback.Standby = truecase strings.HasPrefix(lower, "smart overall-health self-assessment test result:"):fallback.Health = parseSMARTHealthText(line)@@ -2200,7 +2257,9 @@ func runCommandOutputLimited(ctx context.Context, maxBytes int, name string, arg}cmd := exec.CommandContext(ctx, name, args...)- cmd.Stderr = io.Discard+ var stderr limitedCommandBuffer+ stderr.limit = 32 * 1024+ cmd.Stderr = &stderrstdout, err := cmd.StdoutPipe()if err != nil {@@ -2249,8 +2308,27 @@ func runCommandOutputLimited(ctx context.Context, maxBytes int, name string, argreturn nil, fmt.Errorf("%w (%d bytes)", errCommandOutputTooLarge, maxBytes)}if waitErr != nil {+ if message := strings.TrimSpace(stderr.String()); message != "" {+ return output, fmt.Errorf("%w: %s", waitErr, message)+ }return output, waitErr}return output, nil}++type limitedCommandBuffer struct {+ bytes.Buffer+ limit int+}++func (b *limitedCommandBuffer) Write(p []byte) (int, error) {+ originalLength := len(p)+ if remaining := b.limit - b.Len(); remaining > 0 {+ if len(p) > remaining {+ p = p[:remaining]+ }+ _, _ = b.Buffer.Write(p)+ }+ return originalLength, nil+}diff --git a/internal/monitoring/issue1654_host_reenrollment_test.go b/internal/monitoring/issue1654_host_reenrollment_test.gonew file mode 100644index 0000000000..f102d7b8b2--- /dev/null+++ b/internal/monitoring/issue1654_host_reenrollment_test.go@@ -0,0 +1,136 @@+package monitoring++import (+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/internal/models"+ agentshost "github.com/rcourtman/pulse-go-rewrite/pkg/agents/host"+)++func issue1654Monitor() *Monitor {+ return &Monitor{+ state: models.NewState(),+ config: &config.Config{},+ rateTracker: NewRateTracker(),+ hostTokenBindings: make(map[string]string),+ hostReportOrders: make(map[string]hostReportOrder),+ }+}++func issue1654Report(timestamp time.Time) agentshost.Report {+ return agentshost.Report{+ Agent: agentshost.AgentInfo{+ ID: "new-agent-install",+ Version: "6.2.0",+ IntervalSeconds: 30,+ },+ Host: agentshost.HostInfo{+ ID: "new-install-id",+ MachineID: "machine-stable",+ Hostname: "disk-host.local",+ Platform: "linux",+ },+ Timestamp: timestamp,+ }+}++func TestIssue1654FreshInstallReusesStalePhysicalHostIdentity(t *testing.T) {+ monitor := issue1654Monitor()+ createdAt := time.Now().UTC()+ monitor.state.UpsertHost(models.Host{+ ID: "original-host-id",+ Hostname: "disk-host.local",+ MachineID: "machine-stable",+ TokenID: "old-token",+ LastSeen: createdAt.Add(-time.Minute),+ Status: "offline",+ })+ monitor.hostTokenBindings["old-token:disk-host.local"] = "original-host-id"++ host, err := monitor.ApplyHostReport(+ issue1654Report(createdAt.Add(time.Minute)),+ &config.APITokenRecord{ID: "fresh-token", CreatedAt: createdAt},+ )+ if err != nil {+ t.Fatalf("ApplyHostReport() error = %v", err)+ }+ if host.ID != "original-host-id" {+ t.Fatalf("host ID = %q, want stable original-host-id", host.ID)+ }+ if got := len(monitor.state.GetHosts()); got != 1 {+ t.Fatalf("host count = %d, want 1", got)+ }+ if got := monitor.hostTokenBindings["fresh-token:disk-host.local"]; got != "original-host-id" {+ t.Fatalf("fresh token binding = %q, want original-host-id", got)+ }+ if _, ok := monitor.hostTokenBindings["old-token:disk-host.local"]; ok {+ t.Fatal("pre-install token binding survived stable-ID re-enrollment")+ }+}++func TestIssue1654ExistingDuplicateGenerationIsSuperseded(t *testing.T) {+ monitor := issue1654Monitor()+ createdAt := time.Now().UTC()+ monitor.state.UpsertHost(models.Host{+ ID: "stale-host-id",+ Hostname: "disk-host.local",+ MachineID: "machine-stable",+ TokenID: "old-token",+ LastSeen: createdAt.Add(-time.Minute),+ Status: "offline",+ })+ monitor.state.UpsertHost(models.Host{+ ID: "current-host-id",+ Hostname: "disk-host.local",+ MachineID: "machine-stable",+ TokenID: "fresh-token",+ LastSeen: createdAt.Add(time.Minute),+ Status: "online",+ })+ monitor.hostTokenBindings["old-token:disk-host.local"] = "stale-host-id"+ monitor.hostTokenBindings["fresh-token:disk-host.local"] = "current-host-id"++ host, err := monitor.ApplyHostReport(+ issue1654Report(createdAt.Add(2*time.Minute)),+ &config.APITokenRecord{ID: "fresh-token", CreatedAt: createdAt},+ )+ if err != nil {+ t.Fatalf("ApplyHostReport() error = %v", err)+ }+ if host.ID != "current-host-id" {+ t.Fatalf("host ID = %q, want current-host-id", host.ID)+ }+ hosts := monitor.state.GetHosts()+ if len(hosts) != 1 || hosts[0].ID != "current-host-id" {+ t.Fatalf("hosts after supersession = %+v", hosts)+ }+ if _, ok := monitor.hostTokenBindings["old-token:disk-host.local"]; ok {+ t.Fatal("stale token binding survived supersession")+ }+}++func TestIssue1654LivePreexistingAgentIsNotSuperseded(t *testing.T) {+ monitor := issue1654Monitor()+ createdAt := time.Now().UTC()+ monitor.state.UpsertHost(models.Host{+ ID: "still-live-host",+ Hostname: "disk-host.local",+ MachineID: "machine-stable",+ TokenID: "old-token",+ LastSeen: createdAt.Add(time.Minute),+ Status: "online",+ })++ _, err := monitor.ApplyHostReport(+ issue1654Report(createdAt.Add(2*time.Minute)),+ &config.APITokenRecord{ID: "fresh-token", CreatedAt: createdAt},+ )+ if err != nil {+ t.Fatalf("ApplyHostReport() error = %v", err)+ }+ if got := len(monitor.state.GetHosts()); got != 2 {+ t.Fatalf("host count = %d, want both live identities preserved", got)+ }+}diff --git a/internal/monitoring/monitor_agents.go b/internal/monitoring/monitor_agents.goindex c95f32a2c6..725dce075a 100644--- a/internal/monitoring/monitor_agents.go+++ b/internal/monitoring/monitor_agents.go@@ -2229,6 +2229,122 @@ func normalizedSecurityStrings(values []string) []string {return normalized}+// staleHostIdentityForReenrollment recognizes explicit reinstall intent before+// a new token is bound. Reusing the stale record's ID keeps serial-less+// physical-disk identities stable across reinstall while the token creation+// boundary prevents a foreign token from taking over a live host.+func staleHostIdentityForReenrollment(report agentshost.Report, tokenRecord *config.APITokenRecord, hosts []models.Host) string {+ if tokenRecord == nil || tokenRecord.CreatedAt.IsZero() {+ return ""+ }+ machineID := strings.TrimSpace(report.Host.MachineID)+ hostname := strings.TrimSpace(report.Host.Hostname)+ tokenID := strings.TrimSpace(tokenRecord.ID)+ if machineID == "" || hostname == "" || tokenID == "" {+ return ""+ }++ var bestID string+ var bestLastSeen time.Time+ for _, candidate := range hosts {+ if strings.TrimSpace(candidate.MachineID) != machineID ||+ !unifiedresources.HostnamesEquivalent(candidate.Hostname, hostname) ||+ strings.TrimSpace(candidate.TokenID) == tokenID ||+ !candidate.LastSeen.Before(tokenRecord.CreatedAt) {+ continue+ }+ candidateID := strings.TrimSpace(candidate.ID)+ if candidateID == "" {+ continue+ }+ if bestID == "" || candidate.LastSeen.After(bestLastSeen) {+ bestID = candidateID+ bestLastSeen = candidate.LastSeen+ }+ }+ return bestID+}++// supersedeStaleHostAgentDuplicates removes older generations left behind by+// installs completed before this cleanup existed. This is an internal+// supersession, not a user removal: it deliberately creates no tombstone and+// does not revoke either token.+func (m *Monitor) supersedeStaleHostAgentDuplicates(current models.Host, tokenRecord *config.APITokenRecord, hosts []models.Host) {+ if tokenRecord == nil || tokenRecord.CreatedAt.IsZero() {+ return+ }+ machineID := strings.TrimSpace(current.MachineID)+ hostname := strings.TrimSpace(current.Hostname)+ if machineID == "" || hostname == "" {+ return+ }++ for _, stale := range hosts {+ staleID := strings.TrimSpace(stale.ID)+ if staleID == "" ||+ strings.TrimSpace(stale.MachineID) != machineID ||+ !unifiedresources.HostnamesEquivalent(stale.Hostname, hostname) ||+ !stale.LastSeen.Before(tokenRecord.CreatedAt) {+ continue+ }++ if staleID == strings.TrimSpace(current.ID) {+ // The fresh install reused the physical host's stable ID. Remove+ // bindings for its pre-install token so the stopped old agent+ // cannot later overwrite the replacement through that same ID.+ currentTokenID := strings.TrimSpace(current.TokenID)+ m.mu.Lock()+ for key, boundID := range m.hostTokenBindings {+ if strings.TrimSpace(boundID) != staleID {+ continue+ }+ if key == currentTokenID || strings.HasPrefix(key, currentTokenID+":") {+ continue+ }+ delete(m.hostTokenBindings, key)+ }+ m.mu.Unlock()+ continue+ }++ removed, ok := m.state.RemoveHost(staleID)+ if !ok {+ continue+ }+ m.state.RemoveConnectionHealth(hostConnectionPrefix + staleID)+ m.state.UnlinkNodesFromHostAgent(staleID)++ m.mu.Lock()+ for key, boundID := range m.hostTokenBindings {+ if strings.TrimSpace(boundID) == staleID {+ delete(m.hostTokenBindings, key)+ }+ }+ m.clearHostAgentIdentityTrackingLocked(staleID)+ m.mu.Unlock()++ m.hostReportOrderMu.Lock()+ delete(m.hostReportOrders, staleID)+ m.hostReportOrderMu.Unlock()++ if m.hostContinuityStore != nil {+ if err := m.hostContinuityStore.Delete(staleID); err != nil {+ log.Warn().Err(err).Str("staleHostID", staleID).Msg("Failed to remove superseded host continuity entry")+ }+ }+ if m.alertManager != nil {+ m.alertManager.HandleHostRemoved(removed)+ m.SyncAlertState()+ }++ log.Info().+ Str("host", removed.Hostname).+ Str("staleHostID", staleID).+ Str("replacementHostID", current.ID).+ Msg("Superseded stale host agent record after re-enrollment")+ }+}+// ApplyHostReport ingests a host agent report into the shared state.func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.APITokenRecord) (models.Host, error) {m.hostAgentLifecycleMu.RLock()@@ -2290,6 +2406,7 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.if readState != nil {existingHosts = readState.Hosts()}+ existingHostModels := m.state.GetHosts()identifier := baseIdentifierif tokenRecord != nil && strings.TrimSpace(tokenRecord.ID) != "" {@@ -2312,10 +2429,17 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.identifier = boundID} else {bindingID := baseIdentifier+ reusedStaleID := staleHostIdentityForReenrollment(report, tokenRecord, existingHostModels)+ if reusedStaleID != "" {+ bindingID = reusedStaleID+ }for _, candidate := range existingHosts {if candidate == nil || candidate.AgentID() != bindingID {continue}+ if reusedStaleID == bindingID {+ break+ }if hostAgentHostnamesMatch(candidate.Hostname(), hostname) && strings.TrimSpace(candidate.TokenID()) == tokenID {break}@@ -2414,6 +2538,7 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.if readState != nil {existingHosts = readState.Hosts()}+ existingHostModels = m.state.GetHosts()reportOrder, accepted := m.reserveHostReportOrder(identifier, report, receivedAt)if !accepted {@@ -2772,6 +2897,7 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.m.state.UpsertHost(host)m.state.SetConnectionHealth(hostConnectionPrefix+host.ID, true)+ m.supersedeStaleHostAgentDuplicates(host, tokenRecord, existingHostModels)// Update the linked PVE node to point back to this host agentif host.LinkedNodeID != "" {diff --git a/internal/monitoring/monitor_pve.go b/internal/monitoring/monitor_pve.goindex 245c13f6d4..032ce12118 100644--- a/internal/monitoring/monitor_pve.go+++ b/internal/monitoring/monitor_pve.go@@ -65,12 +65,21 @@ func mergeContainerRuntimeCounters(current IOMetrics, status *proxmox.Container)currentPresence := current.Presence.Effective()statusPresence := status.IOCounters.Effective()- if statusPresence.DiskRead {+ // /cluster/resources and /status/current are sampled by different PVE+ // workers. In practice status/current can lag at zero while the cluster+ // listing already contains a newer LXC disk counter (#1613). Do not let a+ // lower disk value erase that evidence unless uptime proves the guest+ // restarted and began a new counter epoch. Equal values still take the+ // later receipt time so an idle interval is emitted as a valid zero.+ restarted := current.SourceUptime > 0 && status.Uptime > 0 && status.Uptime < current.SourceUptime+ if statusPresence.DiskRead &&+ (!currentPresence.DiskRead || status.DiskRead >= uint64(max(0, current.DiskRead)) || restarted) {current.DiskRead = int64(status.DiskRead)currentPresence.DiskRead = truecurrent.ObservedAt.DiskRead = status.ObservedAt}- if statusPresence.DiskWrite {+ if statusPresence.DiskWrite &&+ (!currentPresence.DiskWrite || status.DiskWrite >= uint64(max(0, current.DiskWrite)) || restarted) {current.DiskWrite = int64(status.DiskWrite)currentPresence.DiskWrite = truecurrent.ObservedAt.DiskWrite = status.ObservedAtdiff --git a/internal/monitoring/monitor_pve_guest_lxc_test.go b/internal/monitoring/monitor_pve_guest_lxc_test.goindex d3197fe9fa..cdf95f7cf9 100644--- a/internal/monitoring/monitor_pve_guest_lxc_test.go+++ b/internal/monitoring/monitor_pve_guest_lxc_test.go@@ -25,11 +25,12 @@ func TestMergeContainerRuntimeCounters_PrefersNewerStatusCounters(t *testing.T)t.Parallel()current := IOMetrics{- DiskRead: 0,- DiskWrite: 8,- NetworkIn: 12,- NetworkOut: 0,- Timestamp: time.Unix(0, 0),+ DiskRead: 0,+ DiskWrite: 8,+ NetworkIn: 12,+ NetworkOut: 0,+ Timestamp: time.Unix(0, 0),+ SourceUptime: 100,}merged := mergeContainerRuntimeCounters(current, &proxmox.Container{@@ -37,6 +38,7 @@ func TestMergeContainerRuntimeCounters_PrefersNewerStatusCounters(t *testing.T)DiskWrite: 4,NetIn: 10,NetOut: 256,+ Uptime: 1,})if merged.DiskRead != 128 {@@ -71,6 +73,7 @@ func TestMergeContainerRuntimeCounters_OverridesOnlyPresentStatusFields(t *testiNetworkIn: true,NetworkOut: true,},+ SourceUptime: 100,}status := &proxmox.Container{DiskRead: 0,@@ -80,6 +83,7 @@ func TestMergeContainerRuntimeCounters_OverridesOnlyPresentStatusFields(t *testiDiskRead: true,},ObservedAt: time.Unix(20, 0),+ Uptime: 1,}merged := mergeContainerRuntimeCounters(current, status)@@ -102,6 +106,65 @@ func TestMergeContainerRuntimeCounters_OverridesOnlyPresentStatusFields(t *testi}}+func TestIssue1613LXCStatusLagDoesNotEraseNewerListingDiskWrite(t *testing.T) {+ t.Parallel()++ monitor := &Monitor{rateTracker: NewRateTracker()}+ client := &stubPVEClientLXCStatus{+ containerStatus: &proxmox.Container{+ Status: "running",+ DiskWrite: 0,+ Uptime: 600,+ IOCounters: proxmox.IOCounterPresence{+ Explicit: true,+ DiskWrite: true,+ },+ ObservedAt: time.Unix(1_700_000_001, 0),+ },+ }+ resource := proxmox.ClusterResource{+ Type: "lxc",+ Node: "pve-a",+ Name: "write-test",+ Status: "running",+ VMID: 203,+ Uptime: 600,+ MaxMem: 4096,+ Mem: 2048,+ ObservedAt: time.Unix(1_700_000_000, 0),+ IOCounters: proxmox.IOCounterPresence{+ Explicit: true,+ DiskWrite: true,+ },+ }++ if _, _, _, _, ok := monitor.buildContainerFromClusterResource(+ context.Background(), "cluster-a", resource, client, map[int]bool{},+ ); !ok {+ t.Fatal("expected first LXC sample")+ }++ resource.DiskWrite = 90 * 1024 * 1024+ resource.ObservedAt = resource.ObservedAt.Add(120 * time.Second)+ client.containerStatus.ObservedAt = resource.ObservedAt.Add(time.Second)++ container, _, _, _, ok := monitor.buildContainerFromClusterResource(+ context.Background(), "cluster-a", resource, client, map[int]bool{},+ )+ if !ok {+ t.Fatal("expected second LXC sample")+ }+ if container.DiskWrite <= 0 {+ t.Fatalf("LXC disk write rate = %d, lagging status/current erased the listing counter", container.DiskWrite)+ }+ // The first authoritative zero came from status/current one second after+ // the listing, while the changed counter came from the next listing.+ const want = 90 * 1024 * 1024 / 119+ if container.DiskWrite != want {+ t.Fatalf("LXC disk write rate = %d B/s, want %d B/s", container.DiskWrite, want)+ }+}+func TestBuildContainerFromClusterResource_UsesContainerStatusCountersForRates(t *testing.T) {t.Parallel()diff --git a/internal/truenas/transport.go b/internal/truenas/transport.goindex feed0e1c6b..92879bb5a7 100644--- a/internal/truenas/transport.go+++ b/internal/truenas/transport.go@@ -216,7 +216,17 @@ func (c *Client) ensureTransportLocked(ctx context.Context) (TransportMode, erroreturn TransportJSONRPC, lockedErr}- if !isUnsupportedWebSocketEndpoint(err) {+ unsupportedEndpoint := isUnsupportedWebSocketEndpoint(err)+ // TrueNAS CORE 13 commonly redirects the HTTPS /api/current handshake to+ // /ui/ instead of returning 404. A redirect from an already-TLS endpoint+ // cannot be an HTTP-to-HTTPS upgrade, so treat it as another form of+ // "JSON-RPC not implemented" and let the version probe decide whether the+ // appliance is eligible for the legacy REST transport.+ if !unsupportedEndpoint && c.config.UseHTTPS {+ var handshake *RPCHandshakeError+ unsupportedEndpoint = errors.As(err, &handshake) && isRedirectStatus(handshake.StatusCode)+ }+ if !unsupportedEndpoint {c.recordTransportError(err)return TransportUnknown, err}diff --git a/internal/truenas/transport_test.go b/internal/truenas/transport_test.goindex abdcea1a8a..8972b4cb59 100644--- a/internal/truenas/transport_test.go+++ b/internal/truenas/transport_test.go@@ -331,6 +331,40 @@ func TestTransportNegotiationAllowsOnlyRecognizedLegacyREST(t *testing.T) {}})+ t.Run("legacy core https redirect", func(t *testing.T) {+ var poolRESTCalls atomic.Int32+ server := httptest.NewTLSServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {+ switch request.URL.Path {+ case "/api/current":+ http.Redirect(writer, request, "/ui/", http.StatusFound)+ case "/api/v2.0/system/info":+ _, _ = writer.Write([]byte(`{"hostname":"core","version":"TrueNAS-13.0-U6.4","uptime_seconds":1}`))+ case "/api/v2.0/pool":+ poolRESTCalls.Add(1)+ _, _ = writer.Write([]byte(`[{"id":1,"name":"core-tank","status":"ONLINE"}]`))+ default:+ http.NotFound(writer, request)+ }+ }))+ t.Cleanup(server.Close)++ client := protocolFixtureClient(t, server.URL, ClientConfig{APIKey: "legacy-core-key"})+ pools, err := client.GetPools(context.Background())+ if err != nil {+ t.Fatalf("GetPools() redirected CORE error = %v", err)+ }+ if len(pools) != 1 || pools[0].Name != "core-tank" {+ t.Fatalf("unexpected redirected CORE pools: %+v", pools)+ }+ if poolRESTCalls.Load() != 1 {+ t.Fatalf("redirected CORE pool REST calls = %d, want 1", poolRESTCalls.Load())+ }+ if status := client.TransportStatus(); status.Mode != TransportLegacyREST ||+ status.ApplianceVersion != "TrueNAS-13.0-U6.4" {+ t.Fatalf("unexpected redirected CORE status: %+v", status)+ }+ })+t.Run("current scale fail closed", func(t *testing.T) {var poolRESTCalls atomic.Int32server := httptest.NewTLSServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {@@ -357,6 +391,33 @@ func TestTransportNegotiationAllowsOnlyRecognizedLegacyREST(t *testing.T) {t.Fatalf("current SCALE used pool REST %d times", poolRESTCalls.Load())}})++ t.Run("current scale https redirect fails closed", func(t *testing.T) {+ var poolRESTCalls atomic.Int32+ server := httptest.NewTLSServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {+ switch request.URL.Path {+ case "/api/current":+ http.Redirect(writer, request, "/ui/", http.StatusFound)+ case "/api/v2.0/system/info":+ _, _ = writer.Write([]byte(`{"hostname":"current","version":"TrueNAS-SCALE-25.10.4","uptime_seconds":1}`))+ case "/api/v2.0/pool":+ poolRESTCalls.Add(1)+ _, _ = writer.Write([]byte(`[]`))+ default:+ http.NotFound(writer, request)+ }+ }))+ t.Cleanup(server.Close)++ client := protocolFixtureClient(t, server.URL, ClientConfig{APIKey: "current-key"})+ _, err := client.GetPools(context.Background())+ if err == nil || !strings.Contains(err.Error(), "refusing REST downgrade") {+ t.Fatalf("GetPools() error = %v, want fail-closed downgrade error", err)+ }+ if poolRESTCalls.Load() != 0 {+ t.Fatalf("current SCALE used pool REST %d times", poolRESTCalls.Load())+ }+ })}func TestJSONRPCCredentialsRequireTLSWithoutSendingAuthentication(t *testing.T) {