clavitor/clavis/clavis-telemetry/kuma.go

75 lines
1.9 KiB
Go

//go:build commercial
package main
import (
"log"
"net/http"
"os"
"strings"
"time"
)
// kumaPush sends health status to Kuma every 60 seconds
func kumaPush() {
kumaURL := os.Getenv("KUMA_PUSH_URL")
if kumaURL == "" {
// Kuma push disabled - no hardcoded URL per KISS principle
return
}
ticker := time.NewTicker(60 * time.Second)
defer ticker.Stop()
// Send immediately on startup
sendKumaPush(kumaURL)
for range ticker.C {
sendKumaPush(kumaURL)
}
}
func sendKumaPush(kumaURL string) {
// Check health
var one int
err := db.QueryRow("SELECT 1").Scan(&one)
status := "up"
msg := "telemetry service healthy"
if err != nil {
status = "down"
msg = "database unavailable: " + err.Error()
}
// Check last telemetry received
var lastBeat int64
if err := db.QueryRow(`SELECT MAX(received_at) FROM telemetry`).Scan(&lastBeat); err != nil {
log.Printf("ERR-TELEMETRY-033: Failed to query last telemetry timestamp - %v", err)
// Continue with lastBeat=0, will show warning status
}
now := time.Now().Unix()
if now-lastBeat > 300 {
// No telemetry in 5 minutes - still up but warning
if status == "up" {
msg = "no recent telemetry from POPs"
}
}
// POST to Kuma
payload := `{"status":"` + status + `","msg":"` + strings.ReplaceAll(msg, `"`, `\"`) + `","ping":60}`
resp, err := http.Post(kumaURL, "application/json", strings.NewReader(payload))
if err != nil {
log.Printf("ERR-TELEMETRY-030: Failed to push health status to Kuma at %s - %v", kumaURL, err)
return
}
if resp.StatusCode != http.StatusOK {
log.Printf("ERR-TELEMETRY-031: Kuma returned non-OK status %d from %s", resp.StatusCode, kumaURL)
if err := resp.Body.Close(); err != nil {
log.Printf("ERR-TELEMETRY-032: Failed to close Kuma response body after non-OK status - %v", err)
}
return
}
if err := resp.Body.Close(); err != nil {
log.Printf("ERR-TELEMETRY-032: Failed to close Kuma response body - %v", err)
}
}