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
Add Pro-gated probe assignment to availability targets
[email protected]a5b3816fd376
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.mdindex 19b3d30dc7..3d71adebda 100644--- a/docs/release-control/v6/internal/subsystems/monitoring.md+++ b/docs/release-control/v6/internal/subsystems/monitoring.md@@ -943,6 +943,19 @@ the frontend-primitives-owned Standalone surface may read the same`network-endpoint` projection to show current reachability, latency, check age,and failure state without creating another monitoring provider or top-levelavailability route.+Availability targets may also be assigned to a remote host agent. While the+`external_probe` entitlement is active, a probe-assigned target is executed+exclusively by its assigned agent: monitoring must not schedule or run it+locally, so the check never executes twice. The assignment is effective only for+as long as the entitlement holds; on lapse the effective assignment collapses to+local and the normal poll provider resumes the target on its next planning+cycle, without a restart. Reported results are accepted only from the agent that+currently owns the target, and results for any other target or from any other+agent are dropped. Failure accounting, thresholds, and incident projection stay+server-side. When an assigned agent stops reporting, monitoring derives+indeterminate with a stale-report explanation at read time through the shared+probe-status snapshot rather than mutating stored state, so every availability+consumer sees the same staleness verdict.Mock-mode Discovery context follows the same fixture-graph rule. Demo servicedetails such as detected version, config/data/log paths, Docker bind mounts,ports, and suggested web URLs may be authored in mock fixtures, but consumersdiff --git a/internal/api/availability_handlers.go b/internal/api/availability_handlers.goindex 1f824ab85e..162db91b88 100644--- a/internal/api/availability_handlers.go+++ b/internal/api/availability_handlers.go@@ -15,8 +15,9 @@ import (const availabilityTargetsPathPrefix = "/api/availability-targets/"type AvailabilityHandlers struct {- getPersistence func(ctx context.Context) *config.ConfigPersistence- getMonitor func(ctx context.Context) *monitoring.Monitor+ getPersistence func(ctx context.Context) *config.ConfigPersistence+ getMonitor func(ctx context.Context) *monitoring.Monitor+ licenseResolver licenseFeatureServiceResolver}type availabilityTargetResponse struct {@@ -34,13 +35,72 @@ type availabilityTestResponse struct {func NewAvailabilityHandlers(getPersistence func(ctx context.Context) *config.ConfigPersistence,getMonitor func(ctx context.Context) *monitoring.Monitor,+ licenseResolver licenseFeatureServiceResolver,) *AvailabilityHandlers {return &AvailabilityHandlers{- getPersistence: getPersistence,- getMonitor: getMonitor,+ getPersistence: getPersistence,+ getMonitor: getMonitor,+ licenseResolver: licenseResolver,}}+// availabilityFeatureResolverFunc adapts a closure to the licensing+// FeatureServiceResolver so the router can resolve handlers that are+// constructed before the license handlers exist.+type availabilityFeatureResolverFunc func(ctx context.Context) licenseFeatureChecker++func (f availabilityFeatureResolverFunc) FeatureService(ctx context.Context) licenseFeatureChecker {+ if f == nil {+ return nil+ }+ return f(ctx)+}++// requireProbeAssignment gates only targets that carry a probe assignment.+// Unassigned targets are the community behaviour and must never consult the+// license path.+func (h *AvailabilityHandlers) requireProbeAssignment(w http.ResponseWriter, r *http.Request, target config.AvailabilityTarget) bool {+ if strings.TrimSpace(target.ProbeAgentID) == "" {+ return true+ }+ if h == nil || h.licenseResolver == nil {+ WriteLicenseRequired(w, featureExternalProbeValue, "license service unavailable")+ return false+ }+ service := h.licenseResolver.FeatureService(r.Context())+ if service == nil {+ WriteLicenseRequired(w, featureExternalProbeValue, "license service unavailable")+ return false+ }+ if err := service.RequireFeature(featureExternalProbeValue); err != nil {+ WriteLicenseRequired(w, featureExternalProbeValue, err.Error())+ return false+ }+ if !h.probeAgentExists(r.Context(), target.ProbeAgentID) {+ writeErrorResponse(w, http.StatusBadRequest, "unknown_probe_agent",+ "Probe agent "+target.ProbeAgentID+" is not a registered host agent", nil)+ return false+ }+ return true+}++func (h *AvailabilityHandlers) probeAgentExists(ctx context.Context, agentID string) bool {+ agentID = strings.TrimSpace(agentID)+ if agentID == "" {+ return false+ }+ monitor := h.monitorForRequest(ctx)+ if monitor == nil {+ return false+ }+ for _, host := range monitor.GetLiveHostsSnapshot() {+ if strings.TrimSpace(host.ID) == agentID {+ return true+ }+ }+ return false+}+func (h *AvailabilityHandlers) HandleList(w http.ResponseWriter, r *http.Request) {if mock.IsMockEnabled() {writeJSON(w, http.StatusOK, mockAvailabilityTargetResponses())@@ -87,6 +147,9 @@ func (h *AvailabilityHandlers) HandleAdd(w http.ResponseWriter, r *http.Request)writeErrorResponse(w, http.StatusBadRequest, "validation_error", err.Error(), nil)return}+ if !h.requireProbeAssignment(w, r, target) {+ return+ }persistence := h.persistenceForRequest(w, r.Context())if persistence == nil {@@ -154,6 +217,9 @@ func (h *AvailabilityHandlers) HandleUpdate(w http.ResponseWriter, r *http.RequewriteErrorResponse(w, http.StatusBadRequest, "validation_error", err.Error(), nil)return}+ if !h.requireProbeAssignment(w, r, target) {+ return+ }targets[index] = targetif err := persistence.SaveAvailabilityTargets(targets); err != nil {writeErrorResponse(w, http.StatusInternalServerError, "availability_save_failed", "Failed to save availability targets", map[string]string{"error": err.Error()})diff --git a/internal/api/availability_handlers_test.go b/internal/api/availability_handlers_test.goindex 9337bf02bb..f014c0957f 100644--- a/internal/api/availability_handlers_test.go+++ b/internal/api/availability_handlers_test.go@@ -17,6 +17,7 @@ func TestAvailabilityHandlersCRUDPersistsTargets(t *testing.T) {handler := NewAvailabilityHandlers(func(_ context.Context) *config.ConfigPersistence { return persistence },nil,+ nil,)createBody := availabilityRequestBody(t, config.AvailabilityTarget{@@ -96,6 +97,7 @@ func TestAvailabilityHandlersCreateNormalizesPingAlias(t *testing.T) {handler := NewAvailabilityHandlers(func(_ context.Context) *config.ConfigPersistence { return persistence },nil,+ nil,)createBody := availabilityRequestBody(t, config.AvailabilityTarget{@@ -159,6 +161,7 @@ func TestAvailabilityHandlersTestSavedTarget(t *testing.T) {handler := NewAvailabilityHandlers(func(_ context.Context) *config.ConfigPersistence { return persistence },nil,+ nil,)req := httptest.NewRequest(http.MethodPost, "/api/availability-targets/status-page/test", nil)@@ -190,6 +193,7 @@ func TestAvailabilityHandlersListReturnsMockTargetsInMockMode(t *testing.T) {return nil},nil,+ nil,)req := httptest.NewRequest(http.MethodGet, "/api/availability-targets", nil)@@ -246,7 +250,7 @@ func TestAvailabilityHandlersTestSavedMockTargetUsesSyntheticStatus(t *testing.T}t.Cleanup(func() { _ = mock.SetEnabled(previous) })- handler := NewAvailabilityHandlers(nil, nil)+ handler := NewAvailabilityHandlers(nil, nil, nil)req := httptest.NewRequest(http.MethodPost, "/api/availability-targets/mock-availability-door-controller/test", nil)rec := httptest.NewRecorder()@@ -281,6 +285,7 @@ func TestAvailabilityTargetLinkedResourceIDRoundTrip(t *testing.T) {handler := NewAvailabilityHandlers(func(_ context.Context) *config.ConfigPersistence { return persistence },nil,+ nil,)createBody := availabilityRequestBody(t, config.AvailabilityTarget{diff --git a/internal/api/availability_probe_agent_test.go b/internal/api/availability_probe_agent_test.gonew file mode 100644index 0000000000..c9e9099e32--- /dev/null+++ b/internal/api/availability_probe_agent_test.go@@ -0,0 +1,247 @@+package api++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/internal/models"+ "github.com/rcourtman/pulse-go-rewrite/internal/monitoring"+ agentshost "github.com/rcourtman/pulse-go-rewrite/pkg/agents/host"+)++type stubFeatureChecker struct {+ features map[string]bool+}++func (s stubFeatureChecker) HasFeature(feature string) bool {+ return s.features[feature]+}++func (s stubFeatureChecker) RequireFeature(feature string) error {+ if s.features[feature] {+ return nil+ }+ return fmt.Errorf("feature %s is not licensed", feature)+}++func stubFeatureResolver(features ...string) licenseFeatureServiceResolver {+ allowed := map[string]bool{}+ for _, feature := range features {+ allowed[feature] = true+ }+ return availabilityFeatureResolverFunc(func(context.Context) licenseFeatureChecker {+ return stubFeatureChecker{features: allowed}+ })+}++// monitorWithHostAgent registers one host agent so probe assignment can be+// validated against real monitor state.+func monitorWithHostAgent(t *testing.T, hostID string) *monitoring.Monitor {+ t.Helper()+ monitor, err := monitoring.New(&config.Config{DataPath: t.TempDir()})+ if err != nil {+ t.Fatalf("monitoring.New() error = %v", err)+ }+ t.Cleanup(monitor.Stop)++ if _, err := monitor.ApplyHostReport(agentshost.Report{+ Agent: agentshost.AgentInfo{ID: hostID + "-agent", Version: "6.1.1", IntervalSeconds: 30},+ Host: agentshost.HostInfo{ID: hostID, MachineID: hostID, Hostname: hostID, Platform: "linux"},+ Timestamp: time.Now().UTC(),+ }, &config.APITokenRecord{ID: "token-" + hostID, Name: hostID}); err != nil {+ t.Fatalf("ApplyHostReport() error = %v", err)+ }+ return monitor+}++func probeAssignedTargetBody(t *testing.T, agentID string) *bytes.Reader {+ t.Helper()+ return availabilityRequestBody(t, config.AvailabilityTarget{+ Name: "Branch gateway",+ Address: "gateway.branch.local",+ Protocol: config.AvailabilityProbeICMP,+ Enabled: true,+ PollIntervalSecs: 30,+ TimeoutMillis: 1000,+ FailureThreshold: 2,+ ProbeAgentID: agentID,+ })+}++func TestAvailabilityHandlersRejectProbeAssignmentWithoutLicense(t *testing.T) {+ persistence := config.NewConfigPersistence(t.TempDir())+ monitor := monitorWithHostAgent(t, "probe-host")+ handler := NewAvailabilityHandlers(+ func(context.Context) *config.ConfigPersistence { return persistence },+ func(context.Context) *monitoring.Monitor { return monitor },+ stubFeatureResolver(),+ )++ rec := httptest.NewRecorder()+ handler.HandleAdd(rec, httptest.NewRequest(http.MethodPost, "/api/availability-targets", probeAssignedTargetBody(t, "probe-host")))+ if rec.Code != http.StatusPaymentRequired {+ t.Fatalf("HandleAdd status = %d, want 402; body=%s", rec.Code, rec.Body.String())+ }+ var payload map[string]any+ if err := json.NewDecoder(rec.Body).Decode(&payload); err != nil {+ t.Fatalf("decode 402 payload: %v", err)+ }+ if payload["error"] != "license_required" || payload["feature"] != featureExternalProbeValue {+ t.Fatalf("402 payload = %+v, want the canonical license_required shape", payload)+ }++ targets, err := persistence.LoadAvailabilityTargets()+ if err != nil {+ t.Fatalf("LoadAvailabilityTargets() error = %v", err)+ }+ if len(targets) != 0 {+ t.Fatalf("persisted targets = %+v, want none", targets)+ }+}++func TestAvailabilityHandlersAcceptProbeAssignmentWithLicense(t *testing.T) {+ persistence := config.NewConfigPersistence(t.TempDir())+ monitor := monitorWithHostAgent(t, "probe-host")+ handler := NewAvailabilityHandlers(+ func(context.Context) *config.ConfigPersistence { return persistence },+ func(context.Context) *monitoring.Monitor { return monitor },+ stubFeatureResolver(featureExternalProbeValue),+ )++ rec := httptest.NewRecorder()+ handler.HandleAdd(rec, httptest.NewRequest(http.MethodPost, "/api/availability-targets", probeAssignedTargetBody(t, "probe-host")))+ if rec.Code != http.StatusCreated {+ t.Fatalf("HandleAdd status = %d, want 201; body=%s", rec.Code, rec.Body.String())+ }+ var created config.AvailabilityTarget+ if err := json.NewDecoder(rec.Body).Decode(&created); err != nil {+ t.Fatalf("decode created target: %v", err)+ }+ if created.ProbeAgentID != "probe-host" {+ t.Fatalf("created ProbeAgentID = %q, want probe-host", created.ProbeAgentID)+ }++ // Reassignment to an unknown agent is rejected even while licensed.+ updated := created+ updated.ProbeAgentID = "ghost-agent"+ updateRec := httptest.NewRecorder()+ handler.HandleUpdate(updateRec, httptest.NewRequest(http.MethodPut, "/api/availability-targets/"+created.ID, availabilityRequestBody(t, updated)))+ if updateRec.Code != http.StatusBadRequest {+ t.Fatalf("HandleUpdate status = %d, want 400; body=%s", updateRec.Code, updateRec.Body.String())+ }++ // Clearing the assignment returns the target to local execution. The wire+ // field is omitempty, so the client has to send it explicitly.+ clearBody := bytes.NewReader([]byte(`{"probeAgentId":""}`))+ clearRec := httptest.NewRecorder()+ handler.HandleUpdate(clearRec, httptest.NewRequest(http.MethodPut, "/api/availability-targets/"+created.ID, clearBody))+ if clearRec.Code != http.StatusOK {+ t.Fatalf("HandleUpdate status = %d, want 200; body=%s", clearRec.Code, clearRec.Body.String())+ }+ stored, err := persistence.LoadAvailabilityTargets()+ if err != nil {+ t.Fatalf("LoadAvailabilityTargets() error = %v", err)+ }+ if len(stored) != 1 || stored[0].ProbeAgentID != "" {+ t.Fatalf("stored targets = %+v, want a locally executed target", stored)+ }+}++func TestAvailabilityHandlersRejectUnknownProbeAgent(t *testing.T) {+ persistence := config.NewConfigPersistence(t.TempDir())+ monitor := monitorWithHostAgent(t, "probe-host")+ handler := NewAvailabilityHandlers(+ func(context.Context) *config.ConfigPersistence { return persistence },+ func(context.Context) *monitoring.Monitor { return monitor },+ stubFeatureResolver(featureExternalProbeValue),+ )++ rec := httptest.NewRecorder()+ handler.HandleAdd(rec, httptest.NewRequest(http.MethodPost, "/api/availability-targets", probeAssignedTargetBody(t, "not-registered")))+ if rec.Code != http.StatusBadRequest {+ t.Fatalf("HandleAdd status = %d, want 400; body=%s", rec.Code, rec.Body.String())+ }+ var payload map[string]any+ if err := json.NewDecoder(rec.Body).Decode(&payload); err != nil {+ t.Fatalf("decode 400 payload: %v", err)+ }+ if payload["code"] != "unknown_probe_agent" {+ t.Fatalf("400 payload = %+v, want unknown_probe_agent", payload)+ }+}++func TestAvailabilityHandlersLocalTargetsNeverConsultLicense(t *testing.T) {+ persistence := config.NewConfigPersistence(t.TempDir())+ resolver := availabilityFeatureResolverFunc(func(context.Context) licenseFeatureChecker {+ t.Fatal("locally executed availability targets must not consult the license service")+ return nil+ })+ handler := NewAvailabilityHandlers(+ func(context.Context) *config.ConfigPersistence { return persistence },+ func(context.Context) *monitoring.Monitor { return nil },+ resolver,+ )++ createRec := httptest.NewRecorder()+ handler.HandleAdd(createRec, httptest.NewRequest(http.MethodPost, "/api/availability-targets", availabilityRequestBody(t, config.AvailabilityTarget{+ Name: "Local gateway",+ Address: "gateway.local",+ Protocol: config.AvailabilityProbeICMP,+ Enabled: true,+ })))+ if createRec.Code != http.StatusCreated {+ t.Fatalf("HandleAdd status = %d, want 201; body=%s", createRec.Code, createRec.Body.String())+ }+ var created config.AvailabilityTarget+ if err := json.NewDecoder(createRec.Body).Decode(&created); err != nil {+ t.Fatalf("decode created target: %v", err)+ }++ listRec := httptest.NewRecorder()+ handler.HandleList(listRec, httptest.NewRequest(http.MethodGet, "/api/availability-targets", nil))+ if listRec.Code != http.StatusOK {+ t.Fatalf("HandleList status = %d, want 200; body=%s", listRec.Code, listRec.Body.String())+ }++ created.Enabled = false+ updateRec := httptest.NewRecorder()+ handler.HandleUpdate(updateRec, httptest.NewRequest(http.MethodPut, "/api/availability-targets/"+created.ID, availabilityRequestBody(t, created)))+ if updateRec.Code != http.StatusOK {+ t.Fatalf("HandleUpdate status = %d, want 200; body=%s", updateRec.Code, updateRec.Body.String())+ }++ deleteRec := httptest.NewRecorder()+ handler.HandleDelete(deleteRec, httptest.NewRequest(http.MethodDelete, "/api/availability-targets/"+created.ID, nil))+ if deleteRec.Code != http.StatusOK {+ t.Fatalf("HandleDelete status = %d, want 200; body=%s", deleteRec.Code, deleteRec.Body.String())+ }+}++func TestSanitizeHostAgentConfigForTokenKeepsProbeTargetsForReportOnlyToken(t *testing.T) {+ targets := []map[string]interface{}{{"id": "remote", "address": "gateway.branch.local"}}+ commandsEnabled := true+ cfg := monitoring.HostAgentConfig{+ CommandsEnabled: &commandsEnabled,+ Settings: map[string]interface{}{"availabilityTargets": targets},+ }+ record := &config.APITokenRecord{+ ID: "report-only",+ Scopes: []string{config.ScopeAgentReport},+ Metadata: map[string]string{"bound_agent_id": "probe-host"},+ }++ sanitized := sanitizeHostAgentConfigForToken(cfg, record, models.Host{ID: "probe-host", Hostname: "probe-host"})+ if sanitized.CommandsEnabled == nil || *sanitized.CommandsEnabled {+ t.Fatalf("commands enabled = %+v, want disabled for a report-only token", sanitized.CommandsEnabled)+ }+ if got, ok := sanitized.Settings["availabilityTargets"].([]map[string]interface{}); !ok || len(got) != 1 || got[0]["id"] != "remote" {+ t.Fatalf("sanitized settings = %+v, want the bound host's own probe targets", sanitized.Settings)+ }+}diff --git a/internal/api/router.go b/internal/api/router.goindex 60167fac6c..aead8f12d5 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -496,6 +496,19 @@ func (r *Router) setupRoutes() {r.availabilityHandlers = NewAvailabilityHandlers(r.configHandlers.getPersistence,r.configHandlers.getMonitor,+ // Resolved lazily: license handlers are constructed after this point.+ availabilityFeatureResolverFunc(func(ctx context.Context) licenseFeatureChecker {+ if r.licenseHandlers == nil {+ return nil+ }+ // Service() rather than FeatureService() so an absent tenant+ // service stays a nil interface instead of a typed nil.+ service := r.licenseHandlers.Service(ctx)+ if service == nil {+ return nil+ }+ return service+ }),)recoveryManager := recoverymanager.New(r.multiTenant)r.recoveryHandlers = NewRecoveryHandlers(recoveryManager)@@ -948,6 +961,16 @@ func (r *Router) setupRoutes() {return licSvc.HasFeature(feature)})}+ // Wire license checker for monitoring Pro features (external probes).+ // The checker is consulted per read, so an entitlement lapse converges+ // on the next polling cycle without a restart.+ monitorLicSvc := r.licenseHandlers.Service(context.Background())+ r.monitor.SetLicenseChecker(func(feature string) bool {+ if monitorLicSvc == nil {+ return false+ }+ return monitorLicSvc.HasFeature(feature)+ })}// Initialize recovery token store and capture the exact worker this router owns.diff --git a/internal/config/availability.go b/internal/config/availability.goindex be9e8aeced..42b0655577 100644--- a/internal/config/availability.go+++ b/internal/config/availability.go@@ -64,6 +64,10 @@ type AvailabilityTarget struct {TimeoutMillis int `json:"timeoutMillis,omitempty"`FailureThreshold int `json:"failureThreshold,omitempty"`LinkedResourceID string `json:"linkedResourceId,omitempty"`+ // ProbeAgentID assigns execution to a remote host agent. Empty means the+ // check runs from the local Pulse instance. Agent existence is validated at+ // the API layer, not here, because config has no view of monitor state.+ ProbeAgentID string `json:"probeAgentId,omitempty"`}// NewAvailabilityTarget returns a new target with generated ID and defaults.@@ -265,6 +269,7 @@ func NormalizeAvailabilityTarget(target AvailabilityTarget) AvailabilityTarget {target.UDPExpected = ""}target.LinkedResourceID = strings.TrimSpace(target.LinkedResourceID)+ target.ProbeAgentID = strings.TrimSpace(target.ProbeAgentID)target.ApplyDefaults()return target}diff --git a/internal/config/availability_test.go b/internal/config/availability_test.goindex 62b819ebf4..ed8ce09a15 100644--- a/internal/config/availability_test.go+++ b/internal/config/availability_test.go@@ -161,3 +161,73 @@ func TestAvailabilityTargetsRoundTripThroughPersistence(t *testing.T) {t.Fatalf("poll interval = %d, want default", loaded[0].PollIntervalSecs)}}++func TestNormalizeAvailabilityTargetTrimsProbeAgentID(t *testing.T) {+ target := NormalizeAvailabilityTarget(AvailabilityTarget{+ Address: "device.local",+ Protocol: AvailabilityProbeICMP,+ Enabled: true,+ ProbeAgentID: " agent-remote-1 ",+ })++ if target.ProbeAgentID != "agent-remote-1" {+ t.Fatalf("ProbeAgentID = %q, want agent-remote-1", target.ProbeAgentID)+ }++ local := NormalizeAvailabilityTarget(AvailabilityTarget{+ Address: "device.local",+ Protocol: AvailabilityProbeICMP,+ Enabled: true,+ ProbeAgentID: " ",+ })+ if local.ProbeAgentID != "" {+ t.Fatalf("ProbeAgentID = %q, want empty for a locally executed target", local.ProbeAgentID)+ }+ if err := local.Validate(); err != nil {+ t.Fatalf("Validate() error = %v, want probe assignment to stay an API-layer concern", err)+ }+}++func TestAvailabilityTargetProbeAgentIDRoundTripsThroughPersistence(t *testing.T) {+ persistence := NewConfigPersistence(t.TempDir())+ targets := []AvailabilityTarget{+ {+ ID: "endpoint-remote",+ Name: "Remote branch gateway",+ TargetKind: AvailabilityTargetDevice,+ Address: "gateway.branch.local",+ Protocol: AvailabilityProbeICMP,+ Enabled: true,+ ProbeAgentID: " agent-branch ",+ },+ {+ ID: "endpoint-local",+ Name: "Local gateway",+ Address: "gateway.local",+ Protocol: AvailabilityProbeICMP,+ Enabled: true,+ },+ }++ if err := persistence.SaveAvailabilityTargets(targets); err != nil {+ t.Fatalf("SaveAvailabilityTargets() error = %v", err)+ }++ loaded, err := persistence.LoadAvailabilityTargets()+ if err != nil {+ t.Fatalf("LoadAvailabilityTargets() error = %v", err)+ }+ if len(loaded) != 2 {+ t.Fatalf("LoadAvailabilityTargets() length = %d, want 2", len(loaded))+ }+ byID := map[string]AvailabilityTarget{}+ for _, target := range loaded {+ byID[target.ID] = target+ }+ if got := byID["endpoint-remote"].ProbeAgentID; got != "agent-branch" {+ t.Fatalf("persisted ProbeAgentID = %q, want agent-branch", got)+ }+ if got := byID["endpoint-local"].ProbeAgentID; got != "" {+ t.Fatalf("local target ProbeAgentID = %q, want empty", got)+ }+}diff --git a/internal/monitoring/availability_poller.go b/internal/monitoring/availability_poller.goindex 78e8267408..1817fdbed9 100644--- a/internal/monitoring/availability_poller.go+++ b/internal/monitoring/availability_poller.go@@ -32,6 +32,7 @@ type AvailabilityProbeStatus struct {ConsecutiveFailures int `json:"consecutiveFailures,omitempty"`LastError string `json:"lastError,omitempty"`FailureThreshold int `json:"failureThreshold,omitempty"`+ ProbeAgentID string `json:"probeAgentId,omitempty"`}// AvailabilityProbeOutcome and its values are aliases for the shared probe@@ -61,6 +62,12 @@ func (availabilityPollProvider) ListInstances(m *Monitor) []string {if !target.Enabled {continue}+ // A licensed probe assignment moves execution to the agent. When the+ // entitlement lapses the effective assignment collapses to local, and+ // the next polling cycle re-plans this instance without a restart.+ if m.effectiveProbeAgentID(target) != "" {+ continue+ }names = append(names, target.ID)}sort.Strings(names)@@ -95,6 +102,11 @@ func (availabilityPollProvider) BuildPollTask(m *Monitor, instanceName string) (if !ok || !target.Enabled {return PollTask{}, fmt.Errorf("availability target %q is not enabled", instanceName)}+ // Refuse the local run even for a queue entry scheduled before the target+ // was assigned, so a probe-assigned target never executes twice.+ if agentID := m.effectiveProbeAgentID(target); agentID != "" {+ return PollTask{}, fmt.Errorf("availability target %q is assigned to probe agent %q", instanceName, agentID)+ }return PollTask{InstanceName: target.ID,InstanceType: string(InstanceTypeAvailability),@@ -125,7 +137,7 @@ func (availabilityPollProvider) DescribeInstances(m *Monitor) []PollProviderInst}func (availabilityPollProvider) ConnectionStatuses(m *Monitor) map[string]bool {- statuses := m.AvailabilityStatusSnapshot()+ statuses := m.availabilityStatusSnapshotForTargets(m.availabilityTargets(), time.Now())out := make(map[string]bool, len(statuses))for targetID, status := range statuses {out[availabilityConnectionKey(targetID)] = status.Enabled && status.Available@@ -143,13 +155,13 @@ func (availabilityPollProvider) SupplementalSource() unifiedresources.DataSourcefunc (availabilityPollProvider) SupplementalRecords(m *Monitor, orgID string) []unifiedresources.IngestRecord {targets := m.availabilityTargets()- statuses := m.AvailabilityStatusSnapshot()- records := make([]unifiedresources.IngestRecord, 0, len(targets))now := time.Now().UTC()+ statuses := m.availabilityStatusSnapshotForTargets(targets, now)+ records := make([]unifiedresources.IngestRecord, 0, len(targets))for _, target := range targets {status := statuses[target.ID]if status.TargetID == "" {- status = availabilityStatusFromTarget(target)+ status = m.deriveAvailabilityProbeStaleness(target, availabilityStatusFromTarget(target), now)}resource, identity := availabilityResourceFromTarget(target, status, orgID, now)records = append(records, unifiedresources.IngestRecord{@@ -201,16 +213,34 @@ func (m *Monitor) availabilityTargetByID(id string) (config.AvailabilityTarget,return config.AvailabilityTarget{}, false}+// AvailabilityStatusSnapshot is the single read path every availability+// consumer flows through, so probe staleness is derived here once instead of+// being re-implemented per reader.func (m *Monitor) AvailabilityStatusSnapshot() map[string]AvailabilityProbeStatus {+ if m == nil {+ return nil+ }+ return m.availabilityStatusSnapshotForTargets(m.availabilityTargets(), time.Now())+}++func (m *Monitor) availabilityStatusSnapshotForTargets(targets []config.AvailabilityTarget, now time.Time) map[string]AvailabilityProbeStatus {if m == nil {return nil}m.mu.RLock()- defer m.mu.RUnlock()out := make(map[string]AvailabilityProbeStatus, len(m.availabilityStatuses))for id, status := range m.availabilityStatuses {out[id] = status}+ m.mu.RUnlock()++ for _, target := range targets {+ status, ok := out[target.ID]+ if !ok {+ continue+ }+ out[target.ID] = m.deriveAvailabilityProbeStaleness(target, status, now)+ }return out}@@ -232,7 +262,7 @@ func (m *Monitor) RefreshAvailabilityTargets() {NextRun: now,Interval: clampInterval(time.Duration(target.EffectivePollIntervalSecs())*time.Second, 10*time.Second, time.Hour),}- if target.Enabled {+ if target.Enabled && m.effectiveProbeAgentID(target) == "" {m.taskQueue.Upsert(task)} else {m.taskQueue.Remove(InstanceTypeAvailability, target.ID)@@ -263,30 +293,45 @@ func (m *Monitor) pollAvailabilityTarget(ctx context.Context, target config.Avaioutcome, err := ProbeAvailabilityTargetResult(ctx, target)latency := time.Since(start)checkedAt := time.Now().UTC()- m.setAvailabilityStatus(target, checkedAt, latency, outcome, err)+ m.applyAvailabilityObservation(target, checkedAt, latency, outcome, err, "")+ m.updateResourceStore(m.GetState())+}++// applyAvailabilityObservation records one availability observation regardless of+// where it executed, so remote probe results and local polls share failure+// accounting, connection health, and task bookkeeping.+func (m *Monitor) applyAvailabilityObservation(+ target config.AvailabilityTarget,+ checkedAt time.Time,+ latency time.Duration,+ outcome AvailabilityProbeOutcome,+ probeErr error,+ probeAgentID string,+) {+ m.setAvailabilityStatus(target, checkedAt, latency, outcome, probeErr, probeAgentID)- if err == nil {+ if probeErr == nil {if m.stalenessTracker != nil {m.stalenessTracker.UpdateSuccess(InstanceTypeAvailability, target.ID, nil)}m.setProviderConnectionHealth(InstanceTypeAvailability, target.ID, true)} else {if m.stalenessTracker != nil {- m.stalenessTracker.UpdateSuccess(InstanceTypeAvailability, target.ID, []byte(err.Error()))+ m.stalenessTracker.UpdateSuccess(InstanceTypeAvailability, target.ID, []byte(probeErr.Error()))}m.setProviderConnectionHealth(InstanceTypeAvailability, target.ID, false)}m.recordTaskResult(InstanceTypeAvailability, target.ID, nil)- m.updateResourceStore(m.GetState())}-func (m *Monitor) setAvailabilityStatus(target config.AvailabilityTarget, checkedAt time.Time, latency time.Duration, outcome AvailabilityProbeOutcome, probeErr error) {+func (m *Monitor) setAvailabilityStatus(target config.AvailabilityTarget, checkedAt time.Time, latency time.Duration, outcome AvailabilityProbeOutcome, probeErr error, probeAgentID string) {if m == nil {return}status := availabilityStatusFromTarget(target)status.Outcome = string(outcome)status.LastChecked = checkedAt+ status.ProbeAgentID = strings.TrimSpace(probeAgentID)latencyMs := latency.Milliseconds()if probeErr == nil && latencyMs == 0 {latencyMs = 1diff --git a/internal/monitoring/availability_probe_agent.go b/internal/monitoring/availability_probe_agent.gonew file mode 100644index 0000000000..1bffe60ac4--- /dev/null+++ b/internal/monitoring/availability_probe_agent.go@@ -0,0 +1,204 @@+package monitoring++import (+ "errors"+ "strings"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/availabilityprobe"+ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"+ "github.com/rs/zerolog/log"+)++// availabilityProbeStaleFloor is the shortest window after which a probe-assigned+// target without a fresh report reads as indeterminate.+const availabilityProbeStaleFloor = 5 * time.Minute++// availabilityProbeStaleError is the single read-time explanation shown when an+// assigned agent stops reporting.+const availabilityProbeStaleError = "no recent report from probe agent"++// ProbeAvailabilityResult is one availability observation reported by a remote+// host agent that owns the target's execution.+type ProbeAvailabilityResult struct {+ TargetID string+ Outcome availabilityprobe.Outcome+ LatencyMillis int64+ CheckedAt time.Time+ Error string+}++// effectiveProbeAgentID returns the host agent that currently owns execution of+// the target. It collapses to local execution ("") whenever the external probe+// entitlement is absent, so a license lapse resumes local polling instead of+// stranding the check on an agent that is no longer allowed to run it.+func (m *Monitor) effectiveProbeAgentID(target config.AvailabilityTarget) string {+ assigned := strings.TrimSpace(target.ProbeAgentID)+ if assigned == "" {+ return ""+ }+ if !m.hasLicensedFeature(pkglicensing.FeatureExternalProbe) {+ return ""+ }+ return assigned+}++// ApplyProbeAvailabilityResults ingests availability results reported by a host+// agent. Results are accepted only for targets currently assigned to that agent.+func (m *Monitor) ApplyProbeAvailabilityResults(hostID string, results []ProbeAvailabilityResult) {+ if m == nil {+ return+ }+ hostID = strings.TrimSpace(hostID)+ if hostID == "" || len(results) == 0 {+ return+ }++ applied := 0+ for _, result := range results {+ targetID := strings.TrimSpace(result.TargetID)+ if targetID == "" {+ continue+ }+ target, ok := m.availabilityTargetByID(targetID)+ if !ok {+ log.Debug().+ Str("hostID", hostID).+ Str("targetID", targetID).+ Msg("Rejecting probe availability result for unknown target")+ continue+ }+ if m.effectiveProbeAgentID(target) != hostID {+ log.Debug().+ Str("hostID", hostID).+ Str("targetID", targetID).+ Msg("Rejecting probe availability result from an agent that does not own the target")+ continue+ }++ checkedAt := result.CheckedAt+ if checkedAt.IsZero() {+ checkedAt = time.Now()+ }+ latency := time.Duration(result.LatencyMillis) * time.Millisecond+ if latency < 0 {+ latency = 0+ }+ outcome, probeErr := probeResultOutcome(result)+ m.applyAvailabilityObservation(target, checkedAt.UTC(), latency, outcome, probeErr, hostID)+ applied+++ }++ if applied == 0 {+ return+ }+ m.updateResourceStore(m.GetState())+}++// probeResultOutcome normalizes a reported outcome and derives the failure+// signal. An unreachable report without a message still has to fail, otherwise+// remote checks would never accumulate consecutive failures.+func probeResultOutcome(result ProbeAvailabilityResult) (AvailabilityProbeOutcome, error) {+ outcome := AvailabilityProbeOutcome(strings.ToLower(strings.TrimSpace(string(result.Outcome))))+ message := strings.TrimSpace(result.Error)+ switch outcome {+ case AvailabilityProbeReachable, AvailabilityProbeUnreachable, AvailabilityProbeIndeterminate:+ default:+ if message != "" {+ outcome = AvailabilityProbeUnreachable+ } else {+ outcome = AvailabilityProbeIndeterminate+ }+ }+ if outcome == AvailabilityProbeUnreachable {+ if message == "" {+ message = "probe agent reported the target unreachable"+ }+ return outcome, errors.New(message)+ }+ if message != "" {+ return AvailabilityProbeUnreachable, errors.New(message)+ }+ return outcome, nil+}++// deriveAvailabilityProbeStaleness reports the status a reader should see for a+// probe-assigned target. Stored state is never mutated: an agent that stops+// reporting must read as indeterminate without erasing its last observation.+func (m *Monitor) deriveAvailabilityProbeStaleness(+ target config.AvailabilityTarget,+ status AvailabilityProbeStatus,+ now time.Time,+) AvailabilityProbeStatus {+ if m.effectiveProbeAgentID(target) == "" {+ return status+ }+ if !availabilityProbeReportIsStale(target, status.LastChecked, now) {+ return status+ }+ status.Outcome = string(AvailabilityProbeIndeterminate)+ status.Available = false+ status.LastError = availabilityProbeStaleError+ status.LatencyMillis = 0+ return status+}++func availabilityProbeReportIsStale(target config.AvailabilityTarget, lastChecked time.Time, now time.Time) bool {+ if lastChecked.IsZero() {+ return true+ }+ window := time.Duration(target.EffectivePollIntervalSecs()) * 3 * time.Second+ if window < availabilityProbeStaleFloor {+ window = availabilityProbeStaleFloor+ }+ return now.Sub(lastChecked) > window+}++// availabilityProbeTargetsForAgent returns the probe payload for the targets the+// given agent currently owns.+func (m *Monitor) availabilityProbeTargetsForAgent(hostID string) []map[string]interface{} {+ hostID = strings.TrimSpace(hostID)+ if hostID == "" {+ return nil+ }+ var assigned []map[string]interface{}+ for _, target := range m.availabilityTargets() {+ if m.effectiveProbeAgentID(target) != hostID {+ continue+ }+ assigned = append(assigned, availabilityProbeAgentTargetPayload(target))+ }+ return assigned+}++// availabilityProbeAgentTargetPayload carries only what the agent needs to run+// the check. Failure accounting and resource linkage stay server-side.+func availabilityProbeAgentTargetPayload(target config.AvailabilityTarget) map[string]interface{} {+ payload := map[string]interface{}{+ "id": target.ID,+ "name": target.DisplayName(),+ "targetKind": string(target.TargetKind),+ "address": target.Address,+ "protocol": string(target.Protocol),+ "enabled": target.Enabled,+ "pollIntervalSeconds": target.EffectivePollIntervalSecs(),+ "timeoutMillis": target.EffectiveTimeoutMillis(),+ }+ if target.Port > 0 {+ payload["port"] = target.Port+ }+ if path := strings.TrimSpace(target.Path); path != "" {+ payload["path"] = path+ }+ if target.UDPMode != "" {+ payload["udpMode"] = string(target.UDPMode)+ }+ if target.UDPRequest != "" {+ payload["udpRequest"] = target.UDPRequest+ }+ if target.UDPExpected != "" {+ payload["udpExpectedResponse"] = target.UDPExpected+ }+ return payload+}diff --git a/internal/monitoring/availability_probe_agent_test.go b/internal/monitoring/availability_probe_agent_test.gonew file mode 100644index 0000000000..bcfaa536c1--- /dev/null+++ b/internal/monitoring/availability_probe_agent_test.go@@ -0,0 +1,401 @@+package monitoring++import (+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/internal/models"+ pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"+)++func newProbeAgentTestMonitor(t *testing.T, targets ...config.AvailabilityTarget) *Monitor {+ t.Helper()+ persistence := config.NewConfigPersistence(t.TempDir())+ normalized := make([]config.AvailabilityTarget, 0, len(targets))+ for _, target := range targets {+ normalized = append(normalized, config.NormalizeAvailabilityTarget(target))+ }+ if err := persistence.SaveAvailabilityTargets(normalized); err != nil {+ t.Fatalf("SaveAvailabilityTargets() error = %v", err)+ }+ return &Monitor{+ state: models.NewState(),+ configPersist: persistence,+ availabilityStatuses: make(map[string]AvailabilityProbeStatus),+ pollStatusMap: make(map[string]*pollStatus),+ failureCounts: make(map[string]int),+ lastOutcome: make(map[string]taskOutcome),+ circuitBreakers: make(map[string]*circuitBreaker),+ taskQueue: NewTaskQueue(),+ }+}++func licenseWithExternalProbe(enabled bool) func(string) bool {+ return func(feature string) bool {+ return enabled && feature == pkglicensing.FeatureExternalProbe+ }+}++func probeAgentTarget(id string, agentID string) config.AvailabilityTarget {+ return config.AvailabilityTarget{+ ID: id,+ Name: id,+ Address: id + ".local",+ Protocol: config.AvailabilityProbeICMP,+ Enabled: true,+ PollIntervalSecs: 60,+ FailureThreshold: 2,+ ProbeAgentID: agentID,+ }+}++func TestEffectiveProbeAgentIDRequiresEntitlement(t *testing.T) {+ monitor := newProbeAgentTestMonitor(t)+ assigned := config.NormalizeAvailabilityTarget(probeAgentTarget("remote", "agent-1"))+ local := config.NormalizeAvailabilityTarget(probeAgentTarget("local", ""))++ if got := monitor.effectiveProbeAgentID(assigned); got != "" {+ t.Fatalf("effectiveProbeAgentID() = %q without a license checker, want empty", got)+ }++ monitor.SetLicenseChecker(licenseWithExternalProbe(true))+ if got := monitor.effectiveProbeAgentID(assigned); got != "agent-1" {+ t.Fatalf("effectiveProbeAgentID() = %q, want agent-1", got)+ }+ if got := monitor.effectiveProbeAgentID(local); got != "" {+ t.Fatalf("effectiveProbeAgentID() = %q for an unassigned target, want empty", got)+ }++ monitor.SetLicenseChecker(licenseWithExternalProbe(false))+ if got := monitor.effectiveProbeAgentID(assigned); got != "" {+ t.Fatalf("effectiveProbeAgentID() = %q after a lapse, want empty", got)+ }+}++func TestAvailabilityPollProviderSkipsProbeAssignedTargetsAndResumesOnLapse(t *testing.T) {+ monitor := newProbeAgentTestMonitor(t,+ probeAgentTarget("remote", "agent-1"),+ probeAgentTarget("local", ""),+ )+ monitor.SetLicenseChecker(licenseWithExternalProbe(true))++ names := availabilityPollProvider{}.ListInstances(monitor)+ if len(names) != 1 || names[0] != "local" {+ t.Fatalf("ListInstances() = %+v, want only the locally executed target", names)+ }+ if _, err := (availabilityPollProvider{}).BuildPollTask(monitor, "remote"); err == nil {+ t.Fatal("BuildPollTask() error = nil, want refusal for a probe-assigned target")+ }+ if _, err := (availabilityPollProvider{}).BuildPollTask(monitor, "local"); err != nil {+ t.Fatalf("BuildPollTask(local) error = %v", err)+ }++ // The entitlement lapses: the poller must resume the target without a+ // restart, on the next planning pass.+ monitor.SetLicenseChecker(licenseWithExternalProbe(false))+ names = availabilityPollProvider{}.ListInstances(monitor)+ if len(names) != 2 {+ t.Fatalf("ListInstances() after lapse = %+v, want both targets", names)+ }+ if _, err := (availabilityPollProvider{}).BuildPollTask(monitor, "remote"); err != nil {+ t.Fatalf("BuildPollTask(remote) after lapse error = %v", err)+ }+}++func TestRefreshAvailabilityTargetsUnschedulesProbeAssignedTargets(t *testing.T) {+ monitor := newProbeAgentTestMonitor(t,+ probeAgentTarget("remote", "agent-1"),+ probeAgentTarget("local", ""),+ )+ monitor.SetLicenseChecker(licenseWithExternalProbe(true))++ monitor.RefreshAvailabilityTargets()+ if depth := monitor.taskQueue.Snapshot().Depth; depth != 1 {+ t.Fatalf("queue depth = %d, want only the locally executed target", depth)+ }++ monitor.SetLicenseChecker(licenseWithExternalProbe(false))+ monitor.RefreshAvailabilityTargets()+ if depth := monitor.taskQueue.Snapshot().Depth; depth != 2 {+ t.Fatalf("queue depth after lapse = %d, want both targets scheduled locally", depth)+ }+}++func TestGetHostAgentConfigIncludesOnlyOwnAssignedTargets(t *testing.T) {+ monitor := newProbeAgentTestMonitor(t,+ probeAgentTarget("remote-a", "agent-1"),+ probeAgentTarget("remote-b", "agent-2"),+ probeAgentTarget("local", ""),+ )+ monitor.SetLicenseChecker(licenseWithExternalProbe(true))++ cfg := monitor.GetHostAgentConfig("agent-1")+ raw, ok := cfg.Settings["availabilityTargets"]+ if !ok {+ t.Fatalf("settings = %+v, want availabilityTargets", cfg.Settings)+ }+ payload, ok := raw.([]map[string]interface{})+ if !ok {+ t.Fatalf("availabilityTargets type = %T, want []map[string]interface{}", raw)+ }+ if len(payload) != 1 || payload[0]["id"] != "remote-a" {+ t.Fatalf("availabilityTargets = %+v, want only remote-a", payload)+ }+ for _, forbidden := range []string{"failureThreshold", "linkedResourceId", "probeAgentId"} {+ if _, present := payload[0][forbidden]; present {+ t.Fatalf("availability target payload leaked %q: %+v", forbidden, payload[0])+ }+ }+ if cfg.DesiredConfig == nil {+ t.Fatal("desired config metadata = nil, want signed config metadata")+ }++ if cfg := monitor.GetHostAgentConfig("agent-3"); cfg.Settings["availabilityTargets"] != nil {+ t.Fatalf("unassigned agent settings = %+v, want no availabilityTargets key", cfg.Settings)+ }++ monitor.SetLicenseChecker(licenseWithExternalProbe(false))+ if cfg := monitor.GetHostAgentConfig("agent-1"); cfg.Settings["availabilityTargets"] != nil {+ t.Fatalf("unlicensed settings = %+v, want no availabilityTargets key", cfg.Settings)+ }+}++func TestGetHostAgentConfigPayloadCarriesProbeParameters(t *testing.T) {+ monitor := newProbeAgentTestMonitor(t, config.AvailabilityTarget{+ ID: "udp-check",+ Name: "UDP check",+ TargetKind: config.AvailabilityTargetDevice,+ Address: "sensor.local",+ Protocol: config.AvailabilityProbeUDP,+ Port: 5353,+ UDPMode: config.AvailabilityUDPResponseRequired,+ UDPRequest: "ping",+ UDPExpected: "pong",+ Enabled: true,+ PollIntervalSecs: 45,+ TimeoutMillis: 1500,+ ProbeAgentID: "agent-1",+ })+ monitor.SetLicenseChecker(licenseWithExternalProbe(true))++ payload := monitor.availabilityProbeTargetsForAgent("agent-1")+ if len(payload) != 1 {+ t.Fatalf("payload = %+v, want one target", payload)+ }+ want := map[string]interface{}{+ "id": "udp-check",+ "name": "UDP check",+ "targetKind": string(config.AvailabilityTargetDevice),+ "address": "sensor.local",+ "protocol": string(config.AvailabilityProbeUDP),+ "port": 5353,+ "udpMode": string(config.AvailabilityUDPResponseRequired),+ "udpRequest": "ping",+ "udpExpectedResponse": "pong",+ "enabled": true,+ "pollIntervalSeconds": 45,+ "timeoutMillis": 1500,+ }+ for key, expected := range want {+ if got := payload[0][key]; got != expected {+ t.Fatalf("payload[%q] = %v, want %v", key, got, expected)+ }+ }+ if len(payload[0]) != len(want) {+ t.Fatalf("payload keys = %+v, want exactly %d probe parameters", payload[0], len(want))+ }+}++func TestApplyProbeAvailabilityResultsRejectsForeignAgents(t *testing.T) {+ monitor := newProbeAgentTestMonitor(t,+ probeAgentTarget("remote", "agent-1"),+ probeAgentTarget("local", ""),+ )+ monitor.SetLicenseChecker(licenseWithExternalProbe(true))++ checkedAt := time.Now().UTC()+ monitor.ApplyProbeAvailabilityResults("agent-2", []ProbeAvailabilityResult{+ {TargetID: "remote", Outcome: AvailabilityProbeReachable, LatencyMillis: 5, CheckedAt: checkedAt},+ {TargetID: "local", Outcome: AvailabilityProbeReachable, LatencyMillis: 5, CheckedAt: checkedAt},+ {TargetID: "missing", Outcome: AvailabilityProbeReachable, LatencyMillis: 5, CheckedAt: checkedAt},+ })+ if statuses := monitor.AvailabilityStatusSnapshot(); len(statuses) != 0 {+ t.Fatalf("statuses = %+v, want no state from an agent that owns nothing", statuses)+ }++ // The owning agent may not claim a locally executed target either.+ monitor.ApplyProbeAvailabilityResults("agent-1", []ProbeAvailabilityResult{+ {TargetID: "local", Outcome: AvailabilityProbeReachable, LatencyMillis: 5, CheckedAt: checkedAt},+ })+ if _, ok := monitor.AvailabilityStatusSnapshot()["local"]; ok {+ t.Fatal("locally executed target accepted a probe agent result")+ }++ // A lapsed entitlement withdraws ownership too.+ monitor.SetLicenseChecker(licenseWithExternalProbe(false))+ monitor.ApplyProbeAvailabilityResults("agent-1", []ProbeAvailabilityResult{+ {TargetID: "remote", Outcome: AvailabilityProbeReachable, LatencyMillis: 5, CheckedAt: checkedAt},+ })+ if _, ok := monitor.AvailabilityStatusSnapshot()["remote"]; ok {+ t.Fatal("unlicensed probe agent result was accepted")+ }+}++func TestApplyProbeAvailabilityResultsAccountsFailuresAndAttribution(t *testing.T) {+ monitor := newProbeAgentTestMonitor(t, probeAgentTarget("remote", "agent-1"))+ monitor.SetLicenseChecker(licenseWithExternalProbe(true))++ checkedAt := time.Now().UTC()+ monitor.ApplyProbeAvailabilityResults("agent-1", []ProbeAvailabilityResult{+ {TargetID: "remote", Outcome: AvailabilityProbeReachable, LatencyMillis: 12, CheckedAt: checkedAt},+ })+ status := monitor.AvailabilityStatusSnapshot()["remote"]+ if !status.Available || status.ProbeAgentID != "agent-1" {+ t.Fatalf("status = %+v, want available and attributed to agent-1", status)+ }+ if !status.LastSuccess.Equal(checkedAt) {+ t.Fatalf("last success = %v, want %v", status.LastSuccess, checkedAt)+ }+ if healthy, ok := monitor.state.GetSnapshot().ConnectionHealth["availability-remote"]; !ok || !healthy {+ t.Fatalf("connection health = %v/%v, want healthy", healthy, ok)+ }++ // Two failures reach the threshold; an unreachable report with no message+ // must still count.+ for i := 1; i <= 2; i++ {+ monitor.ApplyProbeAvailabilityResults("agent-1", []ProbeAvailabilityResult{+ {TargetID: "remote", Outcome: AvailabilityProbeUnreachable, CheckedAt: checkedAt.Add(time.Duration(i) * time.Minute)},+ })+ status = monitor.AvailabilityStatusSnapshot()["remote"]+ if status.ConsecutiveFailures != i {+ t.Fatalf("consecutive failures = %d after %d unreachable reports, want %d", status.ConsecutiveFailures, i, i)+ }+ }+ if status.Available || status.LastError == "" {+ t.Fatalf("status = %+v, want an unavailable target with an error", status)+ }+ if !status.LastSuccess.Equal(checkedAt) {+ t.Fatalf("last success = %v, want the carried-forward success %v", status.LastSuccess, checkedAt)+ }+ if healthy := monitor.state.GetSnapshot().ConnectionHealth["availability-remote"]; healthy {+ t.Fatal("connection health = healthy, want unhealthy after failures")+ }++ // A later success resets the accounting.+ recovered := checkedAt.Add(3 * time.Minute)+ monitor.ApplyProbeAvailabilityResults("agent-1", []ProbeAvailabilityResult{+ {TargetID: "remote", Outcome: AvailabilityProbeReachable, LatencyMillis: 8, CheckedAt: recovered},+ })+ status = monitor.AvailabilityStatusSnapshot()["remote"]+ if status.ConsecutiveFailures != 0 || status.LastError != "" || !status.Available {+ t.Fatalf("status = %+v, want a recovered target", status)+ }+ if !status.LastSuccess.Equal(recovered) {+ t.Fatalf("last success = %v, want %v", status.LastSuccess, recovered)+ }+}++func TestApplyProbeAvailabilityResultsIndeterminateClearsFailures(t *testing.T) {+ monitor := newProbeAgentTestMonitor(t, probeAgentTarget("remote", "agent-1"))+ monitor.SetLicenseChecker(licenseWithExternalProbe(true))++ checkedAt := time.Now().UTC()+ monitor.ApplyProbeAvailabilityResults("agent-1", []ProbeAvailabilityResult{+ {TargetID: "remote", Outcome: AvailabilityProbeUnreachable, Error: "icmp probe timed out", CheckedAt: checkedAt},+ })+ monitor.ApplyProbeAvailabilityResults("agent-1", []ProbeAvailabilityResult{+ {TargetID: "remote", Outcome: AvailabilityProbeIndeterminate, CheckedAt: checkedAt.Add(time.Minute)},+ })++ status := monitor.AvailabilityStatusSnapshot()["remote"]+ if status.ConsecutiveFailures != 0 {+ t.Fatalf("consecutive failures = %d after an indeterminate report, want 0", status.ConsecutiveFailures)+ }+ if status.Available {+ t.Fatalf("status = %+v, want indeterminate to stay non-available", status)+ }+ if status.Outcome != string(AvailabilityProbeIndeterminate) {+ t.Fatalf("outcome = %q, want indeterminate", status.Outcome)+ }+}++func TestAvailabilityProbeStalenessDerivesIndeterminateAtReadTime(t *testing.T) {+ target := config.NormalizeAvailabilityTarget(probeAgentTarget("remote", "agent-1"))+ monitor := newProbeAgentTestMonitor(t, target)+ monitor.SetLicenseChecker(licenseWithExternalProbe(true))++ checkedAt := time.Now().UTC()+ monitor.ApplyProbeAvailabilityResults("agent-1", []ProbeAvailabilityResult{+ {TargetID: "remote", Outcome: AvailabilityProbeReachable, LatencyMillis: 9, CheckedAt: checkedAt},+ })++ // Effective poll interval is 60s, so the floor of five minutes governs.+ fresh := monitor.availabilityStatusSnapshotForTargets([]config.AvailabilityTarget{target}, checkedAt.Add(5*time.Minute))+ if !fresh["remote"].Available || fresh["remote"].LastError != "" {+ t.Fatalf("status at the boundary = %+v, want the reported observation", fresh["remote"])+ }++ stale := monitor.availabilityStatusSnapshotForTargets([]config.AvailabilityTarget{target}, checkedAt.Add(5*time.Minute+time.Second))+ if stale["remote"].Outcome != string(AvailabilityProbeIndeterminate) {+ t.Fatalf("stale outcome = %q, want indeterminate", stale["remote"].Outcome)+ }+ if stale["remote"].Available {+ t.Fatal("stale status reported available")+ }+ if stale["remote"].LastError != availabilityProbeStaleError {+ t.Fatalf("stale last error = %q, want %q", stale["remote"].LastError, availabilityProbeStaleError)+ }++ // Stored state is untouched: the derivation is read-time only.+ monitor.mu.RLock()+ stored := monitor.availabilityStatuses["remote"]+ monitor.mu.RUnlock()+ if !stored.Available || stored.LastError != "" {+ t.Fatalf("stored status = %+v, want the unmodified observation", stored)+ }++ // A long poll interval widens the window past the floor.+ slow := target+ slow.PollIntervalSecs = 600+ slowSnapshot := monitor.availabilityStatusSnapshotForTargets([]config.AvailabilityTarget{slow}, checkedAt.Add(29*time.Minute))+ if !slowSnapshot["remote"].Available {+ t.Fatalf("status = %+v, want 3x the poll interval to govern", slowSnapshot["remote"])+ }++ // Local targets never derive probe staleness.+ monitor.SetLicenseChecker(licenseWithExternalProbe(false))+ lapsed := monitor.availabilityStatusSnapshotForTargets([]config.AvailabilityTarget{target}, checkedAt.Add(time.Hour))+ if !lapsed["remote"].Available {+ t.Fatalf("status after lapse = %+v, want local execution semantics", lapsed["remote"])+ }+}++func TestAvailabilitySupplementalRecordsPresentStaleProbeAsIndeterminate(t *testing.T) {+ monitor := newProbeAgentTestMonitor(t, probeAgentTarget("remote", "agent-1"))+ monitor.SetLicenseChecker(licenseWithExternalProbe(true))++ monitor.ApplyProbeAvailabilityResults("agent-1", []ProbeAvailabilityResult{+ {TargetID: "remote", Outcome: AvailabilityProbeReachable, LatencyMillis: 9, CheckedAt: time.Now().UTC().Add(-time.Hour)},+ })++ records := availabilityPollProvider{}.SupplementalRecords(monitor, "org-a")+ if len(records) != 1 {+ t.Fatalf("SupplementalRecords() length = %d, want 1", len(records))+ }+ data := records[0].Resource.Availability+ if data == nil {+ t.Fatal("availability payload = nil")+ }+ if data.ProbeOutcome != string(AvailabilityProbeIndeterminate) || data.Available {+ t.Fatalf("availability payload = %+v, want a stale indeterminate projection", data)+ }+ if data.LastError != availabilityProbeStaleError {+ t.Fatalf("availability last error = %q, want %q", data.LastError, availabilityProbeStaleError)+ }++ statuses := availabilityPollProvider{}.ConnectionStatuses(monitor)+ if statuses["availability-remote"] {+ t.Fatalf("connection statuses = %+v, want a stale probe to read as not connected", statuses)+ }+}diff --git a/internal/monitoring/availability_udp_test.go b/internal/monitoring/availability_udp_test.goindex 5c3e615747..e0b9327129 100644--- a/internal/monitoring/availability_udp_test.go+++ b/internal/monitoring/availability_udp_test.go@@ -86,7 +86,7 @@ func TestAvailabilityUDPIndeterminateDoesNotClaimReachabilityOrAccumulateFailure}}checkedAt := time.Now().UTC()- monitor.setAvailabilityStatus(target, checkedAt, 250*time.Millisecond, AvailabilityProbeIndeterminate, nil)+ monitor.setAvailabilityStatus(target, checkedAt, 250*time.Millisecond, AvailabilityProbeIndeterminate, nil, "")status := monitor.AvailabilityStatusSnapshot()[target.ID]if status.Available {t.Fatal("indeterminate UDP result must not be reported as reachable")diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.goindex b039c0f663..2153dfae46 100644--- a/internal/monitoring/monitor.go+++ b/internal/monitoring/monitor.go@@ -1179,6 +1179,11 @@ type Monitor struct {clusterSensorsCache map[string]clusterSensorsCacheEntrymockChartCacheMu sync.RWMutexmockChartMapCache map[mockChartMetricMapCacheKey]map[string][]MetricPoint+ // Commercial feature gate for monitoring-owned Pro behaviour (external+ // availability probes). Guarded by its own mutex so read-time derivations+ // that already hold m.mu can consult it without lock re-entrancy.+ licenseCheckerMu sync.RWMutex+ licenseChecker func(feature string) bool}func (m *Monitor) setRuntimeContext(ctx context.Context, hub *websocket.Hub) {@@ -4420,6 +4425,31 @@ func (m *Monitor) SetSupplementalRecordsProvider(source unifiedresources.DataSoum.updateResourceStore(m.GetState())}+// SetLicenseChecker wires the commercial feature gate used by monitoring-owned+// Pro behaviour. It mirrors the alert manager's checker so entitlement lookups+// stay request-free inside the polling loop.+func (m *Monitor) SetLicenseChecker(checker func(feature string) bool) {+ if m == nil {+ return+ }+ m.licenseCheckerMu.Lock()+ m.licenseChecker = checker+ m.licenseCheckerMu.Unlock()+}++func (m *Monitor) hasLicensedFeature(feature string) bool {+ if m == nil {+ return false+ }+ m.licenseCheckerMu.RLock()+ checker := m.licenseChecker+ m.licenseCheckerMu.RUnlock()+ if checker == nil {+ return false+ }+ return checker(feature)+}+// SetRecoveryManager wires the recovery store manager for best-effort ingestion of// recovery points derived from polled backup/snapshot data.func (m *Monitor) SetRecoveryManager(manager *recoverymanager.Manager) {diff --git a/internal/monitoring/monitor_agents.go b/internal/monitoring/monitor_agents.goindex e0c9833a58..052066b1fe 100644--- a/internal/monitoring/monitor_agents.go+++ b/internal/monitoring/monitor_agents.go@@ -802,6 +802,16 @@ func (m *Monitor) GetHostAgentConfig(hostID string) HostAgentConfig {}}+ // 3. Externally probed availability targets assigned to this agent. Each+ // agent only ever sees its own assignments because the payload is built+ // from this hostID.+ if targets := m.availabilityProbeTargetsForAgent(hostID); len(targets) > 0 {+ if cfg.Settings == nil {+ cfg.Settings = map[string]interface{}{}+ }+ cfg.Settings["availabilityTargets"] = targets+ }+return attachDesiredConfigMetadata(cfg)}