1/*
2Copyright 2015 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package ratelimiter
18
19import (
20	"fmt"
21	"sync"
22
23	"k8s.io/client-go/util/flowcontrol"
24	"k8s.io/component-base/metrics"
25	"k8s.io/component-base/metrics/legacyregistry"
26)
27
28var (
29	metricsLock        sync.Mutex
30	rateLimiterMetrics = make(map[string]*rateLimiterMetric)
31)
32
33type rateLimiterMetric struct {
34	metric metrics.GaugeMetric
35	stopCh chan struct{}
36}
37
38func registerRateLimiterMetric(ownerName string) error {
39	metricsLock.Lock()
40	defer metricsLock.Unlock()
41
42	if _, ok := rateLimiterMetrics[ownerName]; ok {
43		// only register once in Prometheus. We happen to see an ownerName reused in parallel integration tests.
44		return nil
45	}
46	metric := metrics.NewGauge(&metrics.GaugeOpts{
47		Name:           "rate_limiter_use",
48		Subsystem:      ownerName,
49		Help:           fmt.Sprintf("A metric measuring the saturation of the rate limiter for %v", ownerName),
50		StabilityLevel: metrics.ALPHA,
51	})
52	if err := legacyregistry.Register(metric); err != nil {
53		return fmt.Errorf("error registering rate limiter usage metric: %v", err)
54	}
55	stopCh := make(chan struct{})
56	rateLimiterMetrics[ownerName] = &rateLimiterMetric{
57		metric: metric,
58		stopCh: stopCh,
59	}
60	return nil
61}
62
63// RegisterMetricAndTrackRateLimiterUsage registers a metric ownerName_rate_limiter_use in prometheus to track
64// how much used rateLimiter is and starts a goroutine that updates this metric every updatePeriod
65func RegisterMetricAndTrackRateLimiterUsage(ownerName string, rateLimiter flowcontrol.RateLimiter) error {
66	if err := registerRateLimiterMetric(ownerName); err != nil {
67		return err
68	}
69	// TODO: determine how to track rate limiter saturation
70	// See discussion at https://go-review.googlesource.com/c/time/+/29958#message-4caffc11669cadd90e2da4c05122cfec50ea6a22
71	// go wait.Until(func() {
72	//   metricsLock.Lock()
73	//   defer metricsLock.Unlock()
74	//   rateLimiterMetrics[ownerName].metric.Set()
75	// }, updatePeriod, rateLimiterMetrics[ownerName].stopCh)
76	return nil
77}
78