Skip to content

Commit

Permalink
Add auto detection for Prometheus server service
Browse files Browse the repository at this point in the history
  • Loading branch information
jrauh01 committed Aug 21, 2024
1 parent 824fa2a commit a2ae88f
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
7 changes: 7 additions & 0 deletions cmd/icinga-kubernetes/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 != "" {
Expand Down
28 changes: 28 additions & 0 deletions pkg/metrics/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
}

0 comments on commit a2ae88f

Please sign in to comment.