-
Notifications
You must be signed in to change notification settings - Fork 17
/
metrics.go
199 lines (181 loc) · 6.16 KB
/
metrics.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
package httpmetrics
import (
"context"
"fmt"
"log"
"log/slog"
"net/http"
"net/http/pprof"
"strconv"
"time"
"github.com/kelseyhightower/envconfig"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/client_golang/prometheus/promhttp"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/sdk/resource"
"go.opentelemetry.io/otel/sdk/trace"
)
// ServeMetrics serves the metrics endpoint if the METRICS_PORT env var is set.
func ServeMetrics() {
// Start the metrics server on the metrics port, if defined.
var env struct {
MetricsPort int `envconfig:"METRICS_PORT" default:"2112" required:"true"`
EnablePprof bool `envconfig:"ENABLE_PPROF" default:"false" required:"true"`
}
if err := envconfig.Process("", &env); err != nil {
slog.Error("Failed to process environment variables", "error", err)
return
}
mux := http.NewServeMux()
mux.Handle("/metrics", promhttp.Handler())
srv := &http.Server{
Addr: fmt.Sprintf(":%d", env.MetricsPort),
Handler: mux,
ReadHeaderTimeout: 10 * time.Second,
}
if env.EnablePprof {
// pprof handles
mux.HandleFunc("/debug/pprof/", pprof.Index)
mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
mux.Handle("/debug/pprof/allocs", pprof.Handler("allocs"))
mux.Handle("/debug/pprof/block", pprof.Handler("block"))
mux.Handle("/debug/pprof/goroutine", pprof.Handler("goroutine"))
mux.Handle("/debug/pprof/heap", pprof.Handler("heap"))
mux.Handle("/debug/pprof/mutex", pprof.Handler("mutex"))
mux.Handle("/debug/pprof/threadcreate", pprof.Handler("threadcreate"))
log.Println("registering handle for /debug/pprof")
}
if err := srv.ListenAndServe(); err != nil {
slog.Error("listen and serve for http /metrics", "error", err)
}
}
var (
inFlightGauge = promauto.NewGaugeVec(
prometheus.GaugeOpts{
Name: "http_inflight_requests",
Help: "A gauge of requests currently being served by the wrapped handler.",
},
[]string{"handler", "service_name", "configuration_name", "revision_name"},
)
duration = promauto.NewHistogramVec(
prometheus.HistogramOpts{
Name: "http_request_duration_seconds",
Help: "A histogram of latencies for requests.",
// TODO: tweak bucket values based on real usage.
Buckets: []float64{.25, .5, 1, 2.5, 5, 10, 20, 30, 45, 60},
},
[]string{"handler", "method", "service_name", "configuration_name", "revision_name"},
)
responseSize = promauto.NewHistogramVec(
prometheus.HistogramOpts{
Name: "http_response_size_bytes",
Help: "A histogram of response sizes for requests.",
// TODO: tweak bucket values based on real usage.
Buckets: []float64{200, 500, 900, 1500},
},
[]string{"handler", "method", "service_name", "configuration_name", "revision_name"},
)
counter = promauto.NewCounterVec(
prometheus.CounterOpts{
Name: "http_request_status",
Help: "The number of processed events by response code",
},
[]string{"handler", "method", "code", "service_name", "configuration_name", "revision_name", "ce_type"},
)
)
// https://cloud.google.com/run/docs/container-contract#services-env-vars
var env struct {
KnativeServiceName string `envconfig:"K_SERVICE" default:"unknown"`
KnativeConfigurationName string `envconfig:"K_CONFIGURATION" default:"unknown"`
KnativeRevisionName string `envconfig:"K_REVISION" default:"unknown"`
}
func init() {
if err := envconfig.Process("", &env); err != nil {
slog.Warn("Failed to process environment variables", "error", err)
}
}
// Handler wraps a given http handler in standard metrics handlers.
func Handler(name string, handler http.Handler) http.Handler {
labels := prometheus.Labels{
"handler": name,
"service_name": env.KnativeServiceName,
"configuration_name": env.KnativeConfigurationName,
"revision_name": env.KnativeRevisionName,
}
return promhttp.InstrumentHandlerInFlight(
inFlightGauge.With(labels),
promhttp.InstrumentHandlerDuration(
duration.MustCurryWith(labels),
instrumentHandlerCounter(
counter.MustCurryWith(labels),
promhttp.InstrumentHandlerResponseSize(
responseSize.MustCurryWith(labels),
otelhttp.NewHandler(handler, ""),
),
),
),
)
}
// Handler wraps a given http handler func in standard metrics handlers.
func HandlerFunc(name string, f func(http.ResponseWriter, *http.Request)) http.HandlerFunc {
return Handler(name, http.HandlerFunc(f)).ServeHTTP
}
// Fractions >= 1 will always sample. Fractions < 0 are treated as zero. To
// respect the parent trace's `SampledFlag`, the `TraceIDRatioBased` sampler
// should be used as a delegate of a `Parent` sampler.
//
// Expected usage:
//
// defer metrics.SetupTracer(ctx)()
func SetupTracer(ctx context.Context) func() {
traceExporter, err := otlptracehttp.New(ctx)
if err != nil {
log.Panicf("SetupTracer() = %v", err)
}
bsp := trace.NewBatchSpanProcessor(traceExporter)
res := resource.Default()
tp := trace.NewTracerProvider(
trace.WithResource(res),
trace.WithSpanProcessor(bsp),
)
otel.SetTracerProvider(tp)
prp := propagation.NewCompositeTextMapPropagator(
propagation.TraceContext{},
propagation.Baggage{},
)
otel.SetTextMapPropagator(prp)
return func() {
if err := tp.Shutdown(context.Background()); err != nil {
slog.Error("Error shutting down tracer provider", "error", err)
}
}
}
type delegator struct {
http.ResponseWriter
Status int
}
func (d *delegator) WriteHeader(status int) {
d.Status = status
d.ResponseWriter.WriteHeader(status)
}
func instrumentHandlerCounter(counter *prometheus.CounterVec, next http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
d := &delegator{
ResponseWriter: w,
Status: 200,
}
next.ServeHTTP(d, r)
counter.With(prometheus.Labels{
"method": r.Method,
"code": strconv.Itoa(d.Status),
"ce_type": r.Header.Get(CeTypeHeader),
}).Inc()
}
}