cloudflare/cloudflared

Public

mirrored from https://github.com/cloudflare/cloudflaredAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
2019.10.0

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

metrics/metrics.go

72lines · modecode

1package metrics
2
3import (
4 "context"
5 "net"
6 "net/http"
7 _ "net/http/pprof"
8 "runtime"
9 "sync"
10 "time"
11
12 "golang.org/x/net/trace"
13
14 "github.com/prometheus/client_golang/prometheus"
15 "github.com/prometheus/client_golang/prometheus/promhttp"
16 "github.com/sirupsen/logrus"
17)
18
19const (
20 shutdownTimeout = time.Second * 15
21 startupTime = time.Millisecond * 500
22)
23
24func ServeMetrics(l net.Listener, shutdownC <-chan struct{}, logger *logrus.Logger) (err error) {
25 var wg sync.WaitGroup
26 // Metrics port is privileged, so no need for further access control
27 trace.AuthRequest = func(*http.Request) (bool, bool) { return true, true }
28 // TODO: parameterize ReadTimeout and WriteTimeout. The maximum time we can
29 // profile CPU usage depends on WriteTimeout
30 server := &http.Server{
31 ReadTimeout: 10 * time.Second,
32 WriteTimeout: 10 * time.Second,
33 }
34
35 http.Handle("/metrics", promhttp.Handler())
36
37 wg.Add(1)
38 go func() {
39 defer wg.Done()
40 err = server.Serve(l)
41 }()
42 logger.WithField("addr", l.Addr()).Info("Starting metrics server")
43 // server.Serve will hang if server.Shutdown is called before the server is
44 // fully started up. So add artificial delay.
45 time.Sleep(startupTime)
46
47 <-shutdownC
48 ctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
49 server.Shutdown(ctx)
50 cancel()
51
52 wg.Wait()
53 if err == http.ErrServerClosed {
54 logger.Info("Metrics server stopped")
55 return nil
56 }
57 logger.WithError(err).Error("Metrics server quit with error")
58 return err
59}
60
61func RegisterBuildInfo(buildTime string, version string) {
62 buildInfo := prometheus.NewGaugeVec(
63 prometheus.GaugeOpts{
64 // Don't namespace build_info, since we want it to be consistent across all Cloudflare services
65 Name: "build_info",
66 Help: "Build and version information",
67 },
68 []string{"goversion", "revision", "version"},
69 )
70 prometheus.MustRegister(buildInfo)
71 buildInfo.WithLabelValues(runtime.Version(), buildTime, version).Set(1)
72}
73