2021-06-28 13:20:23 +00:00
|
|
|
package metrics
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
|
2023-08-16 01:40:00 +00:00
|
|
|
"github.com/prometheus/client_golang/prometheus/promhttp"
|
2021-06-28 13:20:23 +00:00
|
|
|
"go.opencensus.io/plugin/ochttp"
|
2022-01-18 18:17:06 +00:00
|
|
|
"go.uber.org/zap"
|
2021-06-28 13:20:23 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// Server runs and controls a HTTP pprof interface.
|
|
|
|
type Server struct {
|
|
|
|
server *http.Server
|
2022-05-30 15:55:30 +00:00
|
|
|
log *zap.Logger
|
2021-06-28 13:20:23 +00:00
|
|
|
}
|
|
|
|
|
2021-10-09 18:18:53 +00:00
|
|
|
// NewMetricsServer creates a prometheus server on a particular interface and port
|
2022-05-30 15:55:30 +00:00
|
|
|
func NewMetricsServer(address string, port int, log *zap.Logger) *Server {
|
2022-01-18 18:17:06 +00:00
|
|
|
p := Server{
|
|
|
|
log: log.Named("metrics"),
|
|
|
|
}
|
|
|
|
|
2022-05-30 15:55:30 +00:00
|
|
|
p.log.Info("starting server", zap.String("address", address), zap.Int("port", port))
|
2021-06-28 13:20:23 +00:00
|
|
|
mux := http.NewServeMux()
|
2023-08-16 01:40:00 +00:00
|
|
|
mux.Handle("/metrics", promhttp.Handler())
|
2021-06-28 13:20:23 +00:00
|
|
|
|
2021-10-15 10:47:40 +00:00
|
|
|
// Healthcheck
|
|
|
|
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
fmt.Fprint(w, "OK")
|
|
|
|
})
|
|
|
|
|
2021-06-28 13:20:23 +00:00
|
|
|
h := &ochttp.Handler{Handler: mux}
|
|
|
|
|
2022-01-18 18:17:06 +00:00
|
|
|
p.server = &http.Server{
|
|
|
|
Addr: fmt.Sprintf("%s:%d", address, port),
|
|
|
|
Handler: h,
|
2021-06-28 13:20:23 +00:00
|
|
|
}
|
2021-10-16 21:50:49 +00:00
|
|
|
|
2021-06-28 13:20:23 +00:00
|
|
|
return &p
|
|
|
|
}
|
|
|
|
|
2021-10-09 18:18:53 +00:00
|
|
|
// Start executes the HTTP server in the background.
|
2021-06-28 13:20:23 +00:00
|
|
|
func (p *Server) Start() {
|
2023-12-01 01:23:28 +00:00
|
|
|
p.log.Info("server started ", zap.Error(p.server.ListenAndServe()))
|
2021-06-28 13:20:23 +00:00
|
|
|
}
|
|
|
|
|
2021-10-09 18:18:53 +00:00
|
|
|
// Stop shuts down the prometheus server
|
2021-10-18 12:43:17 +00:00
|
|
|
func (p *Server) Stop(ctx context.Context) error {
|
2021-06-28 13:20:23 +00:00
|
|
|
err := p.server.Shutdown(ctx)
|
|
|
|
if err != nil {
|
2022-05-30 15:55:30 +00:00
|
|
|
p.log.Error("stopping server", zap.Error(err))
|
2021-10-18 12:43:17 +00:00
|
|
|
return err
|
2021-06-28 13:20:23 +00:00
|
|
|
}
|
2021-10-18 12:43:17 +00:00
|
|
|
|
|
|
|
return nil
|
2021-06-28 13:20:23 +00:00
|
|
|
}
|