From afbd8b8b4584cc7bfc4ce947252883f5cd443402 Mon Sep 17 00:00:00 2001 From: Wimo Date: Wed, 21 Jul 2021 20:45:09 +0800 Subject: [PATCH] Ability to scrape dynamic targets Signed-off-by: Wimo --- cmd/postgres_exporter/main.go | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/cmd/postgres_exporter/main.go b/cmd/postgres_exporter/main.go index 25f94a745..3e32b5b3f 100644 --- a/cmd/postgres_exporter/main.go +++ b/cmd/postgres_exporter/main.go @@ -14,6 +14,7 @@ package main import ( + "context" "net/http" "os" @@ -115,6 +116,12 @@ func main() { prometheus.MustRegister(exporter) http.Handle(*metricPath, promhttp.Handler()) + + registries := make(map[string]*prometheus.Registry) + http.HandleFunc("/probe", func(w http.ResponseWriter, req *http.Request) { + probeHandler(w, req, logger, registries, opts...) + }) + http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html; charset=UTF-8") // nolint: errcheck w.Write(landingPage) // nolint: errcheck @@ -127,3 +134,29 @@ func main() { os.Exit(1) } } + +func probeHandler(w http.ResponseWriter, r *http.Request, logger log.Logger, registries map[string]*prometheus.Registry, opts ...ExporterOpt) { + + ctx, cancel := context.WithCancel(r.Context()) + defer cancel() + r = r.WithContext(ctx) + + target := r.URL.Query().Get("target") + if target == "" { + http.Error(w, "Target parameter is missing", http.StatusBadRequest) + return + } + + registry, target_registered := registries[target] + if !target_registered { + registry = prometheus.NewPedanticRegistry() + exporter := NewExporter([]string{target}, opts...) + registry.MustRegister(version.NewCollector(exporterName)) + registry.MustRegister(exporter) + registries[target] = registry + } + + h := promhttp.HandlerFor(registry, promhttp.HandlerOpts{}) + h.ServeHTTP(w, r) + +}