dependency-injected non-global metrics object

This commit is contained in:
pdbogen 2019-07-22 11:35:28 -07:00
parent b394496f5c
commit bda754ad2d
7 changed files with 162 additions and 78 deletions

View file

@ -1,38 +1,72 @@
package metrics
import "github.com/prometheus/client_golang/prometheus"
import (
"fmt"
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"k8s.io/klog"
)
const MetricsNamespace = "adapter"
var PrometheusUp = prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: MetricsNamespace,
Name: "prometheus_up",
Help: "1 when adapter is able to reach prometheus, 0 otherwise",
})
var RegistryMetrics = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: MetricsNamespace,
Name: "registry_metrics",
Help: "number of metrics entries in cache registry",
}, []string{"registry"})
var Errors = prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: MetricsNamespace,
Name: "errors_total",
Help: "number of errors served",
}, []string{"type"})
var Rules = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: MetricsNamespace,
Name: "roles",
Help: "number of configured rules",
}, []string{"type"})
func init() {
prometheus.MustRegister(
PrometheusUp,
RegistryMetrics,
Errors,
Rules,
)
type ServiceMetrics struct {
PrometheusUp prometheus.Gauge
RegistryMetrics *prometheus.GaugeVec
Errors *prometheus.CounterVec
Rules *prometheus.GaugeVec
Registry *prometheus.Registry
}
func NewMetrics() (*ServiceMetrics, error) {
ret := &ServiceMetrics{
PrometheusUp: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: MetricsNamespace,
Name: "prometheus_up",
Help: "1 when adapter is able to reach prometheus, 0 otherwise",
}),
RegistryMetrics: prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: MetricsNamespace,
Name: "registry_metrics",
Help: "number of metrics entries in cache registry",
}, []string{"registry"}),
Errors: prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: MetricsNamespace,
Name: "errors_total",
Help: "number of errors served",
}, []string{"type"}),
Rules: prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: MetricsNamespace,
Name: "roles",
Help: "number of configured rules",
}, []string{"type"}),
Registry: prometheus.NewRegistry(),
}
for collectorName, collector := range map[string]prometheus.Collector{
"Go collector": prometheus.NewGoCollector(),
"Prometheus Up": ret.PrometheusUp,
"Registry Metrics": ret.RegistryMetrics,
"Errors": ret.Errors,
"Rules": ret.Rules,
} {
if err := ret.Registry.Register(collector); err != nil {
return nil, fmt.Errorf("during registration of %q: %v", collectorName, err)
}
}
return ret, nil
}
func (m *ServiceMetrics) Run(port uint16) {
go func() {
mux := http.NewServeMux()
mux.Handle("/metrics", promhttp.Handler())
klog.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", port), mux))
}()
}