Skip to content

armgit / Pulse

Public Imported from GitHub
0

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

21.9 KB
Raw Blame
package unifiedresources

import (
	"fmt"
	"log"
	"reflect"
	"sort"
	"strings"
	"time"

	"github.com/google/uuid"
)

// recordRegistryChanges persists the changes between two resource lists and
// returns the ones the store accepted, so the caller can announce exactly what
// was recorded.
func recordRegistryChanges(store ResourceStore, before, after []Resource, observedAt time.Time, occurredAt *time.Time, sourceType ChangeSourceType, sourceAdapterHint ChangeSourceAdapter) []ResourceChange {
	return recordRegistryChangesSkipping(store, before, after, observedAt, occurredAt, sourceType, sourceAdapterHint, nil)
}

// recordRegistryChangesSkipping is recordRegistryChanges with a filter: a
// change skip reports true for is neither persisted nor returned, and skip may
// rewrite a change it keeps. A nil skip keeps every change unchanged.
func recordRegistryChangesSkipping(store ResourceStore, before, after []Resource, observedAt time.Time, occurredAt *time.Time, sourceType ChangeSourceType, sourceAdapterHint ChangeSourceAdapter, skip func(*ResourceChange) bool) []ResourceChange {
	if store == nil {
		return nil
	}

	beforeByID := make(map[string]Resource, len(before))
	for _, resource := range before {
		if resource.ID == "" {
			continue
		}
		beforeByID[resource.ID] = resource
	}

	afterByID := make(map[string]Resource, len(after))
	for _, resource := range after {
		if resource.ID == "" {
			continue
		}
		afterByID[resource.ID] = resource
	}

	seen := make(map[string]struct{}, len(beforeByID)+len(afterByID))
	for id := range beforeByID {
		seen[id] = struct{}{}
	}
	for id := range afterByID {
		seen[id] = struct{}{}
	}

	var recorded []ResourceChange
	for id := range seen {
		beforeResource, beforeOK := beforeByID[id]
		afterResource, afterOK := afterByID[id]
		change := buildResourceChange(beforeResource, beforeOK, afterResource, afterOK, observedAt, occurredAt, sourceType, sourceAdapterHint)
		if change == nil || (skip != nil && skip(change)) {
			continue
		}
		if err := store.RecordChange(*change); err != nil {
			log.Printf("unifiedresources: failed to record change for %s: %v", change.ResourceID, err)
			continue
		}
		recorded = append(recorded, *change)
	}
	return recorded
}

// recordRegistryChangesBetweenGenerations compares two complete registry
// generations without making the deep, sorted List clones needed by public
// readers. The resources are read only while both registry locks are held;
// persistence happens after releasing them so a slow store cannot block
// registry readers. The caller must keep the old generation stable until this
// returns (MonitorAdapter's mutationMu does so during a replacement). It
// returns the changes the store accepted.
func recordRegistryChangesBetweenGenerations(before, after *ResourceRegistry, observedAt time.Time, occurredAt *time.Time, sourceType ChangeSourceType, sourceAdapterHint ChangeSourceAdapter) []ResourceChange {
	return recordRegistryChangesBetweenGenerationsSkipping(before, after, observedAt, occurredAt, sourceType, sourceAdapterHint, nil)
}

// recordRegistryChangesBetweenGenerationsSkipping is
// recordRegistryChangesBetweenGenerations with the same skip filter as
// recordRegistryChangesSkipping. skip runs after both registry locks are
// released.
func recordRegistryChangesBetweenGenerationsSkipping(before, after *ResourceRegistry, observedAt time.Time, occurredAt *time.Time, sourceType ChangeSourceType, sourceAdapterHint ChangeSourceAdapter, skip func(*ResourceChange) bool) []ResourceChange {
	if before == nil || after == nil || before.store == nil {
		return nil
	}

	var pending []ResourceChange
	before.mu.RLock()
	after.mu.RLock()
	beforeByID := make(map[string]*Resource, len(before.resources))
	for _, resource := range before.resources {
		if resource != nil && resource.ID != "" {
			beforeByID[resource.ID] = resource
		}
	}
	afterByID := make(map[string]*Resource, len(after.resources))
	for _, resource := range after.resources {
		if resource != nil && resource.ID != "" {
			afterByID[resource.ID] = resource
		}
	}
	for id, previous := range beforeByID {
		current, exists := afterByID[id]
		var next Resource
		if exists {
			next = *current
		}
		if change := buildResourceChange(*previous, true, next, exists, observedAt, occurredAt, sourceType, sourceAdapterHint); change != nil {
			pending = append(pending, *change)
		}
	}
	for id, current := range afterByID {
		if _, exists := beforeByID[id]; exists {
			continue
		}
		if change := buildResourceChange(Resource{}, false, *current, true, observedAt, occurredAt, sourceType, sourceAdapterHint); change != nil {
			pending = append(pending, *change)
		}
	}
	after.mu.RUnlock()
	before.mu.RUnlock()

	recorded := pending[:0]
	for _, change := range pending {
		if skip != nil && skip(&change) {
			continue
		}
		if err := before.store.RecordChange(change); err != nil {
			log.Printf("unifiedresources: failed to record change for %s: %v", change.ResourceID, err)
			continue
		}
		recorded = append(recorded, change)
	}
	return recorded
}

func buildResourceChange(before Resource, beforeOK bool, after Resource, afterOK bool, observedAt time.Time, occurredAt *time.Time, sourceType ChangeSourceType, sourceAdapterHint ChangeSourceAdapter) *ResourceChange {
	if !beforeOK && !afterOK {
		return nil
	}
	var changedFields []string
	if beforeOK && afterOK {
		changedFields = resourceChangedFields(before, after)
		if len(changedFields) == 0 {
			return nil
		}
	}

	change := &ResourceChange{
		ID:            uuid.NewString(),
		ObservedAt:    observedAt,
		OccurredAt:    cloneTimePtr(occurredAt),
		Confidence:    ConfidenceHigh,
		SourceType:    sourceType,
		SourceAdapter: sourceAdapterHint,
	}

	if afterOK {
		change.ResourceID = after.ID
	} else {
		change.ResourceID = before.ID
	}
	if change.ResourceID == "" {
		return nil
	}

	if !beforeOK {
		change.Kind = ChangeStateTransition
		change.From = "absent"
		change.To = resourceStatusString(after.Status)
		change.Reason = "resource discovered"
		change.Metadata = map[string]any{"changeType": "resource_created"}
		if change.SourceAdapter == "" {
			change.SourceAdapter = resourceChangeSourceAdapter(&after)
		}
		change.RelatedResources = relatedResourceIDs(change.ResourceID, before, after)
		return change
	}

	if !afterOK {
		change.Kind = ChangeStateTransition
		change.From = resourceStatusString(before.Status)
		change.To = "absent"
		change.Reason = "resource removed"
		change.Metadata = map[string]any{"changeType": "resource_removed"}
		if change.SourceAdapter == "" {
			change.SourceAdapter = resourceChangeSourceAdapter(&before)
		}
		change.RelatedResources = relatedResourceIDs(change.ResourceID, before, after)
		return change
	}

	change.Metadata = map[string]any{"changedFields": changedFields}

	switch {
	case resourceRestartChanged(before, after):
		change.Kind = ChangeRestart
		change.From = resourceRestartSummary(before)
		change.To = resourceRestartSummary(after)
		change.Reason = "resource restart detected"
	case resourceIncidentChanged(before, after):
		change.Kind = ChangeAnomaly
		change.From = resourceIncidentSummary(before)
		change.To = resourceIncidentSummary(after)
		change.Reason = "resource incident changed"
	case before.Status != after.Status || dockerCommandChanged(before, after) || dockerUpdateStatusChanged(before, after) || proxmoxLifecycleChanged(before, after):
		change.Kind = ChangeStateTransition
		change.From = resourceStateSummary(before)
		change.To = resourceStateSummary(after)
		change.Reason = "resource state changed"
	case !equalStringPtr(before.ParentID, after.ParentID) || !relationshipsEquivalent(before.Relationships, after.Relationships):
		change.Kind = ChangeRelationship
		change.From = resourceRelationSummary(before)
		change.To = resourceRelationSummary(after)
		change.Reason = "resource relationship changed"
	case !reflect.DeepEqual(before.Capabilities, after.Capabilities):
		change.Kind = ChangeCapability
		change.From = fmt.Sprintf("%d", len(before.Capabilities))
		change.To = fmt.Sprintf("%d", len(after.Capabilities))
		change.Reason = "resource capabilities changed"
	default:
		change.Kind = ChangeConfigUpdate
		change.From = resourceConfigSummary(before)
		change.To = resourceConfigSummary(after)
		change.Reason = "resource configuration changed"
	}

	if change.SourceAdapter == "" {
		change.SourceAdapter = resourceChangeSourceAdapter(&after)
	}
	change.RelatedResources = relatedResourceIDs(change.ResourceID, before, after)

	return change
}

func resourceChangedFields(before, after Resource) []string {
	var changed []string

	if before.Type != after.Type {
		changed = append(changed, "type")
	}
	if before.Technology != after.Technology {
		changed = append(changed, "technology")
	}
	if before.Name != after.Name {
		changed = append(changed, "name")
	}
	if before.Status != after.Status {
		changed = append(changed, "status")
	}
	if !equalStringPtr(before.ParentID, after.ParentID) {
		changed = append(changed, "parentId")
	}
	if !relationshipsEquivalent(before.Relationships, after.Relationships) {
		changed = append(changed, "relationships")
	}
	if !reflect.DeepEqual(before.Capabilities, after.Capabilities) {
		changed = append(changed, "capabilities")
	}
	if !sameStringSet(before.Tags, after.Tags) {
		changed = append(changed, "tags")
	}
	if before.CustomURL != after.CustomURL {
		changed = append(changed, "customUrl")
	}
	if !resourceIdentityEquivalent(before.Identity, after.Identity) {
		changed = append(changed, "identity")
	}
	if (isAvailabilityOwnedResource(before) || isAvailabilityOwnedResource(after)) &&
		availabilityConfigurationChanged(before.Availability, after.Availability) {
		changed = append(changed, "availability.configuration")
	}
	if resourceIncidentChanged(before, after) {
		changed = append(changed, "incidents")
	}
	if dockerRestartChanged(before, after) {
		changed = append(changed, "docker.restartCount", "docker.uptimeSeconds")
	}
	if kubernetesRestartChanged(before, after) {
		changed = append(changed, "kubernetes.restarts", "kubernetes.uptimeSeconds")
	}
	if proxmoxRestartChanged(before, after) {
		changed = append(changed, "proxmox.uptime")
	}
	if agentRestartChanged(before, after) {
		changed = append(changed, "agent.uptimeSeconds")
	}
	if dockerCommandChanged(before, after) {
		changed = append(changed, "docker.command")
	}
	if dockerUpdateStatusChanged(before, after) {
		changed = append(changed, "docker.updateStatus")
	}
	if proxmoxLifecycleChanged(before, after) {
		changed = append(changed, "proxmox.lifecycle")
	}

	return changed
}

func availabilityConfigurationChanged(before, after *AvailabilityData) bool {
	type availabilityConfiguration struct {
		TargetID            string
		LinkedResourceID    string
		Name                string
		TargetKind          string
		Address             string
		Protocol            string
		UDPMode             string
		Port                int
		Path                string
		Enabled             bool
		FailureThreshold    int
		PollIntervalSeconds int
		TimeoutMillis       int
	}
	project := func(data *AvailabilityData) availabilityConfiguration {
		if data == nil {
			return availabilityConfiguration{}
		}
		return availabilityConfiguration{
			TargetID:            strings.TrimSpace(data.TargetID),
			LinkedResourceID:    strings.TrimSpace(data.LinkedResourceID),
			Name:                strings.TrimSpace(data.Name),
			TargetKind:          strings.TrimSpace(data.TargetKind),
			Address:             strings.TrimSpace(data.Address),
			Protocol:            strings.TrimSpace(data.Protocol),
			UDPMode:             strings.TrimSpace(data.UDPMode),
			Port:                data.Port,
			Path:                strings.TrimSpace(data.Path),
			Enabled:             data.Enabled,
			FailureThreshold:    data.FailureThreshold,
			PollIntervalSeconds: data.PollIntervalSeconds,
			TimeoutMillis:       data.TimeoutMillis,
		}
	}
	return project(before) != project(after)
}

// relationshipsEquivalent reports whether two relationship sets describe the
// same edges. Registry rebuilds reconstruct every relationship with fresh
// ObservedAt/LastSeenAt stamps and metadata maps, so comparing with
// reflect.DeepEqual emitted a no-op relationship_change row for every
// relationship-bearing resource on every rebuild cycle (the unbounded
// unified_resources.db growth behind issue #1496). Only edge identity —
// canonical source, canonical target, type, and active state — counts as
// change.
func relationshipsEquivalent(a, b []ResourceRelationship) bool {
	if len(a) != len(b) {
		return false
	}
	if len(a) == 0 {
		return true
	}
	edgeKeys := func(relationships []ResourceRelationship) []string {
		keys := make([]string, 0, len(relationships))
		for _, relationship := range relationships {
			keys = append(keys, strings.Join([]string{
				CanonicalResourceID(relationship.SourceID),
				CanonicalResourceID(relationship.TargetID),
				string(relationship.Type),
				fmt.Sprintf("%t", relationship.Active),
			}, "\x1f"))
		}
		sort.Strings(keys)
		return keys
	}
	aKeys := edgeKeys(a)
	bKeys := edgeKeys(b)
	for i := range aKeys {
		if aKeys[i] != bKeys[i] {
			return false
		}
	}
	return true
}

func dockerCommandChanged(before, after Resource) bool {
	var beforeCommand, afterCommand any
	if before.Docker != nil {
		beforeCommand = before.Docker.Command
	}
	if after.Docker != nil {
		afterCommand = after.Docker.Command
	}
	return !reflect.DeepEqual(beforeCommand, afterCommand)
}

func dockerUpdateStatusChanged(before, after Resource) bool {
	var beforeStatus, afterStatus *DockerUpdateStatusMeta
	if before.Docker != nil {
		beforeStatus = before.Docker.UpdateStatus
	}
	if after.Docker != nil {
		afterStatus = after.Docker.UpdateStatus
	}
	if beforeStatus == nil || afterStatus == nil {
		return beforeStatus != afterStatus
	}
	// LastChecked is restamped by every periodic update check, so comparing the
	// whole struct emitted a no-op docker.updateStatus change row per container
	// per check cycle (the resource_changes flooding behind issue #1577). Only
	// semantic fields count as change.
	return beforeStatus.UpdateAvailable != afterStatus.UpdateAvailable ||
		beforeStatus.CurrentDigest != afterStatus.CurrentDigest ||
		beforeStatus.LatestDigest != afterStatus.LatestDigest ||
		beforeStatus.Error != afterStatus.Error
}

func dockerRestartChanged(before, after Resource) bool {
	if before.Docker == nil || after.Docker == nil {
		return false
	}
	if after.Docker.RestartCount > before.Docker.RestartCount {
		return true
	}
	return before.Docker.UptimeSeconds > 0 && after.Docker.UptimeSeconds > 0 && after.Docker.UptimeSeconds < before.Docker.UptimeSeconds
}

// resourceRestartChanged decides the restart kind. An uptime reset that comes
// with a status change stays a state transition, so a host that rebooted while
// offline still records its recovery for availability and status events.
func resourceRestartChanged(before, after Resource) bool {
	if dockerRestartChanged(before, after) || kubernetesRestartChanged(before, after) {
		return true
	}
	return before.Status == after.Status && (proxmoxRestartChanged(before, after) || agentRestartChanged(before, after))
}

// uptimeReset reports an uptime counter that went backwards between two
// positive readings from source, the later one observed later. Snapshots are
// captured before publication is serialized, so an older reading can publish
// after a newer one; its lower uptime is not a reset. A zero reading is a
// stopped or unreported resource.
func uptimeReset(before, after Resource, source DataSource, beforeUptime, afterUptime int64) bool {
	if beforeUptime <= 0 || afterUptime <= 0 || afterUptime >= beforeUptime {
		return false
	}
	beforeSeen, afterSeen := before.SourceStatus[source].LastSeen, after.SourceStatus[source].LastSeen
	return beforeSeen.IsZero() || afterSeen.IsZero() || afterSeen.After(beforeSeen)
}

// proxmoxRestartChanged reports a node, VM or LXC whose Proxmox uptime reset
// on the same node. QEMU's uptime follows its process, so it catches a stop
// and start (including qm reboot and a host reboot) but not an in-guest reboot
// or a reset; a host agent inside the guest reports those. A move to another
// node starts a new process there and is recorded as a relationship change.
func proxmoxRestartChanged(before, after Resource) bool {
	if before.Proxmox == nil || after.Proxmox == nil || before.Proxmox.NodeName != after.Proxmox.NodeName {
		return false
	}
	return uptimeReset(before, after, SourceProxmox, before.Proxmox.Uptime, after.Proxmox.Uptime)
}

// agentRestartChanged reports an operating system reboot seen by the same host
// agent. Another agent taking over the resource is not a reboot.
func agentRestartChanged(before, after Resource) bool {
	if before.Agent == nil || after.Agent == nil || before.Agent.AgentID != after.Agent.AgentID {
		return false
	}
	return uptimeReset(before, after, SourceAgent, before.Agent.UptimeSeconds, after.Agent.UptimeSeconds)
}

func kubernetesRestartChanged(before, after Resource) bool {
	if before.Kubernetes == nil || after.Kubernetes == nil {
		return false
	}
	if after.Kubernetes.Restarts > before.Kubernetes.Restarts {
		return true
	}
	return before.Kubernetes.UptimeSeconds > 0 && after.Kubernetes.UptimeSeconds > 0 && after.Kubernetes.UptimeSeconds < before.Kubernetes.UptimeSeconds
}

func proxmoxLifecycleChanged(before, after Resource) bool {
	var beforeProxmox, afterProxmox *struct {
		ClusterName    string
		LinkedAgentID  string
		Lock           string
		PendingUpdates int
	}
	if before.Proxmox != nil {
		beforeProxmox = &struct {
			ClusterName    string
			LinkedAgentID  string
			Lock           string
			PendingUpdates int
		}{
			ClusterName:    before.Proxmox.ClusterName,
			LinkedAgentID:  before.Proxmox.LinkedAgentID,
			Lock:           before.Proxmox.Lock,
			PendingUpdates: before.Proxmox.PendingUpdates,
		}
	}
	if after.Proxmox != nil {
		afterProxmox = &struct {
			ClusterName    string
			LinkedAgentID  string
			Lock           string
			PendingUpdates int
		}{
			ClusterName:    after.Proxmox.ClusterName,
			LinkedAgentID:  after.Proxmox.LinkedAgentID,
			Lock:           after.Proxmox.Lock,
			PendingUpdates: after.Proxmox.PendingUpdates,
		}
	}
	return !reflect.DeepEqual(beforeProxmox, afterProxmox)
}

func resourceIncidentChanged(before, after Resource) bool {
	return resourceIncidentFingerprint(before.Incidents) != resourceIncidentFingerprint(after.Incidents)
}

func resourceIncidentFingerprint(incidents []ResourceIncident) string {
	if len(incidents) == 0 {
		return "none"
	}

	labels := make([]string, 0, len(incidents))
	for _, incident := range incidents {
		labels = append(labels, fmt.Sprintf("%s|%s|%s|%s|%s",
			strings.TrimSpace(incident.Provider),
			strings.TrimSpace(incident.NativeID),
			strings.TrimSpace(incident.Code),
			strings.TrimSpace(string(incident.Severity)),
			strings.TrimSpace(incident.Summary),
		))
	}

	sort.Strings(labels)
	return strings.Join(labels, "||")
}

func resourceRelationSummary(resource Resource) string {
	if summary := resourceRelationshipSummary(resource.Relationships); summary != "" {
		return summary
	}
	parentID := ""
	if resource.ParentID != nil {
		parentID = strings.TrimSpace(*resource.ParentID)
	}
	if parentID == "" {
		parentID = "root"
	}
	return parentID
}

func resourceStatusString(status ResourceStatus) string {
	return strings.TrimSpace(string(status))
}

func relatedResourceIDs(primaryID string, before, after Resource) []string {
	primaryID = CanonicalResourceID(primaryID)
	seen := make(map[string]struct{}, 2)
	var out []string
	appendID := func(id string) {
		id = CanonicalResourceID(id)
		if id == "" || id == primaryID {
			return
		}
		if _, ok := seen[id]; ok {
			return
		}
		seen[id] = struct{}{}
		out = append(out, id)
	}
	if before.ParentID != nil {
		appendID(*before.ParentID)
	}
	if after.ParentID != nil {
		appendID(*after.ParentID)
	}
	for _, relationship := range before.Relationships {
		appendID(relationship.SourceID)
		appendID(relationship.TargetID)
	}
	for _, relationship := range after.Relationships {
		appendID(relationship.SourceID)
		appendID(relationship.TargetID)
	}
	return out
}

func resourceChangeSourceAdapter(resource *Resource) ChangeSourceAdapter {
	if resource == nil {
		return ""
	}
	switch {
	case resource.Docker != nil || hasDataSource(resource.Sources, SourceDocker):
		return AdapterDocker
	case resource.Proxmox != nil || hasDataSource(resource.Sources, SourceProxmox):
		return AdapterProxmox
	case resource.TrueNAS != nil || hasDataSource(resource.Sources, SourceTrueNAS):
		return AdapterTrueNAS
	case resource.VMware != nil || hasDataSource(resource.Sources, SourceVMware):
		return AdapterVMware
	case resource.Agent != nil || hasDataSource(resource.Sources, SourceAgent):
		return AdapterOpsAgent
	default:
		return ""
	}
}

func changeSourceAdapterForDataSource(source DataSource) ChangeSourceAdapter {
	switch source {
	case SourceDocker:
		return AdapterDocker
	case SourceProxmox:
		return AdapterProxmox
	case SourceTrueNAS:
		return AdapterTrueNAS
	case SourceVMware:
		return AdapterVMware
	case SourceAgent:
		return AdapterOpsAgent
	default:
		return ""
	}
}

// Identity addresses, hostnames and MACs are sets, not ordered observations.
// Registry merges can reorder them or turn a nil slice into an empty one while
// the actual identity remains unchanged; those differences must not create
// configuration-history rows on every poll.
func resourceIdentityEquivalent(a, b ResourceIdentity) bool {
	return a.MachineID == b.MachineID &&
		a.DMIUUID == b.DMIUUID &&
		a.ClusterName == b.ClusterName &&
		a.ProxmoxGuestKey == b.ProxmoxGuestKey &&
		sameStringSet(a.Hostnames, b.Hostnames) &&
		sameStringSet(a.IPAddresses, b.IPAddresses) &&
		sameStringSet(a.MACAddresses, b.MACAddresses)
}

func sameStringSet(a, b []string) bool {
	if len(a) != len(b) {
		return false
	}
	if len(a) == 0 {
		return true
	}

	counts := make(map[string]int, len(a))
	for _, v := range a {
		counts[v]++
	}
	for _, v := range b {
		counts[v]--
		if counts[v] < 0 {
			return false
		}
	}
	for _, count := range counts {
		if count != 0 {
			return false
		}
	}
	return true
}

func equalStringPtr(a, b *string) bool {
	switch {
	case a == nil && b == nil:
		return true
	case a == nil || b == nil:
		return false
	default:
		return strings.TrimSpace(*a) == strings.TrimSpace(*b)
	}
}