diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 86a6a34..29f5f6c 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -75,6 +75,24 @@ There is also a function (enabled by setting `puppetca.deactivate_nodes` to true revoking or cleaning a node certificate. This performs the equivalent of `puppet node deactivate $CERTNAME` after the certificate is revoked or cleaned, which may be useful in environments where the CLI tools are not easily available. +### Prometheus Metrics + +OpenVox View exposes Prometheus metrics at `/metrics` (and `/api/v1/metrics`). +The exposed metrics reflect the dashboard counters: + +| Metric Name | Type | Description | +|-------------------------------------|-------|--------------------------------------------------------------------------------------| +| `openvoxview_nodes_failed` | Gauge | Number of nodes with latest report status failed | +| `openvoxview_nodes_pending` | Gauge | Number of nodes with latest report status pending | +| `openvoxview_nodes_changed` | Gauge | Number of nodes with latest report status changed | +| `openvoxview_nodes_unchanged` | Gauge | Number of nodes with latest report status unchanged | +| `openvoxview_nodes_unreported` | Gauge | Number of nodes that have not reported within the configured `unreported_hours` window| +| `openvoxview_population` | Gauge | Total number of nodes (population) | +| `openvoxview_resources_managed` | Gauge | Total number of resources managed | +| `openvoxview_avg_resources_per_node`| Gauge | Average number of resources per node | + +Standard Go runtime and process metrics are also exposed. + ## YAML Example ```yaml diff --git a/config/config.go b/config/config.go index 00e05cf..f3ec805 100644 --- a/config/config.go +++ b/config/config.go @@ -26,8 +26,10 @@ const ( var configPath = flag.String("config", "", "path to the config file") var printVersion = flag.Bool("version", false, "prints version") -func init() { - flag.Parse() +func parseFlags() { + if !flag.Parsed() { + flag.Parse() + } } type ConfigPqlQuery struct { @@ -69,6 +71,7 @@ type Config struct { } func PrintVersion(version string) bool { + parseFlags() if *printVersion { fmt.Println(version) return true @@ -83,6 +86,7 @@ var ( ) func GetConfig() (*Config, error) { + parseFlags() configOnce.Do(func() { viper.SetConfigName("config") viper.SetConfigType("yaml") diff --git a/go.mod b/go.mod index 4bfc6d2..4cfc423 100644 --- a/go.mod +++ b/go.mod @@ -1,13 +1,24 @@ module github.com/sebastianrakel/openvoxview -go 1.24 +go 1.24.0 -require github.com/gin-gonic/gin v1.11.0 +require ( + github.com/gin-gonic/gin v1.11.0 + github.com/prometheus/client_golang v1.21.1 + github.com/prometheus/common v0.62.0 +) require ( + github.com/beorn7/perks v1.0.1 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/fsnotify/fsnotify v1.9.0 // indirect github.com/go-viper/mapstructure/v2 v2.4.0 // indirect github.com/goccy/go-yaml v1.18.0 // indirect + github.com/klauspost/compress v1.17.11 // indirect + github.com/kylelemons/godebug v1.1.0 // indirect + github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect + github.com/prometheus/client_model v0.6.3 // indirect + github.com/prometheus/procfs v0.17.0 // indirect github.com/quic-go/qpack v0.6.0 // indirect github.com/quic-go/quic-go v0.57.0 // indirect github.com/sagikazarmark/locafero v0.11.0 // indirect @@ -16,7 +27,7 @@ require ( github.com/spf13/cast v1.10.0 // indirect github.com/spf13/pflag v1.0.10 // indirect github.com/subosito/gotenv v1.6.0 // indirect - go.yaml.in/yaml/v3 v3.0.4 // indirect + go.yaml.in/yaml/v3 v3.0.5 // indirect ) require ( @@ -44,5 +55,5 @@ require ( golang.org/x/net v0.43.0 // indirect golang.org/x/sys v0.35.0 // indirect golang.org/x/text v0.28.0 // indirect - google.golang.org/protobuf v1.36.9 // indirect + google.golang.org/protobuf v1.36.12 // indirect ) diff --git a/go.sum b/go.sum index 79e7540..3c0985f 100644 --- a/go.sum +++ b/go.sum @@ -1,7 +1,11 @@ +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/bytedance/sonic v1.14.0 h1:/OfKt8HFw0kh2rj8N0F6C/qPGRESq0BbaNZgcNXXzQQ= github.com/bytedance/sonic v1.14.0/go.mod h1:WoEbx8WTcFJfzCe0hbmyTGrfjt8PzNEBdxlNUO24NhA= github.com/bytedance/sonic/loader v0.3.0 h1:dskwH8edlzNMctoruo8FPTJDF3vLtDT0sXZwvZJyqeA= github.com/bytedance/sonic/loader v0.3.0/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M= github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -36,12 +40,16 @@ github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc= +github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0= github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= @@ -51,10 +59,20 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_golang v1.21.1 h1:DOvXXTqVzvkIewV/CDPFdejpMCGeMcbGCQ8YOmu+Ibk= +github.com/prometheus/client_golang v1.21.1/go.mod h1:U9NM32ykUErtVBxdvD3zfi+EuFkkaBvMb09mIfe0Zgg= +github.com/prometheus/client_model v0.6.3 h1:O0jaTVAYNxTHYInEPFJt5I3+sN8zqBtVMPTB1qyxiEo= +github.com/prometheus/client_model v0.6.3/go.mod h1:gpN5P9S7Rr6Yr92PiQ+Ixvhf6JZEkF1dnxsYL2aPBEM= +github.com/prometheus/common v0.62.0 h1:xasJaQlnWAeyHdUBeGjXmutelfJHWMRr+Fg4QszZ2Io= +github.com/prometheus/common v0.62.0/go.mod h1:vyBcEuLSvWos9B1+CyL7JZ2up+uFzXhkqml0W5zIY1I= +github.com/prometheus/procfs v0.17.0 h1:FuLQ+05u4ZI+SS/w9+BWEM2TXiHKsUQ9TADiRH7DuK0= +github.com/prometheus/procfs v0.17.0/go.mod h1:oPQLaDAMRbA+u8H5Pbfq+dl3VDAvHxMUOVhe0wYB2zw= github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8= github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII= github.com/quic-go/quic-go v0.57.0 h1:AsSSrrMs4qI/hLrKlTH/TGQeTMY0ib1pAOX7vA3AdqE= @@ -90,8 +108,8 @@ github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA github.com/ugorji/go/codec v1.3.0/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4= go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko= go.uber.org/mock v0.5.2/go.mod h1:wLlUxC2vVTPTaE3UD51E0BGOAElKrILxhVSDYQLld5o= -go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= -go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= golang.org/x/arch v0.20.0 h1:dx1zTU0MAE98U+TQ8BLl7XsJbgze2WnNKF/8tGp/Q6c= golang.org/x/arch v0.20.0/go.mod h1:bdwinDaKcfZUGpH09BB7ZmOfhalA8lQdzl62l8gGWsk= golang.org/x/crypto v0.41.0 h1:WKYxWedPGCTVVl5+WHSSrOBT0O8lx32+zxmHxijgXp4= @@ -105,11 +123,9 @@ golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng= golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU= golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE= golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg= -google.golang.org/protobuf v1.36.9 h1:w2gp2mA27hUeUzj9Ex9FBjsBm40zfaDtEWow293U7Iw= -google.golang.org/protobuf v1.36.9/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU= +google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc= +google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/handler/metrics.go b/handler/metrics.go new file mode 100644 index 0000000..4524cd1 --- /dev/null +++ b/handler/metrics.go @@ -0,0 +1,224 @@ +package handler + +import ( + "encoding/json" + "errors" + "log/slog" + "sync" + "time" + + "github.com/gin-gonic/gin" + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/collectors" + "github.com/prometheus/client_golang/prometheus/promhttp" + "github.com/sebastianrakel/openvoxview/config" + "github.com/sebastianrakel/openvoxview/model" + "github.com/sebastianrakel/openvoxview/puppetdb" +) + +type OpenVoxViewCollector struct { + config *config.Config + pdbClient puppetdb.Client + + nodesFailedDesc *prometheus.Desc + nodesPendingDesc *prometheus.Desc + nodesChangedDesc *prometheus.Desc + nodesUnchangedDesc *prometheus.Desc + nodesUnreportedDesc *prometheus.Desc + populationDesc *prometheus.Desc + resourcesManagedDesc *prometheus.Desc + avgResourcesPerNodeDesc *prometheus.Desc +} + +func NewOpenVoxViewCollector(cfg *config.Config, pdbClient puppetdb.Client) *OpenVoxViewCollector { + return &OpenVoxViewCollector{ + config: cfg, + pdbClient: pdbClient, + nodesFailedDesc: prometheus.NewDesc( + "openvoxview_nodes_failed", + "Number of nodes with latest report status failed.", + nil, + nil, + ), + nodesPendingDesc: prometheus.NewDesc( + "openvoxview_nodes_pending", + "Number of nodes with latest report status pending.", + nil, + nil, + ), + nodesChangedDesc: prometheus.NewDesc( + "openvoxview_nodes_changed", + "Number of nodes with latest report status changed.", + nil, + nil, + ), + nodesUnchangedDesc: prometheus.NewDesc( + "openvoxview_nodes_unchanged", + "Number of nodes with latest report status unchanged.", + nil, + nil, + ), + nodesUnreportedDesc: prometheus.NewDesc( + "openvoxview_nodes_unreported", + "Number of nodes that have not reported within the configured unreported duration.", + nil, + nil, + ), + populationDesc: prometheus.NewDesc( + "openvoxview_population", + "Total number of nodes (population).", + nil, + nil, + ), + resourcesManagedDesc: prometheus.NewDesc( + "openvoxview_resources_managed", + "Total number of resources managed.", + nil, + nil, + ), + avgResourcesPerNodeDesc: prometheus.NewDesc( + "openvoxview_avg_resources_per_node", + "Average number of resources per node.", + nil, + nil, + ), + } +} + +func (c *OpenVoxViewCollector) Describe(ch chan<- *prometheus.Desc) { + ch <- c.nodesFailedDesc + ch <- c.nodesPendingDesc + ch <- c.nodesChangedDesc + ch <- c.nodesUnchangedDesc + ch <- c.nodesUnreportedDesc + ch <- c.populationDesc + ch <- c.resourcesManagedDesc + ch <- c.avgResourcesPerNodeDesc +} + +type countResult struct { + Count float64 `json:"count"` +} + +func queryPqlCount(client puppetdb.Client, pql string) (float64, error) { + res, _, err := client.Query(pql) + if err != nil { + return 0, err + } + if len(res) == 0 { + return 0, errors.New("empty response from puppetdb") + } + var cr countResult + if err := json.Unmarshal(res[0], &cr); err != nil { + return 0, err + } + return cr.Count, nil +} + +func (c *OpenVoxViewCollector) Collect(ch chan<- prometheus.Metric) { + var ( + nodes []model.Node + nodesErr error + popCount float64 + popErr error + resCount float64 + resErr error + wg sync.WaitGroup + ) + + wg.Add(3) + go func() { + defer wg.Done() + nodes, nodesErr = c.pdbClient.GetNodes(&puppetdb.PdbQuery{}) + }() + + go func() { + defer wg.Done() + popCount, popErr = queryPqlCount(c.pdbClient, "nodes [count()] { }") + }() + + go func() { + defer wg.Done() + resCount, resErr = queryPqlCount(c.pdbClient, "resources [count()] { }") + }() + + wg.Wait() + + if nodesErr != nil { + slog.Error("failed to get nodes from puppetdb for prometheus metrics", "error", nodesErr) + return + } + + var failed, pending, changed, unchanged, unreported float64 + unreportedHours := uint64(3) + if c.config != nil && c.config.UnreportedHours > 0 { + unreportedHours = c.config.UnreportedHours + } + unreportedThreshold := time.Now().Add(-time.Duration(unreportedHours) * time.Hour) + + for _, node := range nodes { + switch node.LatestReportStatus { + case "failed": + failed++ + case "pending": + pending++ + case "changed": + changed++ + case "unchanged": + unchanged++ + } + + if node.ReportTimestamp == nil || node.ReportTimestamp.IsZero() || node.ReportTimestamp.Before(unreportedThreshold) { + unreported++ + } + } + + population := popCount + if popErr != nil { + slog.Warn("failed to query population count from puppetdb, falling back to node list length", "error", popErr) + population = float64(len(nodes)) + } + + resources := resCount + if resErr != nil { + slog.Error("failed to query resources count from puppetdb for prometheus metrics", "error", resErr) + resources = 0 + } + + var avgResourcesPerNode float64 + if population > 0 { + avgResourcesPerNode = resources / population + } + + ch <- prometheus.MustNewConstMetric(c.nodesFailedDesc, prometheus.GaugeValue, failed) + ch <- prometheus.MustNewConstMetric(c.nodesPendingDesc, prometheus.GaugeValue, pending) + ch <- prometheus.MustNewConstMetric(c.nodesChangedDesc, prometheus.GaugeValue, changed) + ch <- prometheus.MustNewConstMetric(c.nodesUnchangedDesc, prometheus.GaugeValue, unchanged) + ch <- prometheus.MustNewConstMetric(c.nodesUnreportedDesc, prometheus.GaugeValue, unreported) + ch <- prometheus.MustNewConstMetric(c.populationDesc, prometheus.GaugeValue, population) + ch <- prometheus.MustNewConstMetric(c.resourcesManagedDesc, prometheus.GaugeValue, resources) + ch <- prometheus.MustNewConstMetric(c.avgResourcesPerNodeDesc, prometheus.GaugeValue, avgResourcesPerNode) +} + +type MetricsHandler struct { + collector *OpenVoxViewCollector + registry *prometheus.Registry +} + +func NewMetricsHandler(cfg *config.Config, pdbClient puppetdb.Client) *MetricsHandler { + collector := NewOpenVoxViewCollector(cfg, pdbClient) + reg := prometheus.NewRegistry() + reg.MustRegister(collector) + reg.MustRegister(collectors.NewGoCollector()) + reg.MustRegister(collectors.NewProcessCollector(collectors.ProcessCollectorOpts{})) + + return &MetricsHandler{ + collector: collector, + registry: reg, + } +} + +func (h *MetricsHandler) Handler() gin.HandlerFunc { + promHandler := promhttp.HandlerFor(h.registry, promhttp.HandlerOpts{}) + return gin.WrapH(promHandler) +} diff --git a/handler/metrics_test.go b/handler/metrics_test.go new file mode 100644 index 0000000..d6d2463 --- /dev/null +++ b/handler/metrics_test.go @@ -0,0 +1,341 @@ +package handler + +import ( + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/testutil" + "github.com/sebastianrakel/openvoxview/config" + "github.com/sebastianrakel/openvoxview/model" + "github.com/sebastianrakel/openvoxview/puppetdb" +) + +type mockPuppetDbClient struct { + nodes []model.Node + nodesErr error + queryFunc func(query string) ([]json.RawMessage, int, error) +} + +func (m *mockPuppetDbClient) Query(query string) ([]json.RawMessage, int, error) { + if m.queryFunc != nil { + return m.queryFunc(query) + } + return nil, http.StatusOK, nil +} + +func (m *mockPuppetDbClient) GetNodes(query *puppetdb.PdbQuery) ([]model.Node, error) { + return m.nodes, m.nodesErr +} + +func (m *mockPuppetDbClient) GetFacts(query *puppetdb.PdbQuery) ([]model.Fact, error) { + return nil, nil +} + +func (m *mockPuppetDbClient) GetFactNames() (json.RawMessage, error) { + return nil, nil +} + +func (m *mockPuppetDbClient) GetEventCounts(query *puppetdb.PdbQuery) ([]model.EventCount, error) { + return nil, nil +} + +func (m *mockPuppetDbClient) GetMetric(metricName string) (model.Metric, error) { + return model.Metric{}, nil +} + +func (m *mockPuppetDbClient) GetMetricList() (model.MetricList, error) { + return model.MetricList{}, nil +} + +func (m *mockPuppetDbClient) DeactivateNode(certname string) (*model.CommandResponse, error) { + return nil, nil +} + +func TestCollectorCollect(t *testing.T) { + now := time.Now() + recentTime := model.PuppetTime{Time: now.Add(-30 * time.Minute)} + oldTime := model.PuppetTime{Time: now.Add(-5 * time.Hour)} + + nodes := []model.Node{ + { + Name: "node1.example.com", + LatestReportStatus: "failed", + ReportTimestamp: &recentTime, + }, + { + Name: "node2.example.com", + LatestReportStatus: "failed", + ReportTimestamp: &oldTime, // unreported + }, + { + Name: "node3.example.com", + LatestReportStatus: "pending", + ReportTimestamp: &recentTime, + }, + { + Name: "node4.example.com", + LatestReportStatus: "changed", + ReportTimestamp: &recentTime, + }, + { + Name: "node5.example.com", + LatestReportStatus: "changed", + ReportTimestamp: &recentTime, + }, + { + Name: "node6.example.com", + LatestReportStatus: "changed", + ReportTimestamp: nil, // unreported + }, + { + Name: "node7.example.com", + LatestReportStatus: "unchanged", + ReportTimestamp: &recentTime, + }, + { + Name: "node8.example.com", + LatestReportStatus: "unchanged", + ReportTimestamp: &recentTime, + }, + { + Name: "node9.example.com", + LatestReportStatus: "unchanged", + ReportTimestamp: &recentTime, + }, + { + Name: "node10.example.com", + LatestReportStatus: "unchanged", + ReportTimestamp: &oldTime, // unreported + }, + } + + mockPdb := &mockPuppetDbClient{ + nodes: nodes, + queryFunc: func(query string) ([]json.RawMessage, int, error) { + if strings.Contains(query, "nodes") { + raw := json.RawMessage(`{"count": 10}`) + return []json.RawMessage{raw}, http.StatusOK, nil + } + if strings.Contains(query, "resources") { + raw := json.RawMessage(`{"count": 500}`) + return []json.RawMessage{raw}, http.StatusOK, nil + } + return nil, http.StatusOK, nil + }, + } + + cfg := &config.Config{ + UnreportedHours: 3, + } + + collector := NewOpenVoxViewCollector(cfg, mockPdb) + reg := prometheus.NewRegistry() + if err := reg.Register(collector); err != nil { + t.Fatalf("failed to register collector: %v", err) + } + + expectedMetrics := ` +# HELP openvoxview_avg_resources_per_node Average number of resources per node. +# TYPE openvoxview_avg_resources_per_node gauge +openvoxview_avg_resources_per_node 50 +# HELP openvoxview_nodes_changed Number of nodes with latest report status changed. +# TYPE openvoxview_nodes_changed gauge +openvoxview_nodes_changed 3 +# HELP openvoxview_nodes_failed Number of nodes with latest report status failed. +# TYPE openvoxview_nodes_failed gauge +openvoxview_nodes_failed 2 +# HELP openvoxview_nodes_pending Number of nodes with latest report status pending. +# TYPE openvoxview_nodes_pending gauge +openvoxview_nodes_pending 1 +# HELP openvoxview_nodes_unchanged Number of nodes with latest report status unchanged. +# TYPE openvoxview_nodes_unchanged gauge +openvoxview_nodes_unchanged 4 +# HELP openvoxview_nodes_unreported Number of nodes that have not reported within the configured unreported duration. +# TYPE openvoxview_nodes_unreported gauge +openvoxview_nodes_unreported 3 +# HELP openvoxview_population Total number of nodes (population). +# TYPE openvoxview_population gauge +openvoxview_population 10 +# HELP openvoxview_resources_managed Total number of resources managed. +# TYPE openvoxview_resources_managed gauge +openvoxview_resources_managed 500 +` + + metricNames := []string{ + "openvoxview_nodes_failed", + "openvoxview_nodes_pending", + "openvoxview_nodes_changed", + "openvoxview_nodes_unchanged", + "openvoxview_nodes_unreported", + "openvoxview_population", + "openvoxview_resources_managed", + "openvoxview_avg_resources_per_node", + } + + if err := testutil.GatherAndCompare(reg, strings.NewReader(expectedMetrics), metricNames...); err != nil { + t.Errorf("gathered metrics did not match expected: %v", err) + } +} + +func TestCollectorWithPdbErrors(t *testing.T) { + mockPdb := &mockPuppetDbClient{ + nodesErr: errors.New("connection refused"), + } + + cfg := &config.Config{ + UnreportedHours: 3, + } + + collector := NewOpenVoxViewCollector(cfg, mockPdb) + reg := prometheus.NewRegistry() + if err := reg.Register(collector); err != nil { + t.Fatalf("failed to register collector: %v", err) + } + + // When nodes query errors, no metrics should be collected + mfs, err := reg.Gather() + if err != nil { + t.Fatalf("unexpected error during gather: %v", err) + } + + for _, mf := range mfs { + if strings.HasPrefix(mf.GetName(), "openvoxview_") { + t.Errorf("expected no openvoxview metrics on error, got %s", mf.GetName()) + } + } +} + +func TestCollectorPopulationFallback(t *testing.T) { + nodes := []model.Node{ + {Name: "n1", LatestReportStatus: "unchanged"}, + {Name: "n2", LatestReportStatus: "failed"}, + } + + mockPdb := &mockPuppetDbClient{ + nodes: nodes, + queryFunc: func(query string) ([]json.RawMessage, int, error) { + // Fail both population and resources queries + return nil, http.StatusInternalServerError, errors.New("pql failure") + }, + } + + cfg := &config.Config{ + UnreportedHours: 3, + } + + collector := NewOpenVoxViewCollector(cfg, mockPdb) + reg := prometheus.NewRegistry() + if err := reg.Register(collector); err != nil { + t.Fatalf("failed to register collector: %v", err) + } + + expectedMetrics := ` +# HELP openvoxview_avg_resources_per_node Average number of resources per node. +# TYPE openvoxview_avg_resources_per_node gauge +openvoxview_avg_resources_per_node 0 +# HELP openvoxview_nodes_changed Number of nodes with latest report status changed. +# TYPE openvoxview_nodes_changed gauge +openvoxview_nodes_changed 0 +# HELP openvoxview_nodes_failed Number of nodes with latest report status failed. +# TYPE openvoxview_nodes_failed gauge +openvoxview_nodes_failed 1 +# HELP openvoxview_nodes_pending Number of nodes with latest report status pending. +# TYPE openvoxview_nodes_pending gauge +openvoxview_nodes_pending 0 +# HELP openvoxview_nodes_unchanged Number of nodes with latest report status unchanged. +# TYPE openvoxview_nodes_unchanged gauge +openvoxview_nodes_unchanged 1 +# HELP openvoxview_nodes_unreported Number of nodes that have not reported within the configured unreported duration. +# TYPE openvoxview_nodes_unreported gauge +openvoxview_nodes_unreported 2 +# HELP openvoxview_population Total number of nodes (population). +# TYPE openvoxview_population gauge +openvoxview_population 2 +# HELP openvoxview_resources_managed Total number of resources managed. +# TYPE openvoxview_resources_managed gauge +openvoxview_resources_managed 0 +` + + metricNames := []string{ + "openvoxview_nodes_failed", + "openvoxview_nodes_pending", + "openvoxview_nodes_changed", + "openvoxview_nodes_unchanged", + "openvoxview_nodes_unreported", + "openvoxview_population", + "openvoxview_resources_managed", + "openvoxview_avg_resources_per_node", + } + + if err := testutil.GatherAndCompare(reg, strings.NewReader(expectedMetrics), metricNames...); err != nil { + t.Errorf("gathered metrics did not match expected: %v", err) + } +} + +func TestMetricsEndpoint(t *testing.T) { + gin.SetMode(gin.TestMode) + + mockPdb := &mockPuppetDbClient{ + nodes: []model.Node{ + {Name: "n1", LatestReportStatus: "failed"}, + }, + queryFunc: func(query string) ([]json.RawMessage, int, error) { + if strings.Contains(query, "nodes") { + return []json.RawMessage{json.RawMessage(`{"count": 1}`)}, http.StatusOK, nil + } + if strings.Contains(query, "resources") { + return []json.RawMessage{json.RawMessage(`{"count": 10}`)}, http.StatusOK, nil + } + return nil, http.StatusOK, nil + }, + } + + cfg := &config.Config{ + UnreportedHours: 3, + } + + handler := NewMetricsHandler(cfg, mockPdb) + + router := gin.New() + router.GET("/metrics", handler.Handler()) + + req := httptest.NewRequest(http.MethodGet, "/metrics", nil) + rec := httptest.NewRecorder() + + router.ServeHTTP(rec, req) + + if rec.Code != http.StatusOK { + t.Fatalf("expected status 200, got %d", rec.Code) + } + + body, err := io.ReadAll(rec.Body) + if err != nil { + t.Fatalf("failed to read response body: %v", err) + } + + bodyStr := string(body) + expectedSubstrings := []string{ + "openvoxview_nodes_failed 1", + "openvoxview_nodes_pending 0", + "openvoxview_nodes_changed 0", + "openvoxview_nodes_unchanged 0", + "openvoxview_nodes_unreported 1", + "openvoxview_population 1", + "openvoxview_resources_managed 10", + "openvoxview_avg_resources_per_node 10", + } + + for _, sub := range expectedSubstrings { + if !strings.Contains(bodyStr, sub) { + t.Errorf("expected body to contain %q, but it didn't.\nBody:\n%s", sub, bodyStr) + } + } +} diff --git a/main.go b/main.go index 5b9bcf2..0f63174 100644 --- a/main.go +++ b/main.go @@ -11,6 +11,7 @@ import ( "github.com/gin-gonic/gin" "github.com/sebastianrakel/openvoxview/config" "github.com/sebastianrakel/openvoxview/handler" + "github.com/sebastianrakel/openvoxview/puppetdb" ) var ( @@ -58,11 +59,16 @@ func main() { caEnabled := cfg.PuppetCA.Host != "" + pdbClient := puppetdb.NewClient() pdbHandler := handler.NewPdbHandler(cfg) viewHandler := handler.NewViewHandler(cfg) + metricsHandler := handler.NewMetricsHandler(cfg, pdbClient) + + r.GET("/metrics", metricsHandler.Handler()) api := r.Group("/api/v1/") { + api.GET("metrics", metricsHandler.Handler()) api.GET("meta", func(c *gin.Context) { type metaResponse struct { CaEnabled bool diff --git a/puppetdb/client.go b/puppetdb/client.go index 85b51dc..33cf3de 100644 --- a/puppetdb/client.go +++ b/puppetdb/client.go @@ -18,6 +18,17 @@ import ( "github.com/sebastianrakel/openvoxview/model" ) +type Client interface { + Query(query string) ([]json.RawMessage, int, error) + GetFacts(query *PdbQuery) ([]model.Fact, error) + GetFactNames() (json.RawMessage, error) + GetEventCounts(query *PdbQuery) ([]model.EventCount, error) + GetNodes(query *PdbQuery) ([]model.Node, error) + GetMetric(metricName string) (model.Metric, error) + GetMetricList() (model.MetricList, error) + DeactivateNode(certname string) (*model.CommandResponse, error) +} + type client struct { } @@ -28,7 +39,7 @@ type PdbQuery struct { type PdbBadQueryError error -func NewClient() *client { +func NewClient() Client { return &client{} }