From 7c0fc425d1e7e94d09d505c4da572c9c36c781a7 Mon Sep 17 00:00:00 2001 From: Anurag Mittal Date: Thu, 19 Dec 2024 02:57:28 +0100 Subject: [PATCH] Updated metrics.go to add listener add unit tests Issue: COSI-65 --- pkg/metrics/metrics.go | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/pkg/metrics/metrics.go b/pkg/metrics/metrics.go index 8b57aa4d..7ca5df8e 100644 --- a/pkg/metrics/metrics.go +++ b/pkg/metrics/metrics.go @@ -1,6 +1,7 @@ package metrics import ( + "net" "net/http" c "github.com/scality/cosi-driver/pkg/constants" @@ -25,17 +26,24 @@ func init() { } func StartMetricsServer(addr string) (*http.Server, error) { + listener, err := net.Listen("tcp", addr) + if err != nil { + return nil, err + } + return StartMetricsServerWithListener(listener) +} + +func StartMetricsServerWithListener(listener net.Listener) (*http.Server, error) { mux := http.NewServeMux() mux.Handle(c.MetricsPath, promhttp.Handler()) srv := &http.Server{ - Addr: addr, Handler: mux, } go func() { - klog.InfoS("Starting Prometheus metrics server", "address", addr) - if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { + klog.InfoS("Starting Prometheus metrics server", "address", listener.Addr().String()) + if err := srv.Serve(listener); err != nil && err != http.ErrServerClosed { klog.ErrorS(err, "Failed to start metrics server") } }()