cloudflared-mirror/metrics/metrics.go

73 lines
1.9 KiB
Go
Raw Normal View History

2017-10-16 11:44:03 +00:00
package metrics
import (
"net"
"net/http"
_ "net/http/pprof"
"runtime"
2017-12-21 12:21:57 +00:00
"sync"
2017-10-16 11:44:03 +00:00
"time"
"golang.org/x/net/context"
2017-12-21 12:21:57 +00:00
"golang.org/x/net/trace"
2017-10-16 11:44:03 +00:00
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
2018-04-26 14:57:32 +00:00
"github.com/sirupsen/logrus"
2017-10-16 11:44:03 +00:00
)
2017-12-21 12:21:57 +00:00
const (
shutdownTimeout = time.Second * 15
startupTime = time.Millisecond * 500
)
2018-04-26 14:57:32 +00:00
func ServeMetrics(l net.Listener, shutdownC <-chan struct{}, logger *logrus.Logger) (err error) {
2017-12-21 12:21:57 +00:00
var wg sync.WaitGroup
// Metrics port is privileged, so no need for further access control
trace.AuthRequest = func(*http.Request) (bool, bool) { return true, true }
// TODO: parameterize ReadTimeout and WriteTimeout. The maximum time we can
// profile CPU usage depends on WriteTimeout
2017-10-16 11:44:03 +00:00
server := &http.Server{
2017-12-21 12:21:57 +00:00
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
2017-10-16 11:44:03 +00:00
}
2017-12-21 12:21:57 +00:00
http.Handle("/metrics", promhttp.Handler())
wg.Add(1)
2017-10-16 11:44:03 +00:00
go func() {
2017-12-21 12:21:57 +00:00
defer wg.Done()
err = server.Serve(l)
2017-10-16 11:44:03 +00:00
}()
2018-04-26 14:57:32 +00:00
logger.WithField("addr", l.Addr()).Info("Starting metrics server")
2017-12-21 12:21:57 +00:00
// server.Serve will hang if server.Shutdown is called before the server is
// fully started up. So add artificial delay.
time.Sleep(startupTime)
<-shutdownC
ctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
server.Shutdown(ctx)
cancel()
wg.Wait()
2017-10-16 11:44:03 +00:00
if err == http.ErrServerClosed {
2018-04-26 14:57:32 +00:00
logger.Info("Metrics server stopped")
2017-10-16 11:44:03 +00:00
return nil
}
2018-04-26 14:57:32 +00:00
logger.WithError(err).Error("Metrics server quit with error")
2017-10-16 11:44:03 +00:00
return err
}
func RegisterBuildInfo(buildTime string, version string) {
buildInfo := prometheus.NewGaugeVec(
prometheus.GaugeOpts{
// Don't namespace build_info, since we want it to be consistent across all Cloudflare services
Name: "build_info",
Help: "Build and version information",
},
[]string{"goversion", "revision", "version"},
)
prometheus.MustRegister(buildInfo)
buildInfo.WithLabelValues(runtime.Version(), buildTime, version).Set(1)
}