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.

feat: add resource picker and multi-resource report generation

rcourtman5c1487e40650
diff --git a/frontend-modern/src/components/Settings/ReportingPanel.tsx b/frontend-modern/src/components/Settings/ReportingPanel.tsx
index ed66bff680..6e2954248e 100644
--- a/frontend-modern/src/components/Settings/ReportingPanel.tsx
+++ b/frontend-modern/src/components/Settings/ReportingPanel.tsx
@@ -3,9 +3,10 @@ import FileText from 'lucide-solid/icons/file-text';
import Download from 'lucide-solid/icons/download';
import BarChart from 'lucide-solid/icons/bar-chart';
import SettingsPanel from '@/components/shared/SettingsPanel';
-import { formField, formLabel, formHelpText, formControl, formSelect } from '@/components/shared/Form';
+import { formField, formLabel, formHelpText, formControl } from '@/components/shared/Form';
import { showSuccess, showWarning } from '@/utils/toast';
import { apiFetch } from '@/utils/apiClient';
+import { ResourcePicker, type SelectedResource } from './ResourcePicker';
interface FormFieldProps {
label: string;
@@ -24,8 +25,7 @@ function FormField(props: FormFieldProps) {
}
export function ReportingPanel() {
- const [resourceType, setResourceType] = createSignal('node');
- const [resourceId, setResourceId] = createSignal('');
+ const [selectedResources, setSelectedResources] = createSignal<SelectedResource[]>([]);
const [metricType, setMetricType] = createSignal('');
const [format, setFormat] = createSignal<'pdf' | 'csv'>('pdf');
const [range, setRange] = createSignal('24h');
@@ -33,8 +33,9 @@ export function ReportingPanel() {
const [title, setTitle] = createSignal('');
const handleGenerate = async () => {
- if (!resourceId()) {
- showWarning('Please enter a Resource ID');
+ const resources = selectedResources();
+ if (resources.length === 0) {
+ showWarning('Please select at least one resource');
return;
}
@@ -48,20 +49,49 @@ export function ReportingPanel() {
const startStr = start.toISOString();
- const params = new URLSearchParams({
- resourceType: resourceType(),
- resourceId: resourceId(),
- format: format(),
- start: startStr,
- end: end,
- title: title() || `Infrastructure Report - ${resourceId()}`,
- });
-
- if (metricType()) {
- params.append('metricType', metricType());
+ let response: Response;
+ let filename: string;
+
+ if (resources.length === 1) {
+ // Single resource: use existing GET endpoint for backwards compatibility
+ const res = resources[0];
+ const params = new URLSearchParams({
+ resourceType: res.type,
+ resourceId: res.id,
+ format: format(),
+ start: startStr,
+ end: end,
+ title: title() || `Infrastructure Report - ${res.name}`,
+ });
+
+ if (metricType()) {
+ params.append('metricType', metricType());
+ }
+
+ response = await apiFetch(`/api/admin/reports/generate?${params.toString()}`);
+ filename = `report-${res.name}-${new Date().toISOString().split('T')[0]}.${format()}`;
+ } else {
+ // Multiple resources: use POST multi endpoint
+ const body = {
+ resources: resources.map(r => ({
+ resourceType: r.type,
+ resourceId: r.id,
+ })),
+ format: format(),
+ start: startStr,
+ end: end,
+ title: title() || 'Fleet Performance Report',
+ metricType: metricType() || undefined,
+ };
+
+ response = await apiFetch('/api/admin/reports/generate-multi', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+ filename = `fleet-report-${new Date().toISOString().split('T')[0]}.${format()}`;
}
- const response = await apiFetch(`/api/admin/reports/generate?${params.toString()}`);
if (!response.ok) {
const text = await response.text();
throw new Error(text || 'Failed to generate report');
@@ -71,7 +101,7 @@ export function ReportingPanel() {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
- a.download = `report-${resourceId()}-${new Date().toISOString().split('T')[0]}.${format()}`;
+ a.download = filename;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
@@ -94,32 +124,13 @@ export function ReportingPanel() {
icon={<BarChart class="w-5 h-5" strokeWidth={2} />}
bodyClass="space-y-6"
>
- <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
- <FormField label="Resource Type" helpText="Select the type of infrastructure resource">
- <select
- id="resource-type"
- class={formSelect}
- value={resourceType()}
- onChange={(e) => setResourceType(e.currentTarget.value)}
- >
- <option value="node">Proxmox Node</option>
- <option value="vm">Virtual Machine (QEMU)</option>
- <option value="container">Container (LXC)</option>
- <option value="storage">Storage</option>
- </select>
- </FormField>
-
- <FormField label="Resource ID" helpText="Enter the full ID of the resource">
- <input
- id="resource-id"
- type="text"
- class={formControl}
- placeholder="e.g. pve1:node1 or pve1:node1:100"
- value={resourceId()}
- onInput={(e) => setResourceId(e.currentTarget.value)}
- />
- </FormField>
- </div>
+ {/* Resource Picker */}
+ <FormField label="Resources" helpText="Select the resources to include in the report">
+ <ResourcePicker
+ selected={selectedResources}
+ onSelectionChange={setSelectedResources}
+ />
+ </FormField>
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<FormField label="Metric Type (Optional)" helpText="Filter by specific metric type">
@@ -202,7 +213,12 @@ export function ReportingPanel() {
<Show when={generating()} fallback={<Download size={20} />}>
<div class="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin" />
</Show>
- {generating() ? 'Generating...' : 'Generate Report'}
+ {generating()
+ ? 'Generating...'
+ : selectedResources().length > 0
+ ? `Generate Report (${selectedResources().length} resource${selectedResources().length !== 1 ? 's' : ''})`
+ : 'Generate Report'
+ }
</button>
</div>
</SettingsPanel>
@@ -215,7 +231,7 @@ export function ReportingPanel() {
<div>
<h3 class="text-lg font-bold text-white mb-2">Advanced Insights</h3>
<p class="text-slate-400 leading-relaxed">
- Reports are generated directly from the historical metrics store. PDF reports provide a summarized view with average, minimum, and maximum values, while CSV exports provide raw granular data for external analysis in tools like Excel or BI suites.
+ Reports are generated directly from the historical metrics store. PDF reports provide a summarized view with average, minimum, and maximum values, while CSV exports provide raw granular data for external analysis in tools like Excel or BI suites. Select multiple resources to generate a fleet summary report.
</p>
</div>
</div>
diff --git a/frontend-modern/src/components/Settings/ResourcePicker.tsx b/frontend-modern/src/components/Settings/ResourcePicker.tsx
new file mode 100644
index 0000000000..a354db0a45
--- /dev/null
+++ b/frontend-modern/src/components/Settings/ResourcePicker.tsx
@@ -0,0 +1,351 @@
+import { createSignal, createMemo, For, Show, type Accessor } from 'solid-js';
+import Search from 'lucide-solid/icons/search';
+import X from 'lucide-solid/icons/x';
+import CheckSquare from 'lucide-solid/icons/check-square';
+import XSquare from 'lucide-solid/icons/x-square';
+import { formControl } from '@/components/shared/Form';
+import { useResources, getDisplayName } from '@/hooks/useResources';
+import type { Resource, ResourceType } from '@/types/resource';
+import { showWarning } from '@/utils/toast';
+
+const MAX_SELECTION = 50;
+
+export interface SelectedResource {
+ id: string;
+ type: string;
+ name: string;
+}
+
+interface ResourcePickerProps {
+ selected: Accessor<SelectedResource[]>;
+ onSelectionChange: (items: SelectedResource[]) => void;
+}
+
+type TypeFilter = 'all' | 'node' | 'vm' | 'container';
+
+const typeFilterLabels: Record<TypeFilter, string> = {
+ all: 'All',
+ node: 'Nodes',
+ vm: 'VMs',
+ container: 'Containers',
+};
+
+function normalizeType(type: ResourceType): string {
+ if (type === 'oci-container') return 'container';
+ return type;
+}
+
+function matchesTypeFilter(resource: Resource, filter: TypeFilter): boolean {
+ if (filter === 'all') return true;
+ const normalized = normalizeType(resource.type);
+ return normalized === filter;
+}
+
+function getStatusColor(status: string): string {
+ switch (status) {
+ case 'online':
+ case 'running':
+ return 'bg-emerald-400';
+ case 'offline':
+ case 'stopped':
+ return 'bg-slate-500';
+ case 'degraded':
+ return 'bg-amber-400';
+ case 'paused':
+ return 'bg-blue-400';
+ default:
+ return 'bg-slate-500';
+ }
+}
+
+function getTypeBadge(type: ResourceType): { label: string; classes: string } {
+ const normalized = normalizeType(type);
+ switch (normalized) {
+ case 'node':
+ return { label: 'Node', classes: 'bg-blue-500/20 text-blue-400' };
+ case 'vm':
+ return { label: 'VM', classes: 'bg-purple-500/20 text-purple-400' };
+ case 'container':
+ return { label: 'CT', classes: 'bg-emerald-500/20 text-emerald-400' };
+ default:
+ return { label: type, classes: 'bg-slate-500/20 text-slate-400' };
+ }
+}
+
+export function ResourcePicker(props: ResourcePickerProps) {
+ const { resources } = useResources();
+ const [search, setSearch] = createSignal('');
+ const [typeFilter, setTypeFilter] = createSignal<TypeFilter>('all');
+ const [tagFilter, setTagFilter] = createSignal('');
+
+ // Filter to only reportable resource types (nodes, VMs, containers)
+ const reportableResources = createMemo(() => {
+ return resources().filter(r =>
+ r.type === 'node' || r.type === 'vm' || r.type === 'container' || r.type === 'oci-container'
+ );
+ });
+
+ // Apply filters
+ const filteredResources = createMemo(() => {
+ let result = reportableResources();
+
+ // Type filter
+ result = result.filter(r => matchesTypeFilter(r, typeFilter()));
+
+ // Search filter (name or ID)
+ const searchTerm = search().toLowerCase().trim();
+ if (searchTerm) {
+ result = result.filter(r => {
+ const name = getDisplayName(r).toLowerCase();
+ const id = r.id.toLowerCase();
+ return name.includes(searchTerm) || id.includes(searchTerm);
+ });
+ }
+
+ // Tag filter
+ const tag = tagFilter().toLowerCase().trim();
+ if (tag) {
+ result = result.filter(r =>
+ r.tags && r.tags.some(t => t.toLowerCase().includes(tag))
+ );
+ }
+
+ // Sort: nodes first, then VMs, then containers, then alphabetical
+ result.sort((a, b) => {
+ const typeOrder: Record<string, number> = { node: 0, vm: 1, container: 2 };
+ const aOrder = typeOrder[normalizeType(a.type)] ?? 3;
+ const bOrder = typeOrder[normalizeType(b.type)] ?? 3;
+ if (aOrder !== bOrder) return aOrder - bOrder;
+ return getDisplayName(a).localeCompare(getDisplayName(b));
+ });
+
+ return result;
+ });
+
+ const selectedIds = createMemo(() => new Set(props.selected().map(s => s.id)));
+
+ const isSelected = (id: string) => selectedIds().has(id);
+
+ const toggleResource = (resource: Resource) => {
+ const current = props.selected();
+ if (isSelected(resource.id)) {
+ props.onSelectionChange(current.filter(s => s.id !== resource.id));
+ } else {
+ if (current.length >= MAX_SELECTION) {
+ showWarning(`Maximum ${MAX_SELECTION} resources can be selected`);
+ return;
+ }
+ props.onSelectionChange([...current, {
+ id: resource.id,
+ type: normalizeType(resource.type),
+ name: getDisplayName(resource),
+ }]);
+ }
+ };
+
+ const selectAllVisible = () => {
+ const current = props.selected();
+ const currentIds = new Set(current.map(s => s.id));
+ const toAdd = filteredResources()
+ .filter(r => !currentIds.has(r.id))
+ .map(r => ({
+ id: r.id,
+ type: normalizeType(r.type),
+ name: getDisplayName(r),
+ }));
+
+ const newSelection = [...current, ...toAdd];
+ if (newSelection.length > MAX_SELECTION) {
+ showWarning(`Maximum ${MAX_SELECTION} resources can be selected. Only ${MAX_SELECTION - current.length} more can be added.`);
+ props.onSelectionChange([...current, ...toAdd.slice(0, MAX_SELECTION - current.length)]);
+ return;
+ }
+ props.onSelectionChange(newSelection);
+ };
+
+ const clearAll = () => {
+ props.onSelectionChange([]);
+ };
+
+ const removeSelected = (id: string) => {
+ props.onSelectionChange(props.selected().filter(s => s.id !== id));
+ };
+
+ return (
+ <div class="space-y-3">
+ {/* Filter bar */}
+ <div class="flex flex-col gap-3">
+ <div class="flex gap-2 flex-wrap">
+ {/* Search input */}
+ <div class="relative flex-1 min-w-[200px]">
+ <Search class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
+ <input
+ type="text"
+ class={`${formControl} pl-9`}
+ placeholder="Search by name or ID..."
+ value={search()}
+ onInput={(e) => setSearch(e.currentTarget.value)}
+ />
+ </div>
+
+ {/* Tag filter */}
+ <input
+ type="text"
+ class={`${formControl} w-40`}
+ placeholder="Filter by tag..."
+ value={tagFilter()}
+ onInput={(e) => setTagFilter(e.currentTarget.value)}
+ />
+ </div>
+
+ {/* Type toggle buttons */}
+ <div class="flex gap-1">
+ <For each={(['all', 'node', 'vm', 'container'] as TypeFilter[])}>
+ {(type) => (
+ <button
+ class={`px-3 py-1.5 rounded-lg text-sm font-medium transition-all ${
+ typeFilter() === type
+ ? 'bg-blue-600/20 border border-blue-500 text-blue-400'
+ : 'bg-slate-800/50 border border-slate-700 text-slate-400 hover:border-slate-500'
+ }`}
+ onClick={() => setTypeFilter(type)}
+ >
+ {typeFilterLabels[type]}
+ </button>
+ )}
+ </For>
+ </div>
+ </div>
+
+ {/* Resource list */}
+ <div class="border border-slate-700 rounded-lg overflow-hidden">
+ <Show
+ when={reportableResources().length > 0}
+ fallback={
+ <div class="p-8 text-center text-slate-400">
+ <p class="text-sm">No resources available</p>
+ <p class="text-xs mt-1 text-slate-500">Resources will appear when connected to a Proxmox instance</p>
+ </div>
+ }
+ >
+ <Show
+ when={filteredResources().length > 0}
+ fallback={
+ <div class="p-6 text-center text-slate-400 text-sm">
+ No resources match your filters
+ </div>
+ }
+ >
+ <div class="max-h-[300px] overflow-y-auto">
+ <For each={filteredResources()}>
+ {(resource) => {
+ const badge = getTypeBadge(resource.type);
+ return (
+ <button
+ class={`w-full flex items-center gap-3 px-3 py-2 text-left transition-colors border-b border-slate-800 last:border-b-0 ${
+ isSelected(resource.id)
+ ? 'bg-blue-600/10'
+ : 'hover:bg-slate-800/50'
+ }`}
+ onClick={() => toggleResource(resource)}
+ >
+ {/* Checkbox */}
+ <div class={`w-4 h-4 rounded border flex-shrink-0 flex items-center justify-center ${
+ isSelected(resource.id)
+ ? 'bg-blue-600 border-blue-600'
+ : 'border-slate-600'
+ }`}>
+ <Show when={isSelected(resource.id)}>
+ <svg class="w-3 h-3 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="3">
+ <path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7" />
+ </svg>
+ </Show>
+ </div>
+
+ {/* Status dot */}
+ <div class={`w-2 h-2 rounded-full flex-shrink-0 ${getStatusColor(resource.status)}`} />
+
+ {/* Name and ID */}
+ <div class="flex-1 min-w-0">
+ <div class="text-sm text-white truncate">{getDisplayName(resource)}</div>
+ <div class="text-xs text-slate-500 truncate">{resource.id}</div>
+ </div>
+
+ {/* Type badge */}
+ <span class={`text-xs px-2 py-0.5 rounded-full flex-shrink-0 ${badge.classes}`}>
+ {badge.label}
+ </span>
+
+ {/* Tags */}
+ <Show when={resource.tags && resource.tags.length > 0}>
+ <div class="flex gap-1 flex-shrink-0">
+ <For each={resource.tags?.slice(0, 2)}>
+ {(tag) => (
+ <span class="text-xs px-1.5 py-0.5 rounded bg-slate-700 text-slate-300">
+ {tag}
+ </span>
+ )}
+ </For>
+ <Show when={(resource.tags?.length ?? 0) > 2}>
+ <span class="text-xs text-slate-500">+{(resource.tags?.length ?? 0) - 2}</span>
+ </Show>
+ </div>
+ </Show>
+ </button>
+ );
+ }}
+ </For>
+ </div>
+ </Show>
+ </Show>
+ </div>
+
+ {/* Action bar */}
+ <div class="flex items-center justify-between">
+ <div class="flex gap-2">
+ <button
+ class="flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg border border-slate-700 text-slate-400 hover:border-slate-500 hover:text-slate-300 transition-colors"
+ onClick={selectAllVisible}
+ >
+ <CheckSquare size={14} />
+ Select all visible ({filteredResources().length})
+ </button>
+ <Show when={props.selected().length > 0}>
+ <button
+ class="flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg border border-slate-700 text-slate-400 hover:border-red-500/50 hover:text-red-400 transition-colors"
+ onClick={clearAll}
+ >
+ <XSquare size={14} />
+ Clear all
+ </button>
+ </Show>
+ </div>
+ <span class="text-xs text-slate-500">
+ {props.selected().length} selected
+ <Show when={props.selected().length >= MAX_SELECTION}>
+ <span class="text-amber-400 ml-1">(max)</span>
+ </Show>
+ </span>
+ </div>
+
+ {/* Selected summary chips */}
+ <Show when={props.selected().length > 0}>
+ <div class="flex flex-wrap gap-1.5">
+ <For each={props.selected()}>
+ {(item) => (
+ <span class="inline-flex items-center gap-1 pl-2 pr-1 py-1 rounded-lg bg-blue-600/10 border border-blue-500/30 text-sm text-blue-300">
+ {item.name}
+ <button
+ class="p-0.5 rounded hover:bg-blue-500/20 transition-colors"
+ onClick={() => removeSelected(item.id)}
+ >
+ <X size={12} />
+ </button>
+ </span>
+ )}
+ </For>
+ </div>
+ </Show>
+ </div>
+ );
+}
diff --git a/internal/api/reporting_handlers.go b/internal/api/reporting_handlers.go
index c1bb77041f..4f4e0cbb89 100644
--- a/internal/api/reporting_handlers.go
+++ b/internal/api/reporting_handlers.go
@@ -1,6 +1,7 @@
package api
import (
+ "encoding/json"
"fmt"
"net/http"
"regexp"
@@ -12,8 +13,8 @@ import (
"github.com/rcourtman/pulse-go-rewrite/pkg/reporting"
)
-// validResourceID matches safe resource identifiers for filenames
-var validResourceID = regexp.MustCompile(`^[a-zA-Z0-9._-]+$`)
+// validResourceID matches safe resource identifiers (includes colon for guest IDs like "instance:node:vmid")
+var validResourceID = regexp.MustCompile(`^[a-zA-Z0-9._:-]+$`)
// ReportingHandlers handles reporting-related requests
type ReportingHandlers struct {
@@ -124,6 +125,7 @@ func sanitizeFilename(s string) string {
s = strings.ReplaceAll(s, "\"", "")
s = strings.ReplaceAll(s, "\\", "")
s = strings.ReplaceAll(s, "/", "-")
+ s = strings.ReplaceAll(s, ":", "-")
s = strings.ReplaceAll(s, "\r", "")
s = strings.ReplaceAll(s, "\n", "")
@@ -320,6 +322,136 @@ func (h *ReportingHandlers) enrichVMReport(req *reporting.MetricReportRequest, s
}
}
+// multiReportResourceEntry represents a single resource in a multi-report request body.
+type multiReportResourceEntry struct {
+ ResourceType string `json:"resourceType"`
+ ResourceID string `json:"resourceId"`
+}
+
+// multiReportRequestBody is the JSON body for multi-resource report generation.
+type multiReportRequestBody struct {
+ Resources []multiReportResourceEntry `json:"resources"`
+ Format string `json:"format"`
+ Start string `json:"start"`
+ End string `json:"end"`
+ Title string `json:"title"`
+ MetricType string `json:"metricType"`
+}
+
+// HandleGenerateMultiReport generates a multi-resource report.
+func (h *ReportingHandlers) HandleGenerateMultiReport(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+
+ engine := reporting.GetEngine()
+ if engine == nil {
+ writeErrorResponse(w, http.StatusInternalServerError, "engine_unavailable", "Reporting engine not initialized", nil)
+ return
+ }
+
+ var body multiReportRequestBody
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_body", "Invalid request body", nil)
+ return
+ }
+
+ // Validate resource count
+ if len(body.Resources) == 0 {
+ writeErrorResponse(w, http.StatusBadRequest, "no_resources", "At least one resource is required", nil)
+ return
+ }
+ if len(body.Resources) > 50 {
+ writeErrorResponse(w, http.StatusBadRequest, "too_many_resources", "Maximum 50 resources allowed", nil)
+ return
+ }
+
+ // Validate format
+ format := reporting.ReportFormat(body.Format)
+ if format == "" {
+ format = reporting.FormatPDF
+ }
+ if format != reporting.FormatPDF && format != reporting.FormatCSV {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_format", "Format must be 'pdf' or 'csv'", nil)
+ return
+ }
+
+ // Parse time range
+ end := time.Now()
+ if body.End != "" {
+ if t, err := time.Parse(time.RFC3339, body.End); err == nil {
+ end = t
+ }
+ }
+ start := end.Add(-24 * time.Hour)
+ if body.Start != "" {
+ if t, err := time.Parse(time.RFC3339, body.Start); err == nil {
+ start = t
+ }
+ }
+
+ // Build multi-report request
+ multiReq := reporting.MultiReportRequest{
+ Format: format,
+ Start: start,
+ End: end,
+ Title: body.Title,
+ MetricType: body.MetricType,
+ }
+
+ // Get monitor state for enrichment
+ var state models.StateSnapshot
+ var hasState bool
+ if h.mtMonitor != nil {
+ orgID := GetOrgID(r.Context())
+ if monitor, err := h.mtMonitor.GetMonitor(orgID); err == nil && monitor != nil {
+ state = monitor.GetState()
+ hasState = true
+ }
+ }
+
+ // Validate and build each resource request
+ for _, res := range body.Resources {
+ if !validResourceID.MatchString(res.ResourceType) || len(res.ResourceType) > 64 {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_resource_type", fmt.Sprintf("Invalid resourceType: %s", res.ResourceType), nil)
+ return
+ }
+ if !validResourceID.MatchString(res.ResourceID) || len(res.ResourceID) > 128 {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_resource_id", fmt.Sprintf("Invalid resourceId: %s", res.ResourceID), nil)
+ return
+ }
+
+ req := reporting.MetricReportRequest{
+ ResourceType: res.ResourceType,
+ ResourceID: res.ResourceID,
+ MetricType: body.MetricType,
+ Start: start,
+ End: end,
+ Format: format,
+ Title: body.Title,
+ }
+
+ // Enrich with resource data
+ if hasState {
+ h.enrichReportRequest(&req, state, start, end)
+ }
+
+ multiReq.Resources = append(multiReq.Resources, req)
+ }
+
+ data, contentType, err := engine.GenerateMulti(multiReq)
+ if err != nil {
+ writeErrorResponse(w, http.StatusInternalServerError, "generation_failed", "Failed to generate multi-resource report", nil)
+ return
+ }
+
+ w.Header().Set("Content-Type", contentType)
+ filename := fmt.Sprintf("fleet-report-%s.%s", time.Now().Format("20060102"), format)
+ w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filename))
+ w.Write(data)
+}
+
// enrichContainerReport adds container-specific data to the report request
func (h *ReportingHandlers) enrichContainerReport(req *reporting.MetricReportRequest, state models.StateSnapshot, start, end time.Time) {
// Find the container
diff --git a/internal/api/reporting_handlers_test.go b/internal/api/reporting_handlers_test.go
index e31828a4ea..aab7e76e65 100644
--- a/internal/api/reporting_handlers_test.go
+++ b/internal/api/reporting_handlers_test.go
@@ -17,6 +17,7 @@ type stubReportingEngine struct {
contentType string
err error
lastReq reporting.MetricReportRequest
+ lastMulti reporting.MultiReportRequest
}
func (s *stubReportingEngine) Generate(req reporting.MetricReportRequest) ([]byte, string, error) {
@@ -27,6 +28,14 @@ func (s *stubReportingEngine) Generate(req reporting.MetricReportRequest) ([]byt
return s.data, s.contentType, nil
}
+func (s *stubReportingEngine) GenerateMulti(req reporting.MultiReportRequest) ([]byte, string, error) {
+ s.lastMulti = req
+ if s.err != nil {
+ return nil, "", s.err
+ }
+ return s.data, s.contentType, nil
+}
+
func TestReportingHandlers_MethodNotAllowed(t *testing.T) {
handler := NewReportingHandlers(nil)
req := httptest.NewRequest(http.MethodPost, "/api/reporting", nil)
diff --git a/internal/api/router.go b/internal/api/router.go
index 5be40d69b3..731587c1f1 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -568,6 +568,7 @@ func (r *Router) setupRoutes() {
// Advanced Reporting routes
r.mux.HandleFunc("/api/admin/reports/generate", RequirePermission(r.config, r.authorizer, auth.ActionRead, auth.ResourceNodes, RequireLicenseFeature(r.licenseHandlers, license.FeatureAdvancedReporting, RequireScope(config.ScopeSettingsRead, r.reportingHandlers.HandleGenerateReport))))
+ r.mux.HandleFunc("/api/admin/reports/generate-multi", RequirePermission(r.config, r.authorizer, auth.ActionRead, auth.ResourceNodes, RequireLicenseFeature(r.licenseHandlers, license.FeatureAdvancedReporting, RequireScope(config.ScopeSettingsRead, r.reportingHandlers.HandleGenerateMultiReport))))
// Audit Webhook routes
r.mux.HandleFunc("/api/admin/webhooks/audit", RequirePermission(r.config, r.authorizer, auth.ActionAdmin, auth.ResourceAuditLogs, RequireLicenseFeature(r.licenseHandlers, license.FeatureAuditLogging, func(w http.ResponseWriter, req *http.Request) {
diff --git a/pkg/reporting/csv.go b/pkg/reporting/csv.go
index 7cabcd044c..b7284d5d4d 100644
--- a/pkg/reporting/csv.go
+++ b/pkg/reporting/csv.go
@@ -180,6 +180,182 @@ func (g *CSVGenerator) writeData(w *csv.Writer, data *ReportData) error {
return nil
}
+// GenerateMulti creates a multi-resource CSV report from the provided data.
+func (g *CSVGenerator) GenerateMulti(data *MultiReportData) ([]byte, error) {
+ var buf bytes.Buffer
+ w := csv.NewWriter(&buf)
+
+ // Write header comment rows
+ headers := [][]string{
+ {"# Pulse Multi-Resource Metrics Report"},
+ {"# Title:", data.Title},
+ {"# Resources:", fmt.Sprintf("%d", len(data.Resources))},
+ {"# Period:", fmt.Sprintf("%s to %s", data.Start.Format(time.RFC3339), data.End.Format(time.RFC3339))},
+ {"# Generated:", data.GeneratedAt.Format(time.RFC3339)},
+ {"# Total Data Points:", fmt.Sprintf("%d", data.TotalPoints)},
+ {""},
+ }
+ for _, row := range headers {
+ if err := w.Write(row); err != nil {
+ return nil, err
+ }
+ }
+
+ // Write summary section
+ if err := w.Write([]string{"# SUMMARY"}); err != nil {
+ return nil, err
+ }
+
+ // Summary column headers
+ summaryHeaders := []string{"Resource Name", "Resource Type", "Resource ID", "Metric", "Count", "Min", "Max", "Average", "Current", "Unit"}
+ if err := w.Write(summaryHeaders); err != nil {
+ return nil, err
+ }
+
+ // Write summary rows for each resource
+ for _, rd := range data.Resources {
+ resourceName := rd.ResourceID
+ if rd.Resource != nil && rd.Resource.Name != "" {
+ resourceName = rd.Resource.Name
+ }
+ resourceTypeDisplay := GetResourceTypeDisplayName(rd.ResourceType)
+
+ metricNames := make([]string, 0, len(rd.Summary.ByMetric))
+ for name := range rd.Summary.ByMetric {
+ metricNames = append(metricNames, name)
+ }
+ sort.Strings(metricNames)
+
+ for _, metricType := range metricNames {
+ stats := rd.Summary.ByMetric[metricType]
+ unit := GetMetricUnit(metricType)
+ row := []string{
+ resourceName,
+ resourceTypeDisplay,
+ rd.ResourceID,
+ GetMetricTypeDisplayName(metricType),
+ fmt.Sprintf("%d", stats.Count),
+ formatValue(stats.Min, unit),
+ formatValue(stats.Max, unit),
+ formatValue(stats.Avg, unit),
+ formatValue(stats.Current, unit),
+ unit,
+ }
+ if err := w.Write(row); err != nil {
+ return nil, err
+ }
+ }
+ }
+
+ // Empty separator
+ if err := w.Write([]string{""}); err != nil {
+ return nil, err
+ }
+
+ // Write data section
+ if err := w.Write([]string{"# DATA"}); err != nil {
+ return nil, err
+ }
+
+ // Collect all unique metric names across all resources
+ metricNameSet := make(map[string]bool)
+ for _, rd := range data.Resources {
+ for name := range rd.Metrics {
+ metricNameSet[name] = true
+ }
+ }
+ metricNames := make([]string, 0, len(metricNameSet))
+ for name := range metricNameSet {
+ metricNames = append(metricNames, name)
+ }
+ sort.Strings(metricNames)
+
+ // Build data header row
+ headerRow := []string{"Timestamp", "Resource Name", "Resource Type", "Resource ID"}
+ for _, name := range metricNames {
+ unit := GetMetricUnit(name)
+ if unit != "" {
+ headerRow = append(headerRow, fmt.Sprintf("%s (%s)", GetMetricTypeDisplayName(name), unit))
+ } else {
+ headerRow = append(headerRow, GetMetricTypeDisplayName(name))
+ }
+ }
+ if err := w.Write(headerRow); err != nil {
+ return nil, err
+ }
+
+ // Collect all data points across all resources, with resource info
+ type dataRow struct {
+ timestamp int64
+ resourceName string
+ resourceType string
+ resourceID string
+ values map[string]float64
+ }
+
+ var allRows []dataRow
+ for _, rd := range data.Resources {
+ resourceName := rd.ResourceID
+ if rd.Resource != nil && rd.Resource.Name != "" {
+ resourceName = rd.Resource.Name
+ }
+ resourceTypeDisplay := GetResourceTypeDisplayName(rd.ResourceType)
+
+ // Build a map of timestamp -> metric values for this resource
+ timestampValues := make(map[int64]map[string]float64)
+ for metricName, points := range rd.Metrics {
+ for _, p := range points {
+ ts := p.Timestamp.Unix()
+ if timestampValues[ts] == nil {
+ timestampValues[ts] = make(map[string]float64)
+ }
+ timestampValues[ts][metricName] = p.Value
+ }
+ }
+
+ for ts, values := range timestampValues {
+ allRows = append(allRows, dataRow{
+ timestamp: ts,
+ resourceName: resourceName,
+ resourceType: resourceTypeDisplay,
+ resourceID: rd.ResourceID,
+ values: values,
+ })
+ }
+ }
+
+ // Sort by timestamp, then by resource name
+ sort.Slice(allRows, func(i, j int) bool {
+ if allRows[i].timestamp != allRows[j].timestamp {
+ return allRows[i].timestamp < allRows[j].timestamp
+ }
+ return allRows[i].resourceName < allRows[j].resourceName
+ })
+
+ // Write data rows
+ for _, row := range allRows {
+ t := time.Unix(row.timestamp, 0)
+ csvRow := []string{t.Format(time.RFC3339), row.resourceName, row.resourceType, row.resourceID}
+ for _, metricName := range metricNames {
+ if val, ok := row.values[metricName]; ok {
+ csvRow = append(csvRow, fmt.Sprintf("%.2f", val))
+ } else {
+ csvRow = append(csvRow, "")
+ }
+ }
+ if err := w.Write(csvRow); err != nil {
+ return nil, err
+ }
+ }
+
+ w.Flush()
+ if err := w.Error(); err != nil {
+ return nil, fmt.Errorf("CSV write error: %w", err)
+ }
+
+ return buf.Bytes(), nil
+}
+
// formatValue formats a metric value with appropriate precision.
func formatValue(value float64, unit string) string {
if unit == "bytes" {
diff --git a/pkg/reporting/engine.go b/pkg/reporting/engine.go
index 13a5d73220..f4dffea37f 100644
--- a/pkg/reporting/engine.go
+++ b/pkg/reporting/engine.go
@@ -202,6 +202,78 @@ func (e *ReportEngine) queryMetrics(req MetricReportRequest) (*ReportData, error
return data, nil
}
+// GenerateMulti creates a multi-resource report in the specified format.
+func (e *ReportEngine) GenerateMulti(req MultiReportRequest) (data []byte, contentType string, err error) {
+ if e.metricsStore == nil {
+ return nil, "", fmt.Errorf("metrics store not initialized")
+ }
+
+ multiData := &MultiReportData{
+ Title: req.Title,
+ Start: req.Start,
+ End: req.End,
+ GeneratedAt: time.Now(),
+ }
+
+ if multiData.Title == "" {
+ multiData.Title = "Fleet Performance Report"
+ }
+
+ // Query metrics for each resource
+ var successCount int
+ for _, resReq := range req.Resources {
+ resReq.Start = req.Start
+ resReq.End = req.End
+ resReq.MetricType = req.MetricType
+
+ reportData, queryErr := e.queryMetrics(resReq)
+ if queryErr != nil {
+ log.Warn().
+ Str("resourceType", resReq.ResourceType).
+ Str("resourceID", resReq.ResourceID).
+ Err(queryErr).
+ Msg("Skipping resource in multi-report: failed to query metrics")
+ continue
+ }
+
+ multiData.Resources = append(multiData.Resources, reportData)
+ multiData.TotalPoints += reportData.TotalPoints
+ successCount++
+ }
+
+ if successCount == 0 {
+ return nil, "", fmt.Errorf("all resources failed to query metrics")
+ }
+
+ log.Debug().
+ Int("resources", successCount).
+ Int("skipped", len(req.Resources)-successCount).
+ Str("format", string(req.Format)).
+ Int("totalPoints", multiData.TotalPoints).
+ Msg("Generating multi-resource report")
+
+ switch req.Format {
+ case FormatCSV:
+ data, err = e.csvGen.GenerateMulti(multiData)
+ if err != nil {
+ return nil, "", fmt.Errorf("CSV generation failed: %w", err)
+ }
+ contentType = "text/csv"
+
+ case FormatPDF:
+ data, err = e.pdfGen.GenerateMulti(multiData)
+ if err != nil {
+ return nil, "", fmt.Errorf("PDF generation failed: %w", err)
+ }
+ contentType = "application/pdf"
+
+ default:
+ return nil, "", fmt.Errorf("unsupported format: %s", req.Format)
+ }
+
+ return data, contentType, nil
+}
+
// GetResourceTypeDisplayName returns a human-readable name for resource types.
func GetResourceTypeDisplayName(resourceType string) string {
switch resourceType {
diff --git a/pkg/reporting/multi_report_visual_test.go b/pkg/reporting/multi_report_visual_test.go
new file mode 100644
index 0000000000..0df7f39537
--- /dev/null
+++ b/pkg/reporting/multi_report_visual_test.go
@@ -0,0 +1,474 @@
+package reporting
+
+import (
+ "fmt"
+ "math"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+)
+
+// TestMultiReportVisualInspection generates actual PDF and CSV files
+// for visual inspection. Run with:
+//
+// go test ./pkg/reporting/ -run TestMultiReportVisualInspection -v
+//
+// Output files will be written to the system temp directory.
+func TestMultiReportVisualInspection(t *testing.T) {
+ outDir := t.TempDir()
+
+ data := createMultiTestReportData()
+
+ // Generate multi-resource PDF
+ pdfGen := NewPDFGenerator()
+ pdfBytes, err := pdfGen.GenerateMulti(data)
+ if err != nil {
+ t.Fatalf("Multi-resource PDF generation failed: %v", err)
+ }
+
+ pdfPath := filepath.Join(outDir, "multi-resource-report.pdf")
+ if err := os.WriteFile(pdfPath, pdfBytes, 0644); err != nil {
+ t.Fatalf("Failed to write PDF: %v", err)
+ }
+ t.Logf("Multi-resource PDF written to: %s (%d bytes, %d pages estimated)", pdfPath, len(pdfBytes), estimatePages(pdfBytes))
+
+ // Generate multi-resource CSV
+ csvGen := NewCSVGenerator()
+ csvBytes, err := csvGen.GenerateMulti(data)
+ if err != nil {
+ t.Fatalf("Multi-resource CSV generation failed: %v", err)
+ }
+
+ csvPath := filepath.Join(outDir, "multi-resource-report.csv")
+ if err := os.WriteFile(csvPath, csvBytes, 0644); err != nil {
+ t.Fatalf("Failed to write CSV: %v", err)
+ }
+ t.Logf("Multi-resource CSV written to: %s (%d bytes)", csvPath, len(csvBytes))
+
+ // Also generate a single-resource PDF for comparison
+ singlePdfBytes, err := pdfGen.Generate(data.Resources[0])
+ if err != nil {
+ t.Fatalf("Single-resource PDF generation failed: %v", err)
+ }
+ singlePdfPath := filepath.Join(outDir, "single-resource-report.pdf")
+ if err := os.WriteFile(singlePdfPath, singlePdfBytes, 0644); err != nil {
+ t.Fatalf("Failed to write single PDF: %v", err)
+ }
+ t.Logf("Single-resource PDF written to: %s (%d bytes)", singlePdfPath, len(singlePdfBytes))
+
+ // Basic sanity checks
+ if string(pdfBytes[:4]) != "%PDF" {
+ t.Error("Multi PDF missing magic bytes")
+ }
+ if len(pdfBytes) < 5000 {
+ t.Errorf("Multi PDF seems too small: %d bytes", len(pdfBytes))
+ }
+
+ // CSV content checks
+ csvStr := string(csvBytes)
+ expectedStrings := []string{
+ "# Pulse Multi-Resource Metrics Report",
+ "# SUMMARY",
+ "# DATA",
+ "Resource Name",
+ "Resource Type",
+ "Resource ID",
+ "pve1-node1", // node resource ID
+ "web-01", // VM name
+ "db-container-1", // container name
+ "CPU Usage",
+ "Memory Usage",
+ }
+ for _, s := range expectedStrings {
+ if !contains(csvStr, s) {
+ t.Errorf("CSV missing expected content: %q", s)
+ }
+ }
+
+ // Copy files to a persistent location so the user can inspect them
+ persistDir := filepath.Join(os.TempDir(), "pulse-report-visual-test")
+ os.MkdirAll(persistDir, 0755)
+
+ copyFile(t, pdfPath, filepath.Join(persistDir, "multi-resource-report.pdf"))
+ copyFile(t, csvPath, filepath.Join(persistDir, "multi-resource-report.csv"))
+ copyFile(t, singlePdfPath, filepath.Join(persistDir, "single-resource-report.pdf"))
+
+ t.Logf("\n=== FILES FOR VISUAL INSPECTION ===")
+ t.Logf("Multi-resource PDF: %s", filepath.Join(persistDir, "multi-resource-report.pdf"))
+ t.Logf("Multi-resource CSV: %s", filepath.Join(persistDir, "multi-resource-report.csv"))
+ t.Logf("Single-resource PDF: %s", filepath.Join(persistDir, "single-resource-report.pdf"))
+ t.Logf("Open with: open %s", persistDir)
+}
+
+func contains(s, substr string) bool {
+ return len(s) > 0 && len(substr) > 0 && (len(s) >= len(substr)) && (s == substr || len(s) > 0 && containsString(s, substr))
+}
+
+func containsString(s, substr string) bool {
+ for i := 0; i <= len(s)-len(substr); i++ {
+ if s[i:i+len(substr)] == substr {
+ return true
+ }
+ }
+ return false
+}
+
+func copyFile(t *testing.T, src, dst string) {
+ t.Helper()
+ data, err := os.ReadFile(src)
+ if err != nil {
+ t.Logf("Warning: could not read %s: %v", src, err)
+ return
+ }
+ if err := os.WriteFile(dst, data, 0644); err != nil {
+ t.Logf("Warning: could not write %s: %v", dst, err)
+ }
+}
+
+func estimatePages(pdfBytes []byte) int {
+ // Count "/Type /Page" occurrences as rough page estimate
+ count := 0
+ needle := []byte("/Type /Page\n")
+ for i := 0; i <= len(pdfBytes)-len(needle); i++ {
+ match := true
+ for j := 0; j < len(needle); j++ {
+ if pdfBytes[i+j] != needle[j] {
+ match = false
+ break
+ }
+ }
+ if match {
+ count++
+ }
+ }
+ if count == 0 {
+ return -1
+ }
+ return count
+}
+
+// createMultiTestReportData creates rich test data with multiple resources,
+// enrichment data, alerts, storage, backups, and disk info.
+func createMultiTestReportData() *MultiReportData {
+ now := time.Now()
+ start := now.Add(-7 * 24 * time.Hour) // 7 days
+
+ return &MultiReportData{
+ Title: "Fleet Performance Report",
+ Start: start,
+ End: now,
+ GeneratedAt: now,
+ Resources: []*ReportData{
+ createNodeReportData("pve1-node1", "pve1", start, now),
+ createNodeReportData("pve1-node2", "pve2", start, now),
+ createVMReportData("pve1-node1-100", "web-01", start, now),
+ createVMReportData("pve1-node1-101", "api-server", start, now),
+ createContainerReportData("pve1-node2-200", "db-container-1", start, now),
+ },
+ TotalPoints: 168 * 3 * 5, // 168 points * 3 metrics * 5 resources
+ }
+}
+
+func createNodeReportData(id, name string, start, end time.Time) *ReportData {
+ cpuPoints := generateMetricPoints(start, end, 168, 15, 85, 45)
+ memPoints := generateMetricPoints(start, end, 168, 40, 92, 72)
+ diskPoints := generateMetricPoints(start, end, 168, 30, 55, 42)
+
+ cpuTemp := 62.0
+
+ return &ReportData{
+ Title: fmt.Sprintf("Node Report: %s", name),
+ ResourceType: "node",
+ ResourceID: id,
+ Start: start,
+ End: end,
+ GeneratedAt: time.Now(),
+ Metrics: map[string][]MetricDataPoint{
+ "cpu": cpuPoints,
+ "memory": memPoints,
+ "disk": diskPoints,
+ },
+ Summary: computeSummary(cpuPoints, memPoints, diskPoints),
+ TotalPoints: len(cpuPoints) + len(memPoints) + len(diskPoints),
+ Resource: &ResourceInfo{
+ Name: name,
+ DisplayName: name,
+ Status: "online",
+ Host: fmt.Sprintf("https://%s.local:8006", name),
+ Instance: "pve1",
+ Uptime: 432000, // 5 days
+ KernelVersion: "6.8.12-1-pve",
+ PVEVersion: "8.3.1",
+ CPUModel: "AMD EPYC 7543P 32-Core Processor",
+ CPUCores: 32,
+ CPUSockets: 1,
+ MemoryTotal: 137438953472, // 128 GiB
+ DiskTotal: 1099511627776, // 1 TiB
+ LoadAverage: []float64{2.45, 1.82, 1.64},
+ Temperature: &cpuTemp,
+ Tags: []string{"production", "cluster-a"},
+ ClusterName: "prod-cluster",
+ IsCluster: true,
+ },
+ Alerts: []AlertInfo{
+ {
+ Type: "cpu",
+ Level: "warning",
+ Message: "CPU usage above 80% for 5 minutes",
+ Value: 84.5,
+ Threshold: 80,
+ StartTime: end.Add(-2 * time.Hour),
+ },
+ },
+ Storage: []StorageInfo{
+ {
+ Name: "local-zfs",
+ Type: "zfspool",
+ Status: "active",
+ Total: 536870912000,
+ Used: 268435456000,
+ Available: 268435456000,
+ UsagePerc: 50.0,
+ Content: "rootdir,images",
+ },
+ {
+ Name: "local-lvm",
+ Type: "lvmthin",
+ Status: "active",
+ Total: 1099511627776,
+ Used: 659706976666,
+ Available: 439804651110,
+ UsagePerc: 60.0,
+ Content: "images,rootdir",
+ },
+ {
+ Name: "nfs-backups",
+ Type: "nfs",
+ Status: "active",
+ Total: 4398046511104,
+ Used: 3958241860394,
+ Available: 439804651110,
+ UsagePerc: 90.1,
+ Content: "backup",
+ },
+ },
+ Disks: []DiskInfo{
+ {
+ Device: "/dev/nvme0n1",
+ Model: "Samsung SSD 990 PRO 2TB",
+ Serial: "S6Z2NF0WB12345",
+ Type: "nvme",
+ Size: 2000398934016,
+ Health: "PASSED",
+ Temperature: 38,
+ WearLevel: 95,
+ },
+ {
+ Device: "/dev/sda",
+ Model: "WDC WD40EFAX-68JH4N1",
+ Serial: "WD-WXB2D8123456",
+ Type: "hdd",
+ Size: 4000787030016,
+ Health: "PASSED",
+ Temperature: 34,
+ WearLevel: -1,
+ },
+ },
+ }
+}
+
+func createVMReportData(id, name string, start, end time.Time) *ReportData {
+ cpuPoints := generateMetricPoints(start, end, 168, 5, 95, 22)
+ memPoints := generateMetricPoints(start, end, 168, 50, 98, 88)
+ diskPoints := generateMetricPoints(start, end, 168, 20, 45, 35)
+
+ backupTime := end.Add(-24 * time.Hour)
+ return &ReportData{
+ Title: fmt.Sprintf("VM Report: %s", name),
+ ResourceType: "vm",
+ ResourceID: id,
+ Start: start,
+ End: end,
+ GeneratedAt: time.Now(),
+ Metrics: map[string][]MetricDataPoint{
+ "cpu": cpuPoints,
+ "memory": memPoints,
+ "disk": diskPoints,
+ },
+ Summary: computeSummary(cpuPoints, memPoints, diskPoints),
+ TotalPoints: len(cpuPoints) + len(memPoints) + len(diskPoints),
+ Resource: &ResourceInfo{
+ Name: name,
+ DisplayName: name,
+ Status: "running",
+ Node: "pve1",
+ Instance: "pve1",
+ Uptime: 864000, // 10 days
+ OSName: "Ubuntu",
+ OSVersion: "24.04",
+ IPAddresses: []string{"10.0.1.50", "192.168.1.50"},
+ CPUCores: 4,
+ MemoryTotal: 8589934592, // 8 GiB
+ DiskTotal: 53687091200, // 50 GiB
+ Tags: []string{"web", "production"},
+ },
+ Alerts: []AlertInfo{
+ {
+ Type: "memory",
+ Level: "critical",
+ Message: "Memory usage above 95% - OOM risk",
+ Value: 96.2,
+ Threshold: 95,
+ StartTime: end.Add(-30 * time.Minute),
+ },
+ {
+ Type: "cpu",
+ Level: "warning",
+ Message: "CPU usage above 80% sustained",
+ Value: 88.4,
+ Threshold: 80,
+ StartTime: end.Add(-6 * time.Hour),
+ ResolvedTime: timePtr(end.Add(-4 * time.Hour)),
+ },
+ },
+ Backups: []BackupInfo{
+ {
+ Type: "vzdump",
+ Storage: "nfs-backups",
+ Timestamp: backupTime,
+ Size: 4294967296, // 4 GiB
+ Protected: true,
+ VolID: "nfs-backups:vzdump/vzdump-qemu-100-2024_01_01-00_00_00.vma.zst",
+ },
+ {
+ Type: "vzdump",
+ Storage: "nfs-backups",
+ Timestamp: backupTime.Add(-24 * time.Hour),
+ Size: 4190000000,
+ Protected: false,
+ VolID: "nfs-backups:vzdump/vzdump-qemu-100-2023_12_31-00_00_00.vma.zst",
+ },
+ },
+ }
+}
+
+func createContainerReportData(id, name string, start, end time.Time) *ReportData {
+ cpuPoints := generateMetricPoints(start, end, 168, 2, 35, 12)
+ memPoints := generateMetricPoints(start, end, 168, 30, 65, 48)
+ diskPoints := generateMetricPoints(start, end, 168, 10, 25, 18)
+
+ backupTime := end.Add(-48 * time.Hour)
+ return &ReportData{
+ Title: fmt.Sprintf("Container Report: %s", name),
+ ResourceType: "container",
+ ResourceID: id,
+ Start: start,
+ End: end,
+ GeneratedAt: time.Now(),
+ Metrics: map[string][]MetricDataPoint{
+ "cpu": cpuPoints,
+ "memory": memPoints,
+ "disk": diskPoints,
+ },
+ Summary: computeSummary(cpuPoints, memPoints, diskPoints),
+ TotalPoints: len(cpuPoints) + len(memPoints) + len(diskPoints),
+ Resource: &ResourceInfo{
+ Name: name,
+ DisplayName: name,
+ Status: "running",
+ Node: "pve2",
+ Instance: "pve1",
+ Uptime: 2592000, // 30 days
+ OSName: "Debian",
+ OSVersion: "12",
+ IPAddresses: []string{"10.0.2.10"},
+ CPUCores: 2,
+ MemoryTotal: 2147483648, // 2 GiB
+ DiskTotal: 10737418240, // 10 GiB
+ Tags: []string{"database", "staging"},
+ },
+ Backups: []BackupInfo{
+ {
+ Type: "vzdump",
+ Storage: "nfs-backups",
+ Timestamp: backupTime,
+ Size: 1073741824, // 1 GiB
+ Protected: false,
+ VolID: "nfs-backups:vzdump/vzdump-lxc-200-2024_01_01-00_00_00.tar.zst",
+ },
+ },
+ }
+}
+
+// generateMetricPoints creates realistic metric data with variation.
+func generateMetricPoints(start, end time.Time, count int, minVal, maxVal, baseVal float64) []MetricDataPoint {
+ points := make([]MetricDataPoint, count)
+ duration := end.Sub(start)
+ interval := duration / time.Duration(count)
+
+ for i := 0; i < count; i++ {
+ ts := start.Add(time.Duration(i) * interval)
+
+ // Generate realistic variation using sine waves
+ hourFraction := float64(i) / float64(count)
+ // Daily pattern (higher during "business hours")
+ dailyPattern := math.Sin(hourFraction*2*math.Pi) * 0.3
+ // Random-ish noise using multiple sine waves
+ noise := math.Sin(float64(i)*0.7) * 0.1
+ noise += math.Sin(float64(i)*1.3) * 0.05
+
+ val := baseVal + (maxVal-minVal)*(dailyPattern+noise)
+ val = math.Max(minVal, math.Min(maxVal, val))
+
+ points[i] = MetricDataPoint{
+ Timestamp: ts,
+ Value: val,
+ Min: math.Max(minVal, val-3),
+ Max: math.Min(maxVal, val+3),
+ }
+ }
+ return points
+}
+
+// computeSummary calculates summary statistics from metric points.
+func computeSummary(cpuPoints, memPoints, diskPoints []MetricDataPoint) MetricSummary {
+ return MetricSummary{
+ ByMetric: map[string]MetricStats{
+ "cpu": computeStats("cpu", cpuPoints),
+ "memory": computeStats("memory", memPoints),
+ "disk": computeStats("disk", diskPoints),
+ },
+ }
+}
+
+func computeStats(metricType string, points []MetricDataPoint) MetricStats {
+ if len(points) == 0 {
+ return MetricStats{MetricType: metricType}
+ }
+
+ stats := MetricStats{
+ MetricType: metricType,
+ Count: len(points),
+ Min: points[0].Value,
+ Max: points[0].Value,
+ Current: points[len(points)-1].Value,
+ }
+
+ var sum float64
+ for _, p := range points {
+ sum += p.Value
+ if p.Value < stats.Min {
+ stats.Min = p.Value
+ }
+ if p.Value > stats.Max {
+ stats.Max = p.Value
+ }
+ }
+ stats.Avg = sum / float64(len(points))
+ return stats
+}
+
+func timePtr(t time.Time) *time.Time {
+ return &t
+}
diff --git a/pkg/reporting/pdf.go b/pkg/reporting/pdf.go
index 82ceec9092..146c3b702e 100644
--- a/pkg/reporting/pdf.go
+++ b/pkg/reporting/pdf.go
@@ -1622,6 +1622,717 @@ func (g *PDFGenerator) addPageNumbers(pdf *fpdf.Fpdf) {
}
}
+// GenerateMulti creates a multi-resource PDF report from the provided data.
+func (g *PDFGenerator) GenerateMulti(data *MultiReportData) ([]byte, error) {
+ pdf := fpdf.New("P", "mm", "A4", "")
+ pdf.SetMargins(20, 20, 20)
+ pdf.SetAutoPageBreak(true, 25)
+
+ // Page 1: Cover page
+ g.writeMultiCoverPage(pdf, data)
+
+ // Page 2: Fleet summary
+ pdf.AddPage()
+ g.addMultiPageHeader(pdf, data, "Fleet Summary")
+ g.writeFleetSummary(pdf, data)
+
+ // Pages 3+: Condensed per-resource pages
+ for _, rd := range data.Resources {
+ pdf.AddPage()
+ g.addMultiPageHeader(pdf, data, "Resource Detail")
+ g.writeCondensedResourcePage(pdf, rd)
+ }
+
+ // Add page numbers to all pages except cover
+ g.addMultiPageNumbers(pdf)
+
+ // Output to buffer
+ var buf bytes.Buffer
+ if err := pdf.Output(&buf); err != nil {
+ return nil, fmt.Errorf("PDF output error: %w", err)
+ }
+
+ return buf.Bytes(), nil
+}
+
+// writeMultiCoverPage creates a cover page for multi-resource reports.
+func (g *PDFGenerator) writeMultiCoverPage(pdf *fpdf.Fpdf, data *MultiReportData) {
+ pdf.AddPage()
+
+ pageWidth, pageHeight := pdf.GetPageSize()
+
+ // Top accent bar
+ pdf.SetFillColor(colorPrimary[0], colorPrimary[1], colorPrimary[2])
+ pdf.Rect(0, 0, pageWidth, 8, "F")
+
+ // Pulse branding area
+ pdf.SetY(50)
+ pdf.SetFont("Arial", "B", 32)
+ pdf.SetTextColor(colorPrimary[0], colorPrimary[1], colorPrimary[2])
+ pdf.CellFormat(0, 15, "PULSE", "", 1, "C", false, 0, "")
+
+ pdf.SetFont("Arial", "", 12)
+ pdf.SetTextColor(colorTextMuted[0], colorTextMuted[1], colorTextMuted[2])
+ pdf.CellFormat(0, 8, "Infrastructure Monitoring", "", 1, "C", false, 0, "")
+
+ // Main title
+ pdf.SetY(100)
+ pdf.SetFont("Arial", "B", 28)
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ pdf.CellFormat(0, 12, data.Title, "", 1, "C", false, 0, "")
+
+ // Subtitle with counts
+ pdf.SetY(120)
+ pdf.SetFont("Arial", "", 14)
+ pdf.SetTextColor(colorTextMuted[0], colorTextMuted[1], colorTextMuted[2])
+
+ // Calculate duration
+ duration := data.End.Sub(data.Start)
+ durationStr := formatDuration(duration)
+ subtitle := fmt.Sprintf("%d Resources | %s", len(data.Resources), durationStr)
+ pdf.CellFormat(0, 8, subtitle, "", 1, "C", false, 0, "")
+
+ // Scope box
+ pdf.SetY(140)
+ boxX := 40.0
+ boxWidth := pageWidth - 80
+ boxHeight := 40.0
+
+ pdf.SetFillColor(colorBackground[0], colorBackground[1], colorBackground[2])
+ pdf.SetDrawColor(colorGridLine[0], colorGridLine[1], colorGridLine[2])
+ pdf.RoundedRect(boxX, pdf.GetY(), boxWidth, boxHeight, 3, "1234", "FD")
+
+ // Count by type
+ nodeCount, vmCount, ctCount := 0, 0, 0
+ for _, rd := range data.Resources {
+ switch rd.ResourceType {
+ case "node":
+ nodeCount++
+ case "vm":
+ vmCount++
+ case "container":
+ ctCount++
+ }
+ }
+
+ pdf.SetY(pdf.GetY() + 10)
+ pdf.SetFont("Arial", "B", 11)
+ pdf.SetTextColor(colorTextMuted[0], colorTextMuted[1], colorTextMuted[2])
+ pdf.CellFormat(0, 7, "SCOPE", "", 1, "C", false, 0, "")
+
+ pdf.SetFont("Arial", "", 12)
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+
+ var scopeParts []string
+ if nodeCount > 0 {
+ word := "Nodes"
+ if nodeCount == 1 {
+ word = "Node"
+ }
+ scopeParts = append(scopeParts, fmt.Sprintf("%d %s", nodeCount, word))
+ }
+ if vmCount > 0 {
+ word := "VMs"
+ if vmCount == 1 {
+ word = "VM"
+ }
+ scopeParts = append(scopeParts, fmt.Sprintf("%d %s", vmCount, word))
+ }
+ if ctCount > 0 {
+ word := "Containers"
+ if ctCount == 1 {
+ word = "Container"
+ }
+ scopeParts = append(scopeParts, fmt.Sprintf("%d %s", ctCount, word))
+ }
+
+ scopeStr := ""
+ for i, part := range scopeParts {
+ if i > 0 {
+ scopeStr += ", "
+ }
+ scopeStr += part
+ }
+ pdf.CellFormat(0, 8, scopeStr, "", 1, "C", false, 0, "")
+
+ // Time period
+ pdf.SetY(200)
+ pdf.SetFont("Arial", "B", 11)
+ pdf.SetTextColor(colorTextMuted[0], colorTextMuted[1], colorTextMuted[2])
+ pdf.CellFormat(0, 7, "REPORTING PERIOD", "", 1, "C", false, 0, "")
+
+ pdf.SetFont("Arial", "", 12)
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ periodStr := fmt.Sprintf("%s - %s",
+ data.Start.Format("January 2, 2006 15:04"),
+ data.End.Format("January 2, 2006 15:04"))
+ pdf.CellFormat(0, 8, periodStr, "", 1, "C", false, 0, "")
+
+ pdf.SetFont("Arial", "", 10)
+ pdf.SetTextColor(colorTextMuted[0], colorTextMuted[1], colorTextMuted[2])
+ pdf.CellFormat(0, 6, fmt.Sprintf("(%s)", durationStr), "", 1, "C", false, 0, "")
+
+ // Bottom section
+ pdf.SetY(pageHeight - 50)
+ pdf.SetFont("Arial", "", 10)
+ pdf.SetTextColor(colorTextMuted[0], colorTextMuted[1], colorTextMuted[2])
+ pdf.CellFormat(0, 6, fmt.Sprintf("Generated: %s", data.GeneratedAt.Format("January 2, 2006 at 15:04 MST")), "", 1, "C", false, 0, "")
+ pdf.CellFormat(0, 6, fmt.Sprintf("Total Data Points: %d", data.TotalPoints), "", 1, "C", false, 0, "")
+
+ // Bottom accent bar
+ pdf.SetFillColor(colorPrimary[0], colorPrimary[1], colorPrimary[2])
+ pdf.Rect(0, pageHeight-8, pageWidth, 8, "F")
+}
+
+// addMultiPageHeader adds a consistent header to multi-report content pages.
+func (g *PDFGenerator) addMultiPageHeader(pdf *fpdf.Fpdf, data *MultiReportData, section string) {
+ pageWidth, _ := pdf.GetPageSize()
+
+ // Top line
+ pdf.SetDrawColor(colorPrimary[0], colorPrimary[1], colorPrimary[2])
+ pdf.SetLineWidth(0.5)
+ pdf.Line(20, 15, pageWidth-20, 15)
+
+ // Header text
+ pdf.SetY(18)
+ pdf.SetFont("Arial", "B", 9)
+ pdf.SetTextColor(colorPrimary[0], colorPrimary[1], colorPrimary[2])
+ pdf.CellFormat(0, 5, "PULSE FLEET REPORT", "", 0, "L", false, 0, "")
+
+ pdf.SetFont("Arial", "", 9)
+ pdf.SetTextColor(colorTextMuted[0], colorTextMuted[1], colorTextMuted[2])
+ pdf.CellFormat(0, 5, fmt.Sprintf("%d Resources", len(data.Resources)), "", 1, "R", false, 0, "")
+
+ // Section title
+ pdf.SetY(30)
+ pdf.SetFont("Arial", "B", 18)
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ pdf.CellFormat(0, 10, section, "", 1, "L", false, 0, "")
+
+ pdf.Ln(5)
+}
+
+// writeFleetSummary writes the fleet summary table and observations.
+func (g *PDFGenerator) writeFleetSummary(pdf *fpdf.Fpdf, data *MultiReportData) {
+ pageWidth, _ := pdf.GetPageSize()
+
+ // Determine aggregate health
+ healthStatus := "HEALTHY"
+ healthColor := colorAccent
+ healthMessage := "All systems operating normally"
+
+ totalActive := 0
+ totalCritical := 0
+ totalWarning := 0
+ for _, rd := range data.Resources {
+ for _, alert := range rd.Alerts {
+ if alert.ResolvedTime == nil {
+ totalActive++
+ if alert.Level == "critical" {
+ totalCritical++
+ } else {
+ totalWarning++
+ }
+ }
+ }
+ }
+
+ if totalCritical > 0 {
+ healthStatus = "CRITICAL"
+ healthColor = colorDanger
+ healthMessage = fmt.Sprintf("%d critical issues across fleet", totalCritical)
+ } else if totalWarning > 0 {
+ healthStatus = "WARNING"
+ healthColor = colorWarning
+ healthMessage = fmt.Sprintf("%d warnings across fleet", totalWarning)
+ }
+
+ // Health status card
+ cardX := 20.0
+ cardWidth := pageWidth - 40
+ cardHeight := 30.0
+
+ pdf.SetFillColor(healthColor[0], healthColor[1], healthColor[2])
+ pdf.RoundedRect(cardX, pdf.GetY(), cardWidth, cardHeight, 3, "1234", "F")
+
+ pdf.SetXY(cardX, pdf.GetY()+6)
+ pdf.SetFont("Arial", "B", 20)
+ pdf.SetTextColor(255, 255, 255)
+ pdf.CellFormat(cardWidth, 10, healthStatus, "", 1, "C", false, 0, "")
+ pdf.SetFont("Arial", "", 10)
+ pdf.CellFormat(cardWidth, 7, healthMessage, "", 1, "C", false, 0, "")
+
+ pdf.SetY(pdf.GetY() + 12)
+
+ // Summary table
+ pdf.SetFont("Arial", "B", 11)
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ pdf.CellFormat(0, 8, "Resource Summary", "", 1, "L", false, 0, "")
+ pdf.Ln(2)
+
+ // Table header
+ colWidths := []float64{40, 25, 20, 23, 23, 23, 16}
+ headers := []string{"Resource", "Type", "Status", "Avg CPU", "Avg Mem", "Avg Disk", "Alerts"}
+
+ pdf.SetFillColor(colorTableHeader[0], colorTableHeader[1], colorTableHeader[2])
+ pdf.SetTextColor(255, 255, 255)
+ pdf.SetFont("Arial", "B", 8)
+
+ for i, header := range headers {
+ pdf.CellFormat(colWidths[i], 7, header, "1", 0, "C", true, 0, "")
+ }
+ pdf.Ln(-1)
+
+ // Table rows
+ pdf.SetFont("Arial", "", 8)
+ fill := false
+
+ // Track highest values for observations
+ var highestCPUName string
+ var highestCPUVal float64
+ var mostAlertsName string
+ var mostAlertsCount int
+
+ for _, rd := range data.Resources {
+ if fill {
+ pdf.SetFillColor(colorTableAlt[0], colorTableAlt[1], colorTableAlt[2])
+ } else {
+ pdf.SetFillColor(255, 255, 255)
+ }
+
+ // Resource name
+ resourceName := rd.ResourceID
+ if rd.Resource != nil && rd.Resource.Name != "" {
+ resourceName = rd.Resource.Name
+ }
+ if len(resourceName) > 25 {
+ resourceName = resourceName[:22] + "..."
+ }
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ pdf.CellFormat(colWidths[0], 6, resourceName, "1", 0, "L", fill, 0, "")
+
+ // Type
+ pdf.CellFormat(colWidths[1], 6, GetResourceTypeDisplayName(rd.ResourceType), "1", 0, "C", fill, 0, "")
+
+ // Status
+ status := "N/A"
+ if rd.Resource != nil {
+ status = rd.Resource.Status
+ }
+ if status == "online" || status == "running" {
+ pdf.SetTextColor(colorAccent[0], colorAccent[1], colorAccent[2])
+ } else if status == "stopped" || status == "offline" {
+ pdf.SetTextColor(colorDanger[0], colorDanger[1], colorDanger[2])
+ } else {
+ pdf.SetTextColor(colorWarning[0], colorWarning[1], colorWarning[2])
+ }
+ pdf.CellFormat(colWidths[2], 6, status, "1", 0, "C", fill, 0, "")
+
+ // Avg CPU
+ var avgCPU float64
+ if stats, ok := rd.Summary.ByMetric["cpu"]; ok {
+ avgCPU = stats.Avg
+ }
+ pdf.SetTextColor(getStatColor(avgCPU)[0], getStatColor(avgCPU)[1], getStatColor(avgCPU)[2])
+ pdf.CellFormat(colWidths[3], 6, fmt.Sprintf("%.1f%%", avgCPU), "1", 0, "C", fill, 0, "")
+
+ if avgCPU > highestCPUVal {
+ highestCPUVal = avgCPU
+ if rd.Resource != nil && rd.Resource.Name != "" {
+ highestCPUName = rd.Resource.Name
+ } else {
+ highestCPUName = rd.ResourceID
+ }
+ }
+
+ // Avg Memory
+ var avgMem float64
+ if stats, ok := rd.Summary.ByMetric["memory"]; ok {
+ avgMem = stats.Avg
+ }
+ pdf.SetTextColor(getStatColor(avgMem)[0], getStatColor(avgMem)[1], getStatColor(avgMem)[2])
+ pdf.CellFormat(colWidths[4], 6, fmt.Sprintf("%.1f%%", avgMem), "1", 0, "C", fill, 0, "")
+
+ // Avg Disk
+ var avgDisk float64
+ if stats, ok := rd.Summary.ByMetric["disk"]; ok {
+ avgDisk = stats.Avg
+ } else if stats, ok := rd.Summary.ByMetric["usage"]; ok {
+ avgDisk = stats.Avg
+ }
+ pdf.SetTextColor(getStatColor(avgDisk)[0], getStatColor(avgDisk)[1], getStatColor(avgDisk)[2])
+ pdf.CellFormat(colWidths[5], 6, fmt.Sprintf("%.1f%%", avgDisk), "1", 0, "C", fill, 0, "")
+
+ // Alerts count
+ alertCount := 0
+ for _, alert := range rd.Alerts {
+ if alert.ResolvedTime == nil {
+ alertCount++
+ }
+ }
+ pdf.SetTextColor(getAlertCountColor(alertCount)[0], getAlertCountColor(alertCount)[1], getAlertCountColor(alertCount)[2])
+ pdf.CellFormat(colWidths[6], 6, fmt.Sprintf("%d", alertCount), "1", 0, "C", fill, 0, "")
+
+ if alertCount > mostAlertsCount {
+ mostAlertsCount = alertCount
+ if rd.Resource != nil && rd.Resource.Name != "" {
+ mostAlertsName = rd.Resource.Name
+ } else {
+ mostAlertsName = rd.ResourceID
+ }
+ }
+
+ pdf.Ln(-1)
+ fill = !fill
+ }
+
+ pdf.Ln(8)
+
+ // Fleet Observations
+ pdf.SetFont("Arial", "B", 11)
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ pdf.CellFormat(0, 8, "Fleet Observations", "", 1, "L", false, 0, "")
+ pdf.Ln(2)
+
+ pdf.SetFont("Arial", "", 10)
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+
+ if highestCPUName != "" {
+ pdf.SetFillColor(colorSecondary[0], colorSecondary[1], colorSecondary[2])
+ pdf.Circle(pdf.GetX()+3, pdf.GetY()+3, 2, "F")
+ pdf.SetX(pdf.GetX() + 8)
+ pdf.CellFormat(0, 6, fmt.Sprintf("Highest CPU: %s (avg %.1f%%)", highestCPUName, highestCPUVal), "", 1, "L", false, 0, "")
+ pdf.Ln(1)
+ }
+
+ if mostAlertsCount > 0 && mostAlertsName != "" {
+ pdf.SetFillColor(colorDanger[0], colorDanger[1], colorDanger[2])
+ pdf.Circle(pdf.GetX()+3, pdf.GetY()+3, 2, "F")
+ pdf.SetX(pdf.GetX() + 8)
+ pdf.CellFormat(0, 6, fmt.Sprintf("Most alerts: %s (%d active)", mostAlertsName, mostAlertsCount), "", 1, "L", false, 0, "")
+ pdf.Ln(1)
+ }
+
+ if totalActive == 0 {
+ pdf.SetFillColor(colorAccent[0], colorAccent[1], colorAccent[2])
+ pdf.Circle(pdf.GetX()+3, pdf.GetY()+3, 2, "F")
+ pdf.SetX(pdf.GetX() + 8)
+ pdf.CellFormat(0, 6, "No active alerts across the fleet", "", 1, "L", false, 0, "")
+ }
+}
+
+// writeCondensedResourcePage writes a condensed single-page view for one resource.
+func (g *PDFGenerator) writeCondensedResourcePage(pdf *fpdf.Fpdf, rd *ReportData) {
+ // Resource header
+ resourceName := rd.ResourceID
+ if rd.Resource != nil && rd.Resource.Name != "" {
+ resourceName = rd.Resource.Name
+ }
+
+ // Name - measure width while font is still set to bold
+ pdf.SetFont("Arial", "B", 14)
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ nameWidth := pdf.GetStringWidth(resourceName)
+ pdf.CellFormat(nameWidth+2, 8, resourceName, "", 0, "L", false, 0, "")
+
+ // Type/status/uptime inline after the name
+ typeDisplay := GetResourceTypeDisplayName(rd.ResourceType)
+ status := "unknown"
+ if rd.Resource != nil {
+ status = rd.Resource.Status
+ }
+
+ pdf.SetFont("Arial", "", 10)
+ if status == "online" || status == "running" {
+ pdf.SetTextColor(colorAccent[0], colorAccent[1], colorAccent[2])
+ } else if status == "stopped" || status == "offline" {
+ pdf.SetTextColor(colorDanger[0], colorDanger[1], colorDanger[2])
+ } else {
+ pdf.SetTextColor(colorWarning[0], colorWarning[1], colorWarning[2])
+ }
+ statusStr := fmt.Sprintf(" | %s | %s", typeDisplay, status)
+
+ // Uptime
+ if rd.Resource != nil && rd.Resource.Uptime > 0 {
+ statusStr += fmt.Sprintf(" | Uptime: %s", formatUptime(rd.Resource.Uptime))
+ }
+ pdf.CellFormat(0, 8, statusStr, "", 1, "L", false, 0, "")
+ pdf.Ln(3)
+
+ // Stats bar - CPU, Memory, Disk averages and maxes
+ pdf.SetFillColor(colorBackground[0], colorBackground[1], colorBackground[2])
+ pdf.SetDrawColor(colorGridLine[0], colorGridLine[1], colorGridLine[2])
+ barY := pdf.GetY()
+ barWidth := 170.0
+ barHeight := 22.0
+ pdf.RoundedRect(20, barY, barWidth, barHeight, 2, "1234", "FD")
+
+ colW := barWidth / 3.0
+
+ // CPU stats
+ var avgCPU, maxCPU, avgMem, maxMem, avgDisk, maxDisk float64
+ if stats, ok := rd.Summary.ByMetric["cpu"]; ok {
+ avgCPU = stats.Avg
+ maxCPU = stats.Max
+ }
+ if stats, ok := rd.Summary.ByMetric["memory"]; ok {
+ avgMem = stats.Avg
+ maxMem = stats.Max
+ }
+ if stats, ok := rd.Summary.ByMetric["disk"]; ok {
+ avgDisk = stats.Avg
+ maxDisk = stats.Max
+ } else if stats, ok := rd.Summary.ByMetric["usage"]; ok {
+ avgDisk = stats.Avg
+ maxDisk = stats.Max
+ }
+
+ // CPU column
+ pdf.SetXY(20+2, barY+3)
+ pdf.SetFont("Arial", "B", 9)
+ pdf.SetTextColor(colorSecondary[0], colorSecondary[1], colorSecondary[2])
+ pdf.CellFormat(colW-4, 5, "CPU", "", 0, "C", false, 0, "")
+
+ pdf.SetXY(20+2, barY+9)
+ pdf.SetFont("Arial", "B", 11)
+ pdf.SetTextColor(getStatColor(avgCPU)[0], getStatColor(avgCPU)[1], getStatColor(avgCPU)[2])
+ pdf.CellFormat(colW-4, 5, fmt.Sprintf("avg %.1f%% / max %.1f%%", avgCPU, maxCPU), "", 0, "C", false, 0, "")
+
+ // Memory column
+ pdf.SetXY(20+colW+2, barY+3)
+ pdf.SetFont("Arial", "B", 9)
+ pdf.SetTextColor([3]int{155, 89, 182}[0], [3]int{155, 89, 182}[1], [3]int{155, 89, 182}[2])
+ pdf.CellFormat(colW-4, 5, "Memory", "", 0, "C", false, 0, "")
+
+ pdf.SetXY(20+colW+2, barY+9)
+ pdf.SetFont("Arial", "B", 11)
+ pdf.SetTextColor(getStatColor(avgMem)[0], getStatColor(avgMem)[1], getStatColor(avgMem)[2])
+ pdf.CellFormat(colW-4, 5, fmt.Sprintf("avg %.1f%% / max %.1f%%", avgMem, maxMem), "", 0, "C", false, 0, "")
+
+ // Disk column
+ pdf.SetXY(20+2*colW+2, barY+3)
+ pdf.SetFont("Arial", "B", 9)
+ pdf.SetTextColor(colorAccent[0], colorAccent[1], colorAccent[2])
+ pdf.CellFormat(colW-4, 5, "Disk", "", 0, "C", false, 0, "")
+
+ pdf.SetXY(20+2*colW+2, barY+9)
+ pdf.SetFont("Arial", "B", 11)
+ pdf.SetTextColor(getStatColor(avgDisk)[0], getStatColor(avgDisk)[1], getStatColor(avgDisk)[2])
+ pdf.CellFormat(colW-4, 5, fmt.Sprintf("avg %.1f%% / max %.1f%%", avgDisk, maxDisk), "", 0, "C", false, 0, "")
+
+ pdf.SetY(barY + barHeight + 5)
+
+ // Small chart: CPU + Memory overlaid (if we have data)
+ cpuPoints := rd.Metrics["cpu"]
+ memPoints := rd.Metrics["memory"]
+ if len(cpuPoints) >= 2 || len(memPoints) >= 2 {
+ chartHeight := 40.0
+ chartWidth := 170.0
+ chartX := 20.0
+ chartY := pdf.GetY()
+
+ // Use CPU data primarily, or memory if no CPU
+ primaryPoints := cpuPoints
+ if len(primaryPoints) < 2 {
+ primaryPoints = memPoints
+ }
+
+ if len(primaryPoints) >= 2 {
+ // Chart title
+ pdf.SetFont("Arial", "B", 9)
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ pdf.CellFormat(0, 5, "Performance Overview", "", 1, "L", false, 0, "")
+ chartY = pdf.GetY()
+
+ g.drawChart(pdf, primaryPoints, chartX, chartY, chartWidth, chartHeight, "cpu")
+
+ // If we have both CPU and memory, overlay memory
+ if len(cpuPoints) >= 2 && len(memPoints) >= 2 {
+ g.drawChartOverlay(pdf, memPoints, cpuPoints, chartX, chartY, chartWidth, chartHeight)
+ }
+
+ // Legend (below chart X-axis labels which are at chartY + chartHeight + 1..+5)
+ pdf.SetY(chartY + chartHeight + 7)
+ pdf.SetFont("Arial", "", 7)
+ if len(cpuPoints) >= 2 {
+ pdf.SetTextColor(colorSecondary[0], colorSecondary[1], colorSecondary[2])
+ pdf.CellFormat(30, 4, "--- CPU", "", 0, "L", false, 0, "")
+ }
+ if len(memPoints) >= 2 {
+ pdf.SetTextColor(155, 89, 182)
+ pdf.CellFormat(30, 4, "--- Memory", "", 0, "L", false, 0, "")
+ }
+ pdf.Ln(6)
+ }
+ }
+
+ // Active alerts (up to 3)
+ activeAlerts := make([]AlertInfo, 0)
+ for _, alert := range rd.Alerts {
+ if alert.ResolvedTime == nil {
+ activeAlerts = append(activeAlerts, alert)
+ }
+ }
+
+ if len(activeAlerts) > 0 {
+ pdf.Ln(3)
+ pdf.SetFont("Arial", "B", 10)
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ pdf.CellFormat(0, 6, "Active Alerts", "", 1, "L", false, 0, "")
+ pdf.Ln(1)
+
+ pdf.SetFont("Arial", "", 9)
+ maxAlerts := 3
+ if len(activeAlerts) < maxAlerts {
+ maxAlerts = len(activeAlerts)
+ }
+ for i := 0; i < maxAlerts; i++ {
+ alert := activeAlerts[i]
+ if alert.Level == "critical" {
+ pdf.SetTextColor(colorDanger[0], colorDanger[1], colorDanger[2])
+ } else {
+ pdf.SetTextColor(colorWarning[0], colorWarning[1], colorWarning[2])
+ }
+ pdf.CellFormat(6, 5, "!", "", 0, "C", false, 0, "")
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ msg := alert.Message
+ if len(msg) > 80 {
+ msg = msg[:77] + "..."
+ }
+ pdf.CellFormat(0, 5, msg, "", 1, "L", false, 0, "")
+ }
+ if len(activeAlerts) > 3 {
+ pdf.SetTextColor(colorTextMuted[0], colorTextMuted[1], colorTextMuted[2])
+ pdf.CellFormat(0, 5, fmt.Sprintf("... and %d more", len(activeAlerts)-3), "", 1, "L", false, 0, "")
+ }
+ }
+
+ // Storage summary (nodes) or backup summary (VMs/containers)
+ if len(rd.Storage) > 0 {
+ pdf.Ln(3)
+ pdf.SetFont("Arial", "B", 10)
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ pdf.CellFormat(0, 6, "Storage Pools", "", 1, "L", false, 0, "")
+ pdf.Ln(1)
+
+ pdf.SetFont("Arial", "", 9)
+ for _, s := range rd.Storage {
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ line := fmt.Sprintf("%s (%s): %s / %s (%.1f%%)",
+ s.Name, s.Type,
+ formatBytes(float64(s.Used)),
+ formatBytes(float64(s.Total)),
+ s.UsagePerc)
+ pdf.CellFormat(0, 5, line, "", 1, "L", false, 0, "")
+ }
+ }
+
+ if len(rd.Backups) > 0 {
+ pdf.Ln(3)
+ pdf.SetFont("Arial", "B", 10)
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ pdf.CellFormat(0, 6, "Backups", "", 1, "L", false, 0, "")
+ pdf.Ln(1)
+
+ pdf.SetFont("Arial", "", 9)
+ pdf.SetTextColor(colorTextDark[0], colorTextDark[1], colorTextDark[2])
+ pdf.CellFormat(0, 5, fmt.Sprintf("%d backups available", len(rd.Backups)), "", 1, "L", false, 0, "")
+ if len(rd.Backups) > 0 {
+ latest := rd.Backups[0]
+ for _, b := range rd.Backups {
+ if b.Timestamp.After(latest.Timestamp) {
+ latest = b
+ }
+ }
+ pdf.CellFormat(0, 5, fmt.Sprintf("Latest: %s (%s)", latest.Timestamp.Format("2006-01-02 15:04"), formatBytes(float64(latest.Size))), "", 1, "L", false, 0, "")
+ }
+ }
+}
+
+// drawChartOverlay draws a secondary line on an existing chart using memory data over CPU scale.
+func (g *PDFGenerator) drawChartOverlay(pdf *fpdf.Fpdf, overlayPoints []MetricDataPoint, primaryPoints []MetricDataPoint, x, y, width, height float64) {
+ if len(overlayPoints) < 2 || len(primaryPoints) < 2 {
+ return
+ }
+
+ // Use the same time scale as the primary chart
+ startTime := primaryPoints[0].Timestamp.Unix()
+ endTime := primaryPoints[len(primaryPoints)-1].Timestamp.Unix()
+ timeRange := float64(endTime - startTime)
+ if timeRange == 0 {
+ timeRange = 1
+ }
+
+ // Use the primary chart's value range for consistent scaling
+ minVal, maxVal := primaryPoints[0].Value, primaryPoints[0].Value
+ for _, p := range primaryPoints {
+ if p.Value < minVal {
+ minVal = p.Value
+ }
+ if p.Value > maxVal {
+ maxVal = p.Value
+ }
+ }
+ // Also include overlay points in the range
+ for _, p := range overlayPoints {
+ if p.Value < minVal {
+ minVal = p.Value
+ }
+ if p.Value > maxVal {
+ maxVal = p.Value
+ }
+ }
+
+ valRange := maxVal - minVal
+ if valRange < 1 {
+ valRange = 10
+ }
+ minVal = math.Max(0, minVal-valRange*0.1)
+ maxVal = maxVal + valRange*0.1
+
+ // Draw the overlay line in purple (memory color)
+ memColor := [3]int{155, 89, 182}
+ pdf.SetDrawColor(memColor[0], memColor[1], memColor[2])
+ pdf.SetLineWidth(0.6)
+
+ prevX, prevY := 0.0, 0.0
+ for i, p := range overlayPoints {
+ xPos := x + 2 + (float64(p.Timestamp.Unix()-startTime)/timeRange)*(width-4)
+ yPos := y + height - 2 - ((p.Value-minVal)/(maxVal-minVal))*(height-4)
+ yPos = math.Max(y+2, math.Min(y+height-2, yPos))
+
+ if i > 0 {
+ pdf.Line(prevX, prevY, xPos, yPos)
+ }
+ prevX, prevY = xPos, yPos
+ }
+}
+
+// addMultiPageNumbers adds page numbers to all pages except the first (cover).
+func (g *PDFGenerator) addMultiPageNumbers(pdf *fpdf.Fpdf) {
+ pdf.SetAutoPageBreak(false, 0)
+
+ totalPages := pdf.PageCount()
+
+ for i := 2; i <= totalPages; i++ {
+ pdf.SetPage(i)
+ pageWidth, pageHeight := pdf.GetPageSize()
+
+ pdf.SetY(pageHeight - 15)
+ pdf.SetFont("Arial", "", 8)
+ pdf.SetTextColor(colorTextMuted[0], colorTextMuted[1], colorTextMuted[2])
+
+ pageNum := i - 1
+ totalContent := totalPages - 1
+ pdf.CellFormat(0, 5, fmt.Sprintf("Page %d of %d", pageNum, totalContent), "", 0, "C", false, 0, "")
+
+ // Bottom line
+ pdf.SetDrawColor(colorGridLine[0], colorGridLine[1], colorGridLine[2])
+ pdf.SetLineWidth(0.3)
+ pdf.Line(20, pageHeight-20, pageWidth-20, pageHeight-20)
+ }
+}
+
// getMetricColor returns a color for a metric type.
func getMetricColor(metricType string) [3]int {
switch metricType {
diff --git a/pkg/reporting/reporting.go b/pkg/reporting/reporting.go
index 378cc4abe4..5f98c2c621 100644
--- a/pkg/reporting/reporting.go
+++ b/pkg/reporting/reporting.go
@@ -106,10 +106,31 @@ type DiskInfo struct {
WearLevel int // 0-100, percentage of life REMAINING (100 = healthy, 0 = end of life, -1 = unknown)
}
+// MultiReportRequest defines the parameters for generating a multi-resource report.
+type MultiReportRequest struct {
+ Resources []MetricReportRequest // One per resource, each with enrichment
+ Format ReportFormat
+ Start time.Time
+ End time.Time
+ Title string
+ MetricType string
+}
+
+// MultiReportData holds the data for multi-resource report generation.
+type MultiReportData struct {
+ Title string
+ Start time.Time
+ End time.Time
+ GeneratedAt time.Time
+ Resources []*ReportData // Reuse existing ReportData per resource
+ TotalPoints int
+}
+
// Engine defines the interface for report generation.
// This allows the enterprise version to provide PDF/CSV generation.
type Engine interface {
Generate(req MetricReportRequest) (data []byte, contentType string, err error)
+ GenerateMulti(req MultiReportRequest) (data []byte, contentType string, err error)
}
var (
diff --git a/pkg/reporting/reporting_test.go b/pkg/reporting/reporting_test.go
index e131ac70f6..7d91812d0a 100644
--- a/pkg/reporting/reporting_test.go
+++ b/pkg/reporting/reporting_test.go
@@ -11,6 +11,11 @@ func (f *fakeEngine) Generate(req MetricReportRequest) ([]byte, string, error) {
return []byte("ok"), "text/plain", nil
}
+func (f *fakeEngine) GenerateMulti(req MultiReportRequest) ([]byte, string, error) {
+ f.called = true
+ return []byte("ok"), "text/plain", nil
+}
+
func TestSetGetEngine(t *testing.T) {
engine := &fakeEngine{}
SetEngine(engine)