From 768e5c960125a737b15fcdbccd6c8ebf08600b5a Mon Sep 17 00:00:00 2001 From: Johannes Rauh Date: Wed, 21 Aug 2024 10:42:18 +0200 Subject: [PATCH] Add auto detection for Prometheus server service --- cmd/icinga-kubernetes/main.go | 7 +++++++ pkg/metrics/config.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/cmd/icinga-kubernetes/main.go b/cmd/icinga-kubernetes/main.go index 2d8c01e..081e9f4 100644 --- a/cmd/icinga-kubernetes/main.go +++ b/cmd/icinga-kubernetes/main.go @@ -126,6 +126,13 @@ func main() { klog.Error(errors.Wrap(err, "cannot retrieve prometheus config")) } + + if cfg.Prometheus.Url == "" { + err = metrics.AutoDetectPrometheus(ctx, clientset, &cfg.Prometheus) + if err != nil { + klog.Error(errors.Wrap(err, "cannot auto-detect prometheus")) + } + } } if cfg.Prometheus.Url != "" { diff --git a/pkg/metrics/config.go b/pkg/metrics/config.go index 6922d75..05119cb 100644 --- a/pkg/metrics/config.go +++ b/pkg/metrics/config.go @@ -2,9 +2,12 @@ package metrics import ( "context" + "fmt" "github.com/icinga/icinga-go-library/database" schemav1 "github.com/icinga/icinga-kubernetes/pkg/schema/v1" "github.com/pkg/errors" + kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/kubernetes" ) // PrometheusConfig defines Prometheus configuration. @@ -52,3 +55,28 @@ func RetrievePrometheusConfig(ctx context.Context, db *database.DB, config *Prom return nil } + +func AutoDetectPrometheus(ctx context.Context, clientset *kubernetes.Clientset, config *PrometheusConfig) error { + services, err := clientset.CoreV1().Services("monitoring").List(ctx, kmetav1.ListOptions{ + LabelSelector: "app.kubernetes.io/component=server", + }) + if err != nil { + return errors.Wrap(err, "cannot list Prometheus services") + } + + if len(services.Items) == 0 { + return errors.New("no Prometheus service found") + } + + if len(services.Items) > 1 { + return errors.New("multiple Prometheus services found") + } + + config.Url = fmt.Sprintf( + "http://%s:%d", + services.Items[0].Spec.ClusterIP, + services.Items[0].Spec.Ports[0].Port, + ) + + return nil +}