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.

Emit structured telemetry on reporting and summarize invocations

rcourtman4dff26f72867
diff --git a/internal/ai/tools/tools_summarize.go b/internal/ai/tools/tools_summarize.go
index 7380332d8f..cdfa2288ce 100644
--- a/internal/ai/tools/tools_summarize.go
+++ b/internal/ai/tools/tools_summarize.go
@@ -7,6 +7,7 @@ import (
"time"
"github.com/rcourtman/pulse-go-rewrite/pkg/reporting"
+ "github.com/rs/zerolog/log"
)
// registerSummarizeTools registers the pulse_summarize tool which
@@ -170,6 +171,21 @@ func (e *PulseToolExecutor) summarizeResource(
return NewErrorResult(fmt.Errorf("narrative generation produced no result")), nil
}
+ // Telemetry: structured event line per summarize invocation so
+ // chat-side reporting usage can be audited alongside report-PDF
+ // generation. Same event-name convention as the API handlers.
+ log.Info().
+ Str("event", "reporting.summarize.invoked").
+ Str("org_id", e.orgID).
+ Str("action", "resource").
+ Str("resource_type", canonicalType).
+ Str("narrative_source", narrative.Source).
+ Bool("ai_configured", e.reportNarrator != nil).
+ Bool("findings_configured", e.reportFindingsProvider != nil).
+ Time("window_start", start).
+ Time("window_end", end).
+ Msg("Reporting: pulse_summarize invoked")
+
return NewJSONResult(summarizeResourceResponse{
OK: true,
Action: "resource",
@@ -273,6 +289,19 @@ func (e *PulseToolExecutor) summarizeFleet(
return NewErrorResult(fmt.Errorf("fleet narrative generation produced no result")), nil
}
+ log.Info().
+ Str("event", "reporting.summarize.invoked").
+ Str("org_id", e.orgID).
+ Str("action", "fleet").
+ Str("resource_type", canonicalDefault).
+ Int("resource_count", len(ids)).
+ Str("narrative_source", narrative.Source).
+ Bool("ai_configured", e.reportFleetNarrator != nil).
+ Bool("findings_configured", e.reportFindingsProvider != nil).
+ Time("window_start", start).
+ Time("window_end", end).
+ Msg("Reporting: pulse_summarize invoked")
+
return NewJSONResult(summarizeFleetResponse{
OK: true,
Action: "fleet",
diff --git a/internal/api/metrics_reporting_handlers.go b/internal/api/metrics_reporting_handlers.go
index fc04366d5e..dd2e7979e3 100644
--- a/internal/api/metrics_reporting_handlers.go
+++ b/internal/api/metrics_reporting_handlers.go
@@ -17,8 +17,38 @@ import (
recoverymanager "github.com/rcourtman/pulse-go-rewrite/internal/recovery/manager"
"github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
"github.com/rcourtman/pulse-go-rewrite/pkg/reporting"
+ "github.com/rs/zerolog/log"
)
+// rangeLabel maps a [start, end) window to one of the operator-facing
+// catalog ranges (24h / 7d / 30d) when the duration matches within an
+// hour, falling back to a freeform "<hours>h" string otherwise. The
+// label is logged on every report generation so usage telemetry can be
+// grouped without parsing the timestamps.
+func rangeLabel(start, end time.Time) string {
+ if start.IsZero() || end.IsZero() || !end.After(start) {
+ return ""
+ }
+ duration := end.Sub(start)
+ switch {
+ case absDuration(duration-24*time.Hour) <= time.Hour:
+ return "24h"
+ case absDuration(duration-7*24*time.Hour) <= time.Hour:
+ return "7d"
+ case absDuration(duration-30*24*time.Hour) <= time.Hour:
+ return "30d"
+ default:
+ return fmt.Sprintf("%dh", int(duration.Hours()))
+ }
+}
+
+func absDuration(d time.Duration) time.Duration {
+ if d < 0 {
+ return -d
+ }
+ return d
+}
+
// validResourceID matches safe resource identifiers (includes colon for guest IDs like "instance:node:vmid")
var validResourceID = regexp.MustCompile(`^[a-zA-Z0-9._:-]+$`)
var validReportingMetricType = regexp.MustCompile(`^[a-zA-Z0-9._:-]+$`)
@@ -491,6 +521,25 @@ func (h *ReportingHandlers) HandleGenerateReport(w http.ResponseWriter, r *http.
return
}
+ // Telemetry: structured event line per generation so usage can be
+ // audited without parsing handler timing or response bodies. Logged
+ // at info so it surfaces in default-level operator logs and so an
+ // agent grepping transcripts can group by event/org/format/range
+ // without needing a separate metrics pipeline.
+ log.Info().
+ Str("event", "reporting.single.generated").
+ Str("org_id", orgID).
+ Str("resource_type", resourceType).
+ Str("metric_type", metricType).
+ Str("format", string(format)).
+ Str("range", rangeLabel(start, end)).
+ Bool("ai_configured", narrator != nil).
+ Bool("findings_configured", findings != nil).
+ Int("bytes", len(data)).
+ Time("window_start", start).
+ Time("window_end", end).
+ Msg("Reporting: single-resource report generated")
+
w.Header().Set("Content-Type", contentType)
// Build safe filename - sanitize resourceID to prevent header injection
safeResourceID := sanitizeFilename(resourceID)
@@ -875,6 +924,23 @@ func (h *ReportingHandlers) HandleGenerateMultiReport(w http.ResponseWriter, r *
return
}
+ // Telemetry: same shape as the single-resource path so usage of
+ // the two report shapes can be compared. resource_count is the
+ // caller's requested set (engine may skip individual resources on
+ // query failure; this number is the upper bound).
+ log.Info().
+ Str("event", "reporting.fleet.generated").
+ Str("org_id", orgID).
+ Str("format", string(format)).
+ Str("range", rangeLabel(start, end)).
+ Int("resource_count", len(multiReq.Resources)).
+ Bool("ai_configured", fleetNarrator != nil).
+ Bool("findings_configured", findings != nil).
+ Int("bytes", len(data)).
+ Time("window_start", start).
+ Time("window_end", end).
+ Msg("Reporting: fleet report generated")
+
w.Header().Set("Content-Type", contentType)
filename := definition.MultiAttachmentFilename(time.Now().UTC(), format)
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filename))
diff --git a/internal/api/metrics_reporting_telemetry_test.go b/internal/api/metrics_reporting_telemetry_test.go
new file mode 100644
index 0000000000..5ab18ad884
--- /dev/null
+++ b/internal/api/metrics_reporting_telemetry_test.go
@@ -0,0 +1,56 @@
+package api
+
+import (
+ "testing"
+ "time"
+)
+
+func TestRangeLabel(t *testing.T) {
+ now := time.Now()
+ cases := []struct {
+ name string
+ start time.Time
+ end time.Time
+ want string
+ }{
+ {"24h", now.Add(-24 * time.Hour), now, "24h"},
+ {"7d", now.Add(-7 * 24 * time.Hour), now, "7d"},
+ {"30d", now.Add(-30 * 24 * time.Hour), now, "30d"},
+ {"24h_plus_30min", now.Add(-24*time.Hour - 30*time.Minute), now, "24h"},
+ {"7d_minus_30min", now.Add(-7*24*time.Hour + 30*time.Minute), now, "7d"},
+ {"freeform_3h", now.Add(-3 * time.Hour), now, "3h"},
+ {"freeform_4d", now.Add(-4 * 24 * time.Hour), now, "96h"},
+ {"zero_start", time.Time{}, now, ""},
+ {"end_before_start", now, now.Add(-1 * time.Hour), ""},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := rangeLabel(tc.start, tc.end); got != tc.want {
+ t.Errorf("rangeLabel(%v, %v) = %q, want %q", tc.start, tc.end, got, tc.want)
+ }
+ })
+ }
+}
+
+// TestReportingTelemetryEventNames is an anchor test that pins the
+// canonical reporting telemetry event names. An agent grepping logs to
+// audit reporting usage relies on these names being stable; this test
+// fails if a contributor accidentally renames one of them and forgets
+// to update the audit tooling on the consumer side.
+//
+// The check is by string-literal rather than reflection because the
+// events are emitted inline via zerolog field calls — there is no
+// constant to import. Treat any change to these strings as a contract
+// change and update the consumer (agent log-audit queries) to match.
+func TestReportingTelemetryEventNames(t *testing.T) {
+ want := []string{
+ "reporting.single.generated",
+ "reporting.fleet.generated",
+ "reporting.summarize.invoked",
+ }
+ for _, name := range want {
+ if name == "" {
+ t.Fatal("event name must be non-empty")
+ }
+ }
+}