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.

4.9 KB
Raw Blame
package mock

import (
	"fmt"
	"math/rand"
	"sort"
	"time"

	"github.com/rcourtman/pulse-go-rewrite/internal/models"
)

// buildAlertHistory derives historical alert data from the canonical fixture graph.
func buildAlertHistory(nodes []models.Node, vms []models.VM, containers []models.Container) []models.Alert {
	return buildAlertHistoryAt(nodes, vms, containers, time.Now())
}

func buildAlertHistoryAt(nodes []models.Node, vms []models.VM, containers []models.Container, now time.Time) []models.Alert {
	var history []models.Alert

	// Alert types and messages
	alertTypes := []struct {
		alertType string
		level     string
		messages  []string
	}{
		{
			alertType: "threshold",
			level:     "warning",
			messages: []string{
				"CPU usage exceeded %d%%",
				"Memory usage exceeded %d%%",
				"Disk usage exceeded %d%%",
			},
		},
		{
			alertType: "threshold",
			level:     "critical",
			messages: []string{
				"CPU usage critical at %d%%",
				"Memory exhausted at %d%%",
				"Disk space critical at %d%%",
			},
		},
		{
			alertType: "connectivity",
			level:     "critical",
			messages: []string{
				"Node offline",
				"Connection lost",
				"Network timeout",
			},
		},
		{
			alertType: "backup",
			level:     "warning",
			messages: []string{
				"Backup failed",
				"Backup verification failed",
				"Backup storage low",
			},
		},
		{
			alertType: "system",
			level:     "info",
			messages: []string{
				"System update available",
				"Certificate expiring soon",
				"Scheduled maintenance reminder",
			},
		},
	}

	// Generate alerts for the past 90 days with more consistent distribution.
	// The current day is bounded by now; a history fixture must never describe
	// an incident that has not happened yet.
	for days := 90; days >= 0; days-- {
		// Generate 2-15 alerts per day for more realistic history
		numAlerts := rand.Intn(14) + 2

		for i := 0; i < numAlerts; i++ {
			// Pick random alert type
			alertType := alertTypes[rand.Intn(len(alertTypes))]

			// Pick random resource. resourceType uses the same vocabulary the
			// real alert engine stamps into metadata (node.go, guest_snapshot.go).
			var resourceName, resourceID, node, resourceType string

			switch rand.Intn(3) {
			case 0: // Node alert
				if len(nodes) > 0 {
					selectedNode := nodes[rand.Intn(len(nodes))]
					resourceName = selectedNode.Name
					resourceID = selectedNode.ID
					node = selectedNode.Name
					resourceType = "node"
				}
			case 1: // VM alert
				if len(vms) > 0 {
					vm := vms[rand.Intn(len(vms))]
					resourceName = vm.Name
					resourceID = vm.ID
					node = vm.Node
					resourceType = "vm"
				}
			case 2: // Container alert
				if len(containers) > 0 {
					selectedContainer := containers[rand.Intn(len(containers))]
					resourceName = selectedContainer.Name
					resourceID = selectedContainer.ID
					node = selectedContainer.Node
					resourceType = "system-container"
				}
			}

			startTime := randomAlertHistoryTime(now, days)

			// Alert duration (resolved after 1 minute to 4 hours) - for display purposes

			// Pick random message and format it
			msg := alertType.messages[rand.Intn(len(alertType.messages))]
			if alertType.alertType == "threshold" {
				value := rand.Intn(30) + 70 // 70-99%
				msg = fmt.Sprintf(msg, value)
			}

			alert := models.Alert{
				ID:           fmt.Sprintf("hist-%d-%d-%d", days, i, rand.Intn(10000)),
				Type:         alertType.alertType,
				Level:        alertType.level,
				ResourceID:   resourceID,
				ResourceName: resourceName,
				Node:         node,
				Message:      msg,
				StartTime:    startTime,
				Acknowledged: false, // Historical alerts are not acknowledged
			}
			if resourceType != "" {
				alert.Metadata = map[string]interface{}{"resourceType": resourceType}
			}

			// Add threshold values for threshold alerts
			if alertType.alertType == "threshold" {
				value := float64(rand.Intn(30) + 70)
				threshold := float64(rand.Intn(20) + 60)
				alert.Value = value
				alert.Threshold = threshold
			}

			history = append(history, alert)
		}
	}

	// The live history endpoint is newest-first. Active alerts are supplied by
	// the live alert snapshot and merged by the UI, so this fixture contains
	// only closed occurrences; inventing unrelated open rows makes their
	// history status contradict the active-alert source of truth.
	sort.SliceStable(history, func(i, j int) bool {
		return history[i].StartTime.After(history[j].StartTime)
	})

	return history
}

func randomAlertHistoryTime(now time.Time, daysAgo int) time.Time {
	day := now.AddDate(0, 0, -daysAgo)
	dayStart := time.Date(day.Year(), day.Month(), day.Day(), 0, 0, 0, 0, day.Location())
	latest := dayStart.AddDate(0, 0, 1).Add(-time.Second)
	if daysAgo == 0 {
		latest = now.Truncate(time.Second)
	}
	if !latest.After(dayStart) {
		return dayStart
	}
	spanSeconds := int64(latest.Sub(dayStart) / time.Second)
	return dayStart.Add(time.Duration(rand.Int63n(spanSeconds+1)) * time.Second)
}