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.

15.1 KB
Raw Blame
package unifiedresources

import "strings"

func RefreshCanonicalIdentity(resource *Resource) {
	if resource == nil {
		return
	}

	displayName := firstTrimmed(resource.Name, canonicalHostname(*resource), resource.ID)
	hostname := canonicalHostname(*resource)
	platformID := canonicalPlatformID(*resource)
	primaryID := canonicalPrimaryID(*resource)
	aliases := canonicalAliases(*resource, primaryID, platformID, hostname)

	if displayName == "" && hostname == "" && platformID == "" && primaryID == "" && len(aliases) == 0 {
		resource.Canonical = nil
		return
	}

	resource.Canonical = &CanonicalIdentity{
		DisplayName:   displayName,
		Hostname:      hostname,
		PlatformID:    platformID,
		PrimaryID:     primaryID,
		Aliases:       aliases,
		SupersededIDs: uniqueTrimmed(resource.SupersededCanonicalIDs...),
	}
}

func canonicalPrimaryID(resource Resource) string {
	if nodeID := canonicalProxmoxNodePrimaryID(resource); nodeID != "" {
		return nodeID
	}
	if isDockerChildResource(resource) {
		for _, target := range []interface {
			GetResourceType() string
			GetResourceID() string
		}{resource.MetricsTarget, resource.DiscoveryTarget} {
			if id := dockerChildTargetID(resource, target); id != "" {
				return string(CanonicalResourceType(resource.Type)) + ":" + id
			}
		}
		if identity := canonicalDockerSwarmNodePrimaryID(resource); identity != "" {
			return identity
		}
		return strings.TrimSpace(resource.ID)
	}
	if identity := formatTargetIdentity(resource.MetricsTarget); identity != "" {
		return identity
	}
	if identity := formatTargetIdentity(resource.DiscoveryTarget); identity != "" {
		return identity
	}
	if runtimeID := strings.TrimSpace(canonicalDockerRuntimeID(resource)); runtimeID != "" {
		return "docker-host:" + runtimeID
	}
	if clusterID := strings.TrimSpace(canonicalKubernetesClusterID(resource)); clusterID != "" {
		switch CanonicalResourceType(resource.Type) {
		case ResourceTypeK8sCluster, ResourceTypeK8sNode, ResourceTypePod, ResourceTypeK8sDeployment:
			return "k8s:" + clusterID
		}
	}
	if agentID := strings.TrimSpace(canonicalAgentID(resource)); agentID != "" {
		return "agent:" + agentID
	}
	if instanceID := strings.TrimSpace(canonicalPBSInstanceID(resource)); instanceID != "" {
		return "pbs:" + instanceID
	}
	if instanceID := strings.TrimSpace(canonicalPMGInstanceID(resource)); instanceID != "" {
		return "pmg:" + instanceID
	}
	if identity := canonicalVMwarePrimaryID(resource); identity != "" {
		return identity
	}
	if targetID := strings.TrimSpace(canonicalAvailabilityTargetID(resource)); targetID != "" {
		return "availability:" + targetID
	}
	return strings.TrimSpace(resource.ID)
}

func canonicalProxmoxNodePrimaryID(resource Resource) string {
	if CanonicalResourceType(resource.Type) != ResourceTypeAgent || resource.Proxmox == nil {
		return ""
	}
	sourceID := strings.TrimSpace(resource.Proxmox.SourceID)
	if sourceID == "" {
		return ""
	}
	return "node:" + sourceID
}

func canonicalAliases(resource Resource, primaryID, platformID, hostname string) []string {
	values := append([]string{}, resource.SupersededCanonicalIDs...)
	if isDockerChildResource(resource) {
		// Docker placement identifies the command host, not the collected
		// object. Indexing that host on every child makes the real host's
		// otherwise unique hostname and agent ID ambiguous.
		values = append(values, primaryID)
		if CanonicalResourceType(resource.Type) == ResourceTypeDockerSwarmNode {
			values = append(values, canonicalDockerNodeID(resource), canonicalDockerNodeName(resource))
		}
		values = append(values,
			dockerChildTargetID(resource, resource.MetricsTarget),
			dockerChildTargetID(resource, resource.DiscoveryTarget),
			platformID, hostname, resource.Name, resource.Identity.MachineID, resource.ID,
		)
		return uniqueTrimmed(append(values, resource.Identity.Hostnames...)...)
	}
	values = append(values,
		primaryID,
		targetResourceID(resource.MetricsTarget),
		targetAgentID(resource.DiscoveryTarget),
		targetResourceID(resource.DiscoveryTarget),
		canonicalDockerNodeID(resource),
		canonicalDockerNodeName(resource),
		canonicalDockerRuntimeID(resource),
		canonicalKubernetesClusterID(resource),
		canonicalAgentID(resource),
		canonicalPBSInstanceID(resource),
		canonicalPMGInstanceID(resource),
		canonicalVMwareManagedObjectID(resource),
		canonicalVMwareHostUUID(resource),
		canonicalAvailabilityTargetID(resource),
		canonicalAvailabilityAddress(resource),
		platformID,
		hostname,
		strings.TrimSpace(resource.Identity.MachineID),
		strings.TrimSpace(resource.ID),
	)
	values = append(values, resource.Identity.Hostnames...)
	// Alert evaluation references host-agent resources as "agent:{hostID}"
	// (see alerts.hostResourceID). A merged PVE-node + pulse-agent resource
	// takes "node:..." as its primary ID, so the prefixed agent ref must be
	// indexed explicitly or per-resource policy lookups miss (#1497).
	if agentID := strings.TrimSpace(canonicalAgentID(resource)); agentID != "" {
		values = append(values, "agent:"+agentID)
	}
	if resource.Proxmox != nil {
		// Only the node owns its node identity. Guests and storage inherit
		// the parent's NodeIdentity and NodeAliases for presentation and
		// search, but as aliases they would make every child answer to the
		// node's alert resource ID, so one node alert painted every guest.
		if CanonicalResourceType(resource.Type) == ResourceTypeAgent {
			values = append(
				values,
				strings.TrimSpace(resource.Proxmox.NodeIdentity),
				strings.TrimSpace(resource.Proxmox.NodeName),
			)
			values = append(values, resource.Proxmox.NodeAliases...)
		}
		// PVE disk alerts predate the unified resource registry and retain a
		// path-shaped resource reference. Resolve it to this exact physical
		// disk so a UI mute reaches both new and restored occurrences (#2112).
		if CanonicalResourceType(resource.Type) == ResourceTypePhysicalDisk && resource.PhysicalDisk != nil &&
			strings.TrimSpace(resource.Proxmox.Instance) != "" && strings.TrimSpace(resource.Proxmox.NodeName) != "" &&
			strings.TrimSpace(resource.PhysicalDisk.DevPath) != "" {
			values = append(values, ProxmoxPhysicalDiskAlertResourceID(
				resource.Proxmox.Instance, resource.Proxmox.NodeName, resource.PhysicalDisk.DevPath,
			))
		}
	}

	return uniqueTrimmed(values...)
}

func canonicalPlatformID(resource Resource) string {
	if isDockerChildResource(resource) {
		return firstTrimmed(
			dockerChildTargetID(resource, resource.MetricsTarget),
			dockerChildTargetID(resource, resource.DiscoveryTarget),
			resource.Name, resource.ID,
		)
	}
	return firstTrimmed(
		canonicalProxmoxNodeName(resource),
		canonicalAgentHostname(resource),
		canonicalDockerHostname(resource),
		canonicalPBSHostname(resource),
		canonicalPMGHostname(resource),
		canonicalTrueNASHostname(resource),
		canonicalAvailabilityAddress(resource),
		canonicalKubernetesPlatformID(resource),
		resource.Name,
		resource.ID,
	)
}

func canonicalHostname(resource Resource) string {
	if isDockerChildResource(resource) {
		return firstIdentityHostname(resource.Identity)
	}
	return firstTrimmed(
		firstIdentityHostname(resource.Identity),
		canonicalAgentHostname(resource),
		canonicalDockerHostname(resource),
		canonicalPBSHostname(resource),
		canonicalPMGHostname(resource),
		canonicalTrueNASHostname(resource),
		canonicalAvailabilityAddress(resource),
	)
}

func isDockerChildResource(resource Resource) bool {
	if resource.Docker == nil {
		return false
	}
	switch CanonicalResourceType(resource.Type) {
	case ResourceTypeAppContainer, ResourceTypeDockerService, ResourceTypeDockerImage,
		ResourceTypeDockerVolume, ResourceTypeDockerNetwork, ResourceTypeDockerTask,
		ResourceTypeDockerSwarmNode, ResourceTypeDockerSecret, ResourceTypeDockerConfig:
		return true
	}
	return false
}

func dockerChildTargetID(resource Resource, target interface {
	GetResourceType() string
	GetResourceID() string
}) string {
	if target == nil || CanonicalResourceType(ResourceType(target.GetResourceType())) != CanonicalResourceType(resource.Type) {
		return ""
	}
	return targetResourceID(target)
}

func canonicalProxmoxNodeName(resource Resource) string {
	if resource.Proxmox == nil {
		return ""
	}
	return strings.TrimSpace(resource.Proxmox.NodeName)
}

func canonicalAgentHostname(resource Resource) string {
	if resource.Agent == nil {
		return ""
	}
	return strings.TrimSpace(resource.Agent.Hostname)
}

func canonicalDockerHostname(resource Resource) string {
	if resource.Docker == nil {
		return ""
	}
	return strings.TrimSpace(resource.Docker.Hostname)
}

func canonicalPBSHostname(resource Resource) string {
	if resource.PBS == nil {
		return ""
	}
	return strings.TrimSpace(resource.PBS.Hostname)
}

func canonicalPMGHostname(resource Resource) string {
	if resource.PMG == nil {
		return ""
	}
	return strings.TrimSpace(resource.PMG.Hostname)
}

func canonicalTrueNASHostname(resource Resource) string {
	if resource.TrueNAS == nil {
		return ""
	}
	return strings.TrimSpace(resource.TrueNAS.Hostname)
}

func canonicalAvailabilityTargetID(resource Resource) string {
	if resource.Availability == nil {
		return ""
	}
	return strings.TrimSpace(resource.Availability.TargetID)
}

func canonicalAvailabilityAddress(resource Resource) string {
	if resource.Availability == nil {
		return ""
	}
	return strings.TrimSpace(resource.Availability.Address)
}

func canonicalKubernetesPlatformID(resource Resource) string {
	if resource.Kubernetes == nil {
		return ""
	}
	return firstTrimmed(
		resource.Kubernetes.NodeName,
		resource.Kubernetes.ClusterName,
		resource.Kubernetes.SourceName,
		resource.Kubernetes.Context,
		resource.Kubernetes.ClusterID,
	)
}

func canonicalAgentID(resource Resource) string {
	if resource.Agent != nil {
		if id := strings.TrimSpace(resource.Agent.AgentID); id != "" {
			return id
		}
	}
	if resource.Kubernetes != nil {
		if id := strings.TrimSpace(resource.Kubernetes.AgentID); id != "" {
			return id
		}
	}
	if resource.DiscoveryTarget != nil {
		if id := strings.TrimSpace(resource.DiscoveryTarget.AgentID); id != "" {
			return id
		}
	}
	return ""
}

func canonicalDockerRuntimeID(resource Resource) string {
	if resource.Docker != nil {
		if id := strings.TrimSpace(resource.Docker.HostSourceID); id != "" {
			return id
		}
	}
	return ""
}

func canonicalDockerSwarmNodePrimaryID(resource Resource) string {
	if CanonicalResourceType(resource.Type) != ResourceTypeDockerSwarmNode || resource.Docker == nil {
		return ""
	}
	nodeID := firstTrimmed(resource.Docker.NodeID, resource.Docker.NodeName, resource.Name)
	if nodeID == "" {
		return ""
	}
	scope := firstTrimmed(dockerSwarmClusterKeyFromMeta(resource.Docker.Swarm), resource.Docker.HostSourceID)
	if scope == "" {
		return "docker-swarm-node:" + nodeID
	}
	return "docker-swarm-node:" + scope + ":" + nodeID
}

func canonicalDockerNodeID(resource Resource) string {
	if resource.Docker == nil {
		return ""
	}
	return strings.TrimSpace(resource.Docker.NodeID)
}

func canonicalDockerNodeName(resource Resource) string {
	if resource.Docker == nil {
		return ""
	}
	return strings.TrimSpace(resource.Docker.NodeName)
}

func canonicalKubernetesClusterID(resource Resource) string {
	if resource.Kubernetes == nil {
		return ""
	}
	return firstTrimmed(resource.Kubernetes.ClusterID)
}

func canonicalPBSInstanceID(resource Resource) string {
	if resource.PBS == nil {
		return ""
	}
	return strings.TrimSpace(resource.PBS.InstanceID)
}

func canonicalPMGInstanceID(resource Resource) string {
	if resource.PMG == nil {
		return ""
	}
	return strings.TrimSpace(resource.PMG.InstanceID)
}

func canonicalVMwarePrimaryID(resource Resource) string {
	if resource.VMware == nil {
		return ""
	}
	managedObjectID := strings.TrimSpace(resource.VMware.ManagedObjectID)
	if managedObjectID == "" {
		return ""
	}
	entityType := strings.TrimSpace(resource.VMware.EntityType)
	if entityType == "" {
		entityType = string(CanonicalResourceType(resource.Type))
	}
	connectionID := strings.TrimSpace(resource.VMware.ConnectionID)
	if connectionID != "" {
		return "vmware:" + connectionID + ":" + entityType + ":" + managedObjectID
	}
	return "vmware:" + entityType + ":" + managedObjectID
}

func canonicalVMwareManagedObjectID(resource Resource) string {
	if resource.VMware == nil {
		return ""
	}
	return strings.TrimSpace(resource.VMware.ManagedObjectID)
}

func canonicalVMwareHostUUID(resource Resource) string {
	if resource.VMware == nil {
		return ""
	}
	return strings.TrimSpace(resource.VMware.HostUUID)
}

func firstIdentityHostname(identity ResourceIdentity) string {
	for _, hostname := range identity.Hostnames {
		if trimmed := strings.TrimSpace(hostname); trimmed != "" {
			return trimmed
		}
	}
	return ""
}

func formatTargetIdentity(target interface {
	GetResourceType() string
	GetResourceID() string
}) string {
	if target == nil {
		return ""
	}
	resourceType := string(CanonicalResourceType(ResourceType(strings.TrimSpace(target.GetResourceType()))))
	resourceID := strings.TrimSpace(target.GetResourceID())
	if resourceType == "" || resourceID == "" {
		return ""
	}
	return resourceType + ":" + resourceID
}

func targetResourceID(target interface{ GetResourceID() string }) string {
	if target == nil {
		return ""
	}
	return strings.TrimSpace(target.GetResourceID())
}

func targetAgentID(target interface{ GetAgentID() string }) string {
	if target == nil {
		return ""
	}
	return strings.TrimSpace(target.GetAgentID())
}

func firstTrimmed(values ...string) string {
	for _, value := range values {
		if trimmed := strings.TrimSpace(value); trimmed != "" {
			return trimmed
		}
	}
	return ""
}

func uniqueTrimmed(values ...string) []string {
	// Canonical aliases usually contain only a handful of non-empty unique
	// identities among many optional inputs. Do not allocate a map sized for
	// every placeholder, or retain that capacity in each row's alias slice.
	// A bounded stack scan handles the common case; larger vocabularies use
	// the same lowercased-key map semantics without quadratic growth.
	var smallKeys [8]string
	var seen map[string]struct{}
	aliases := make([]string, 0, min(len(values), len(smallKeys)))
	for _, value := range values {
		trimmed := strings.TrimSpace(value)
		if trimmed == "" {
			continue
		}
		key := strings.ToLower(trimmed)
		if seen != nil {
			if _, ok := seen[key]; ok {
				continue
			}
		} else {
			duplicate := false
			for _, previous := range smallKeys[:len(aliases)] {
				if previous == key {
					duplicate = true
					break
				}
			}
			if duplicate {
				continue
			}
			if len(aliases) < len(smallKeys) {
				smallKeys[len(aliases)] = key
			} else {
				seen = make(map[string]struct{}, min(len(values), 64))
				for _, previous := range smallKeys {
					seen[previous] = struct{}{}
				}
			}
		}
		if seen != nil {
			seen[key] = struct{}{}
		}
		aliases = append(aliases, trimmed)
	}
	return aliases
}

func (target *DiscoveryTarget) GetResourceType() string {
	if target == nil {
		return ""
	}
	return target.ResourceType
}

func (target *DiscoveryTarget) GetAgentID() string {
	if target == nil {
		return ""
	}
	return target.AgentID
}

func (target *DiscoveryTarget) GetResourceID() string {
	if target == nil {
		return ""
	}
	return target.ResourceID
}

func (target *MetricsTarget) GetResourceType() string {
	if target == nil {
		return ""
	}
	return target.ResourceType
}

func (target *MetricsTarget) GetResourceID() string {
	if target == nil {
		return ""
	}
	return target.ResourceID
}