f-21: mon: add prometheus data

Signed-off-by: GnomeZworc <nicolas.boufidjeline@g3e.fr>
This commit is contained in:
GnomeZworc 2026-04-12 17:30:07 +02:00
commit 32669371d6
Signed by: nicolas.boufideline
GPG key ID: 4406BBBF8845D632
2 changed files with 87 additions and 0 deletions

View file

@ -0,0 +1,67 @@
package agentmetrics
import (
"strings"
"git.g3e.fr/syonad/two/pkg/db/kv"
"github.com/dgraph-io/badger/v4"
"github.com/prometheus/client_golang/prometheus"
)
var allStates = []string{"creating", "created", "deleting", "deleted"}
// AgentCollector implements prometheus.Collector and exposes agent metrics
// by querying the BadgerDB on each scrape.
type AgentCollector struct {
db *badger.DB
vpcsTotal *prometheus.Desc
subnetsTotal *prometheus.Desc
}
func NewAgentCollector(db *badger.DB) *AgentCollector {
return &AgentCollector{
db: db,
vpcsTotal: prometheus.NewDesc(
"syonad_vpcs_total",
"Number of VPCs by state.",
[]string{"state"}, nil,
),
subnetsTotal: prometheus.NewDesc(
"syonad_subnets_total",
"Number of subnets by state.",
[]string{"state"}, nil,
),
}
}
func (c *AgentCollector) Describe(ch chan<- *prometheus.Desc) {
ch <- c.vpcsTotal
ch <- c.subnetsTotal
}
func (c *AgentCollector) Collect(ch chan<- prometheus.Metric) {
c.collectStates(ch, "vpc/", c.vpcsTotal)
c.collectStates(ch, "subnet/", c.subnetsTotal)
}
// collectStates counts resources under the given DB prefix by their state value
// and emits one gauge per state label.
func (c *AgentCollector) collectStates(ch chan<- prometheus.Metric, prefix string, desc *prometheus.Desc) {
counts := make(map[string]float64, len(allStates))
for _, s := range allStates {
counts[s] = 0
}
items, err := kv.ListByPrefix(c.db, prefix)
if err == nil {
for key, val := range items {
if strings.HasSuffix(key, "/state") {
counts[val]++
}
}
}
for _, state := range allStates {
ch <- prometheus.MustNewConstMetric(desc, prometheus.GaugeValue, counts[state], state)
}
}

20
pkg/prometheus/server.go Normal file
View file

@ -0,0 +1,20 @@
package promserver
import (
"log"
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
// Start launches the Prometheus metrics HTTP server on the given address.
// The provided registry is used to expose metrics at /metrics.
func Start(address string, registry *prometheus.Registry) {
mux := http.NewServeMux()
mux.Handle("/metrics", promhttp.HandlerFor(registry, promhttp.HandlerOpts{
EnableOpenMetrics: true,
}))
log.Printf("Prometheus server listening on %s", address)
log.Fatal(http.ListenAndServe(address, mux))
}