Skip to content

Commit

Permalink
Add helpers to stop and start metrics/profile servers
Browse files Browse the repository at this point in the history
These are used throughout the Submariner project.

Signed-off-by: Stephen Kitt <[email protected]>
  • Loading branch information
skitt committed Jan 31, 2024
1 parent d895217 commit fc4f7f7
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions pkg/util/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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")
}
}

0 comments on commit fc4f7f7

Please sign in to comment.