From fc4f7f70239b5cab2551a99c036942c4b837b1ad Mon Sep 17 00:00:00 2001 From: Stephen Kitt Date: Wed, 31 Jan 2024 14:45:04 +0100 Subject: [PATCH] Add helpers to stop and start metrics/profile servers These are used throughout the Submariner project. Signed-off-by: Stephen Kitt --- pkg/util/helpers.go | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/pkg/util/helpers.go b/pkg/util/helpers.go index 53762e04..9c1140d5 100644 --- a/pkg/util/helpers.go +++ b/pkg/util/helpers.go @@ -19,11 +19,16 @@ limitations under the License. package util import ( + "context" "crypto/x509" "fmt" + "net/http" + "net/http/pprof" "sync/atomic" + "time" "github.com/pkg/errors" + "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/submariner-io/admiral/pkg/resource" "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" @@ -171,3 +176,40 @@ func AddCertificateErrorHandler(fatal bool) { // The generic handler has already logged the error, no need to repeat if we don't want extra detail }) } + +// StartMetricsAndProfileServer starts an HTTP server providing access to Prometheus metrics +// and/or profiling information. +// The returned server should be shut down on process exit, using StopMetricsAndProfileServer(). +func StartMetricsAndProfileServer(metrics, profile bool, port int) *http.Server { + if !metrics && !profile { + return nil + } + + srv := &http.Server{Addr: fmt.Sprintf(":%d", port), ReadHeaderTimeout: 60 * time.Second} + + if metrics { + http.Handle("/metrics", promhttp.Handler()) + } + if profile { + http.HandleFunc("/debug", pprof.Profile) + } + + go func() { + if err := srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) { + logger.Errorf(err, "Error starting metrics/profile HTTP server") + } + }() + + return srv +} + +// StopMetricsAndProfileServer stops the given HTTP server, if any. +func StopMetricsAndProfileServer(srv *http.Server) { + if srv == nil { + return + } + + if err := srv.Shutdown(context.TODO()); err != nil { + logger.Errorf(err, "Error shutting down metrics/profile HTTP server") + } +}