-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmetrics.go
More file actions
565 lines (441 loc) · 15.5 KB
/
Copy pathmetrics.go
File metadata and controls
565 lines (441 loc) · 15.5 KB
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
package service
import (
"context"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"sync"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
// MetricsCollector holds all the metrics for the service with a flexible registry
type MetricsCollector struct {
serviceName string
registry *prometheus.Registry
mu sync.RWMutex
// Built-in HTTP metrics (always available)
httpRequestsTotal *prometheus.CounterVec
httpRequestDuration *prometheus.HistogramVec
httpRequestsInFlight prometheus.Gauge
// Custom metrics registry
counters map[string]*prometheus.CounterVec
gauges map[string]*prometheus.GaugeVec
histograms map[string]*prometheus.HistogramVec
summaries map[string]*prometheus.SummaryVec
}
// MetricConfig holds configuration for creating custom metrics
type MetricConfig struct {
Name string
Help string
Labels []string
Buckets []float64 // For histograms
Objectives map[float64]float64 // For summaries
}
// NewMetricsCollector creates a new metrics collector with a flexible registry
func NewMetricsCollector(serviceName string) *MetricsCollector {
registry := prometheus.NewRegistry()
metricsCollector := &MetricsCollector{
serviceName: serviceName,
registry: registry,
counters: make(map[string]*prometheus.CounterVec),
gauges: make(map[string]*prometheus.GaugeVec),
histograms: make(map[string]*prometheus.HistogramVec),
summaries: make(map[string]*prometheus.SummaryVec),
}
// Create built-in HTTP metrics
metricsCollector.httpRequestsTotal = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: serviceName + "_http_requests_total",
Help: "Total number of HTTP requests",
},
[]string{"method", "endpoint", "status_code"},
)
metricsCollector.httpRequestDuration = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: serviceName + "_http_request_duration_seconds",
Help: "HTTP request duration in seconds",
Buckets: prometheus.DefBuckets,
},
[]string{"method", "endpoint", "status_code"},
)
metricsCollector.httpRequestsInFlight = prometheus.NewGauge(
prometheus.GaugeOpts{
Name: serviceName + "_http_requests_in_flight",
Help: "Number of HTTP requests currently being processed",
},
)
// Register built-in metrics
registry.MustRegister(metricsCollector.httpRequestsTotal)
registry.MustRegister(metricsCollector.httpRequestDuration)
registry.MustRegister(metricsCollector.httpRequestsInFlight)
return metricsCollector
}
// RegisterCounter registers a new counter metric
func (mc *MetricsCollector) RegisterCounter(config MetricConfig) error {
mc.mu.Lock()
defer mc.mu.Unlock()
// Ensure metric name has service prefix
prefixedName := mc.ensureMetricNamePrefix(config.Name)
if _, exists := mc.counters[prefixedName]; exists {
return fmt.Errorf("counter %s already exists", prefixedName) //nolint:err113
}
counter := prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: prefixedName,
Help: config.Help,
},
config.Labels,
)
if err := mc.registry.Register(counter); err != nil {
return fmt.Errorf("failed to register counter %s: %w", prefixedName, err)
}
mc.counters[prefixedName] = counter
return nil
}
// RegisterGauge registers a new gauge metric
func (mc *MetricsCollector) RegisterGauge(config MetricConfig) error {
mc.mu.Lock()
defer mc.mu.Unlock()
// Ensure metric name has service prefix
prefixedName := mc.ensureMetricNamePrefix(config.Name)
if _, exists := mc.gauges[prefixedName]; exists {
return fmt.Errorf("gauge %s already exists", prefixedName) //nolint:err113
}
gauge := prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: prefixedName,
Help: config.Help,
},
config.Labels,
)
if err := mc.registry.Register(gauge); err != nil {
return fmt.Errorf("failed to register gauge %s: %w", prefixedName, err)
}
mc.gauges[prefixedName] = gauge
return nil
}
// RegisterHistogram registers a new histogram metric
func (mc *MetricsCollector) RegisterHistogram(config MetricConfig) error {
mc.mu.Lock()
defer mc.mu.Unlock()
// Ensure metric name has service prefix
prefixedName := mc.ensureMetricNamePrefix(config.Name)
if _, exists := mc.histograms[prefixedName]; exists {
return fmt.Errorf("histogram %s already exists", prefixedName) //nolint:err113
}
buckets := config.Buckets
if len(buckets) == 0 {
buckets = prometheus.DefBuckets
}
histogram := prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: prefixedName,
Help: config.Help,
Buckets: buckets,
},
config.Labels,
)
if err := mc.registry.Register(histogram); err != nil {
return fmt.Errorf("failed to register histogram %s: %w", prefixedName, err)
}
mc.histograms[prefixedName] = histogram
return nil
}
// RegisterSummary registers a new summary metric
func (mc *MetricsCollector) RegisterSummary(config MetricConfig) error {
mc.mu.Lock()
defer mc.mu.Unlock()
// Ensure metric name has service prefix
prefixedName := mc.ensureMetricNamePrefix(config.Name)
if _, exists := mc.summaries[prefixedName]; exists {
return fmt.Errorf("summary %s already exists", prefixedName) //nolint:err113
}
objectives := config.Objectives
if len(objectives) == 0 {
objectives = map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001}
}
summary := prometheus.NewSummaryVec(
prometheus.SummaryOpts{
Name: prefixedName,
Help: config.Help,
Objectives: objectives,
},
config.Labels,
)
if err := mc.registry.Register(summary); err != nil {
return fmt.Errorf("failed to register summary %s: %w", prefixedName, err)
}
mc.summaries[prefixedName] = summary
return nil
}
// IncCounter increments a counter metric
func (mc *MetricsCollector) IncCounter(name string, labels ...string) error {
mc.mu.RLock()
defer mc.mu.RUnlock()
// Ensure metric name has service prefix
prefixedName := mc.ensureMetricNamePrefix(name)
counter, exists := mc.counters[prefixedName]
if !exists {
return fmt.Errorf("counter %s not found", prefixedName) //nolint:err113
}
counter.WithLabelValues(labels...).Inc()
return nil
}
// AddCounter adds a value to a counter metric
func (mc *MetricsCollector) AddCounter(name string, value float64, labels ...string) error {
mc.mu.RLock()
defer mc.mu.RUnlock()
// Ensure metric name has service prefix
prefixedName := mc.ensureMetricNamePrefix(name)
counter, exists := mc.counters[prefixedName]
if !exists {
return fmt.Errorf("counter %s not found", prefixedName) //nolint:err113
}
counter.WithLabelValues(labels...).Add(value)
return nil
}
// SetGauge sets a gauge metric value
func (mc *MetricsCollector) SetGauge(name string, value float64, labels ...string) error {
mc.mu.RLock()
defer mc.mu.RUnlock()
// Ensure metric name has service prefix
prefixedName := mc.ensureMetricNamePrefix(name)
gauge, exists := mc.gauges[prefixedName]
if !exists {
return fmt.Errorf("gauge %s not found", prefixedName) //nolint:err113
}
gauge.WithLabelValues(labels...).Set(value)
return nil
}
// IncGauge increments a gauge metric
func (mc *MetricsCollector) IncGauge(name string, labels ...string) error {
mc.mu.RLock()
defer mc.mu.RUnlock()
// Ensure metric name has service prefix
prefixedName := mc.ensureMetricNamePrefix(name)
gauge, exists := mc.gauges[prefixedName]
if !exists {
return fmt.Errorf("gauge %s not found", prefixedName) //nolint:err113
}
gauge.WithLabelValues(labels...).Inc()
return nil
}
// DecGauge decrements a gauge metric
func (mc *MetricsCollector) DecGauge(name string, labels ...string) error {
mc.mu.RLock()
defer mc.mu.RUnlock()
// Ensure metric name has service prefix
prefixedName := mc.ensureMetricNamePrefix(name)
gauge, exists := mc.gauges[prefixedName]
if !exists {
return fmt.Errorf("gauge %s not found", prefixedName) //nolint:err113
}
gauge.WithLabelValues(labels...).Dec()
return nil
}
// AddGauge adds a value to a gauge metric
func (mc *MetricsCollector) AddGauge(name string, value float64, labels ...string) error {
mc.mu.RLock()
defer mc.mu.RUnlock()
// Ensure metric name has service prefix
prefixedName := mc.ensureMetricNamePrefix(name)
gauge, exists := mc.gauges[prefixedName]
if !exists {
return fmt.Errorf("gauge %s not found", prefixedName) //nolint:err113
}
gauge.WithLabelValues(labels...).Add(value)
return nil
}
// ObserveHistogram observes a value in a histogram metric
func (mc *MetricsCollector) ObserveHistogram(name string, value float64, labels ...string) error {
mc.mu.RLock()
defer mc.mu.RUnlock()
// Ensure metric name has service prefix
prefixedName := mc.ensureMetricNamePrefix(name)
histogram, exists := mc.histograms[prefixedName]
if !exists {
return fmt.Errorf("histogram %s not found", prefixedName) //nolint:err113
}
histogram.WithLabelValues(labels...).Observe(value)
return nil
}
// ObserveSummary observes a value in a summary metric
func (mc *MetricsCollector) ObserveSummary(name string, value float64, labels ...string) error {
mc.mu.RLock()
defer mc.mu.RUnlock()
// Ensure metric name has service prefix
prefixedName := mc.ensureMetricNamePrefix(name)
summary, exists := mc.summaries[prefixedName]
if !exists {
return fmt.Errorf("summary %s not found", prefixedName) //nolint:err113
}
summary.WithLabelValues(labels...).Observe(value)
return nil
}
// GetRegistry returns the Prometheus registry for custom integrations
func (mc *MetricsCollector) GetRegistry() *prometheus.Registry {
return mc.registry
}
// ensureMetricNamePrefix ensures the metric name has the service name prefix
func (mc *MetricsCollector) ensureMetricNamePrefix(name string) string {
if !strings.HasPrefix(name, mc.serviceName+"_") {
return mc.serviceName + "_" + name
}
return name
}
// responseWriter wraps http.ResponseWriter to capture status code
type responseWriter struct {
http.ResponseWriter
statusCode int
}
// WriteHeader captures the status code
func (rw *responseWriter) WriteHeader(code int) {
rw.statusCode = code
rw.ResponseWriter.WriteHeader(code)
}
// MetricsMiddleware creates middleware that records HTTP metrics
func MetricsMiddleware(metrics *MetricsCollector) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Add metrics collector to context
ctx := context.WithValue(r.Context(), MetricsKey, metrics)
r = r.WithContext(ctx)
// Track in-flight requests
metrics.httpRequestsInFlight.Inc()
defer metrics.httpRequestsInFlight.Dec()
// Create wrapped response writer to capture status code
wrapped := &responseWriter{
ResponseWriter: w,
statusCode: 200, // Default status code
}
// Record request start time
start := time.Now()
// Call the next handler
next.ServeHTTP(wrapped, r)
// Record metrics
duration := time.Since(start).Seconds()
statusCode := strconv.Itoa(wrapped.statusCode)
metrics.httpRequestsTotal.WithLabelValues(
r.Method, r.URL.Path, statusCode,
).Inc()
metrics.httpRequestDuration.WithLabelValues(
r.Method, r.URL.Path, statusCode,
).Observe(duration)
})
}
}
// GetMetrics retrieves the metrics collector from the request context
func GetMetrics(r *http.Request) *MetricsCollector {
metrics, ok := r.Context().Value(MetricsKey).(*MetricsCollector)
if !ok {
return nil
}
return metrics
}
// Helper functions for easy metric manipulation from handlers
// IncCounter increments a counter metric from a request context
func IncCounter(r *http.Request, name string, labels ...string) error {
metrics := GetMetrics(r)
if metrics == nil {
return errors.New("metrics not available in request context") //nolint:err113
}
return metrics.IncCounter(name, labels...)
}
// AddCounter adds a value to a counter metric from a request context
func AddCounter(r *http.Request, name string, value float64, labels ...string) error {
metrics := GetMetrics(r)
if metrics == nil {
return errors.New("metrics not available in request context") //nolint:err113
}
return metrics.AddCounter(name, value, labels...)
}
// SetGauge sets a gauge metric value from a request context
func SetGauge(r *http.Request, name string, value float64, labels ...string) error {
metrics := GetMetrics(r)
if metrics == nil {
return errors.New("metrics not available in request context") //nolint:err113
}
return metrics.SetGauge(name, value, labels...)
}
// IncGauge increments a gauge metric from a request context
func IncGauge(r *http.Request, name string, labels ...string) error {
metrics := GetMetrics(r)
if metrics == nil {
return errors.New("metrics not available in request context") //nolint:err113
}
return metrics.IncGauge(name, labels...)
}
// DecGauge decrements a gauge metric from a request context
func DecGauge(r *http.Request, name string, labels ...string) error {
metrics := GetMetrics(r)
if metrics == nil {
return errors.New("metrics not available in request context") //nolint:err113
}
return metrics.DecGauge(name, labels...)
}
// AddGauge adds a value to a gauge metric from a request context
func AddGauge(r *http.Request, name string, value float64, labels ...string) error {
metrics := GetMetrics(r)
if metrics == nil {
return errors.New("metrics not available in request context") //nolint:err113
}
return metrics.AddGauge(name, value, labels...)
}
// ObserveHistogram observes a value in a histogram metric from a request context
func ObserveHistogram(r *http.Request, name string, value float64, labels ...string) error {
metrics := GetMetrics(r)
if metrics == nil {
return errors.New("metrics not available in request context") //nolint:err113
}
return metrics.ObserveHistogram(name, value, labels...)
}
// ObserveSummary observes a value in a summary metric from a request context
func ObserveSummary(r *http.Request, name string, value float64, labels ...string) error {
metrics := GetMetrics(r)
if metrics == nil {
return errors.New("metrics not available in request context") //nolint:err113
}
return metrics.ObserveSummary(name, value, labels...)
}
// startMetricsServer starts the Prometheus metrics server
func (s *Service) startMetricsServer() error {
mux := http.NewServeMux()
// Use the custom registry from metrics collector
handler := promhttp.HandlerFor(s.Metrics.GetRegistry(), promhttp.HandlerOpts{})
mux.Handle(s.Config.MetricsPath, handler)
// Add health check endpoints
if s.HealthChecker != nil {
// Main health check endpoint (comprehensive health status)
mux.Handle(s.Config.HealthPath, s.HealthChecker.Handler())
// Kubernetes readiness probe endpoint
mux.HandleFunc(s.Config.ReadinessPath, s.HealthChecker.ReadinessHandler())
// Kubernetes liveness probe endpoint
mux.HandleFunc(s.Config.LivenessPath, s.HealthChecker.LivenessHandler())
} else {
// Fallback basic health endpoints if health checker is not available
mux.HandleFunc(s.Config.HealthPath, func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("OK"))
})
mux.HandleFunc(s.Config.ReadinessPath, func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("Ready"))
})
mux.HandleFunc(s.Config.LivenessPath, func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("Alive"))
})
}
s.metricsServer = &http.Server{
Addr: s.Config.MetricsAddr,
Handler: mux,
ReadTimeout: 5 * time.Minute,
WriteTimeout: 5 * time.Minute,
IdleTimeout: 5 * time.Minute,
}
s.Logger.Info("starting metrics server", "addr", s.Config.MetricsAddr, "path", s.Config.MetricsPath)
return s.metricsServer.ListenAndServe() //nolint:wrapcheck
}