cloudflare/cloudflared

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
2019.11.2

Branches

Tags

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

Clone

HTTPS

Download ZIP

metrics/metrics.go

76lines · modecode

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