github.com/cilium/cilium@v1.16.2/pkg/api/metrics/metrics.go (about) 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright Authors of Cilium 3 4 package metrics 5 6 import ( 7 "time" 8 9 "github.com/prometheus/client_golang/prometheus" 10 11 "github.com/cilium/cilium/operator/metrics" 12 ) 13 14 // PrometheusMetrics is an implementation of Prometheus metrics for external 15 // API usage 16 type PrometheusMetrics struct { 17 registry metrics.RegisterGatherer 18 APIDuration *prometheus.HistogramVec 19 RateLimit *prometheus.HistogramVec 20 } 21 22 // NewPrometheusMetrics returns a new metrics tracking implementation to cover 23 // external API usage. 24 func NewPrometheusMetrics(namespace, subsystem string, registry metrics.RegisterGatherer) *PrometheusMetrics { 25 m := &PrometheusMetrics{registry: registry} 26 27 m.APIDuration = prometheus.NewHistogramVec(prometheus.HistogramOpts{ 28 Namespace: namespace, 29 Subsystem: subsystem, 30 Name: "api_duration_seconds", 31 Help: "Duration of interactions with API", 32 }, []string{"operation", "response_code"}) 33 34 m.RateLimit = prometheus.NewHistogramVec(prometheus.HistogramOpts{ 35 Namespace: namespace, 36 Subsystem: subsystem, 37 Name: "api_rate_limit_duration_seconds", 38 Help: "Duration of client-side rate limiter blocking", 39 }, []string{"operation"}) 40 41 registry.MustRegister(m.APIDuration) 42 registry.MustRegister(m.RateLimit) 43 44 return m 45 } 46 47 // ObserveAPICall must be called on every API call made with the operation 48 // performed, the status code received and the duration of the call 49 func (p *PrometheusMetrics) ObserveAPICall(operation, status string, duration float64) { 50 p.APIDuration.WithLabelValues(operation, status).Observe(duration) 51 } 52 53 // ObserveRateLimit must be called in case an API call was subject to rate limiting 54 func (p *PrometheusMetrics) ObserveRateLimit(operation string, delay time.Duration) { 55 p.RateLimit.WithLabelValues(operation).Observe(delay.Seconds()) 56 } 57 58 // NoOpMetrics is a no-op implementation 59 type NoOpMetrics struct{} 60 61 // ObserveAPICall must be called on every API call made with the operation 62 // performed, the status code received and the duration of the call. This No-op 63 // implementation will perform no metrics accounting in return. 64 func (m *NoOpMetrics) ObserveAPICall(call, status string, duration float64) {} 65 66 // ObserveRateLimit must be called in case an API call was subject to rate 67 // limiting. This No-op implementation will perform no metrics accounting in 68 // return. 69 func (m *NoOpMetrics) ObserveRateLimit(operation string, duration time.Duration) {}