/
singleton.go
185 lines (159 loc) · 6.24 KB
/
singleton.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
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package controller
import (
"context"
"errors"
"time"
"github.com/prometheus/client_golang/prometheus"
"k8s.io/client-go/util/workqueue"
"knative.dev/pkg/logging"
"sigs.k8s.io/controller-runtime/pkg/manager"
crmetrics "sigs.k8s.io/controller-runtime/pkg/metrics"
"sigs.k8s.io/controller-runtime/pkg/ratelimiter"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/karpenter/pkg/operator/injection"
"sigs.k8s.io/karpenter/pkg/metrics"
)
const (
Immediately = 1 * time.Nanosecond
)
type SingletonBuilder struct {
mgr manager.Manager
}
func NewSingletonManagedBy(m manager.Manager) SingletonBuilder {
return SingletonBuilder{
mgr: m,
}
}
func (b SingletonBuilder) Complete(r Reconciler) error {
return b.mgr.Add(newSingleton(r))
}
type Singleton struct {
Reconciler
rateLimiter ratelimiter.RateLimiter
}
func newSingleton(r Reconciler) *Singleton {
s := &Singleton{
Reconciler: r,
rateLimiter: workqueue.DefaultItemBasedRateLimiter(),
}
s.initMetrics()
return s
}
// initMetrics is effectively the same metrics initialization function used by controller-runtime
// https://github.com/kubernetes-sigs/controller-runtime/blob/main/pkg/internal/controller/controller.go
func (s *Singleton) initMetrics() {
activeWorkers.WithLabelValues(s.Name()).Set(0)
reconcileErrors.WithLabelValues(s.Name()).Add(0)
reconcileTotal.WithLabelValues(s.Name(), labelError).Add(0)
reconcileTotal.WithLabelValues(s.Name(), labelRequeueAfter).Add(0)
reconcileTotal.WithLabelValues(s.Name(), labelRequeue).Add(0)
reconcileTotal.WithLabelValues(s.Name(), labelSuccess).Add(0)
workerCount.WithLabelValues(s.Name()).Set(float64(1))
}
var singletonRequest = reconcile.Request{}
func (s *Singleton) Start(ctx context.Context) error {
ctx = injection.WithControllerName(ctx, s.Name())
ctx = logging.WithLogger(ctx, logging.FromContext(ctx).Named(s.Name()))
logging.FromContext(ctx).Infof("starting controller")
defer logging.FromContext(ctx).Infof("stopping controller")
for {
select {
case <-time.After(s.reconcile(ctx)):
case <-ctx.Done():
return nil
}
}
}
func (s *Singleton) reconcile(ctx context.Context) time.Duration {
activeWorkers.WithLabelValues(s.Name()).Inc()
defer activeWorkers.WithLabelValues(s.Name()).Dec()
measureDuration := metrics.Measure(reconcileDuration.WithLabelValues(s.Name()))
res, err := s.Reconcile(ctx, singletonRequest)
measureDuration() // Observe the length of time between the function creation and now
switch {
case err != nil:
reconcileErrors.WithLabelValues(s.Name()).Inc()
reconcileTotal.WithLabelValues(s.Name(), labelError).Inc()
logging.FromContext(ctx).Error(err)
return s.rateLimiter.When(singletonRequest)
case res.Requeue:
reconcileTotal.WithLabelValues(s.Name(), labelRequeue).Inc()
return s.rateLimiter.When(singletonRequest)
default:
s.rateLimiter.Forget(singletonRequest)
switch {
case res.RequeueAfter > 0:
reconcileTotal.WithLabelValues(s.Name(), labelRequeueAfter).Inc()
return res.RequeueAfter
default:
reconcileTotal.WithLabelValues(s.Name(), labelSuccess).Inc()
return time.Duration(0)
}
}
}
func (s *Singleton) NeedLeaderElection() bool {
return true
}
func init() {
mergeMetrics()
}
const (
labelError = "error"
labelRequeueAfter = "requeue_after"
labelRequeue = "requeue"
labelSuccess = "success"
)
// Metrics below are copied metrics fired by controller-runtime in its /internal package. This is leveraged
// so that we can fire to the same namespace as users expect other controller-runtime metrics to be fired
// https://github.com/kubernetes-sigs/controller-runtime/blob/main/pkg/internal/controller/metrics/metrics.go
var (
reconcileTotal = prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "controller_runtime_reconcile_total",
Help: "Total number of reconciliations per controller",
}, []string{"controller", "result"})
reconcileDuration = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "controller_runtime_reconcile_time_seconds",
Help: "Length of time per reconciliation per controller",
Buckets: metrics.DurationBuckets(),
}, []string{"controller"})
reconcileErrors = prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "controller_runtime_reconcile_errors_total",
Help: "Total number of reconciliation errors per controller",
}, []string{"controller"})
workerCount = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Name: "controller_runtime_max_concurrent_reconciles",
Help: "Maximum number of concurrent reconciles per controller",
}, []string{"controller"})
activeWorkers = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Name: "controller_runtime_active_workers",
Help: "Number of currently used workers per controller",
}, []string{"controller"})
)
// mergeMetrics merges the singletonMetrics with metrics already registered in the controller-runtime metrics registry
// https://github.com/kubernetes-sigs/controller-runtime/blob/main/pkg/internal/controller/metrics/metrics.go
// We know that all these metrics should be registered by controller-runtime so we should switch over
func mergeMetrics() {
err := &prometheus.AlreadyRegisteredError{}
errors.As(crmetrics.Registry.Register(reconcileTotal), err)
reconcileTotal = err.ExistingCollector.(*prometheus.CounterVec)
errors.As(crmetrics.Registry.Register(reconcileDuration), err)
reconcileDuration = err.ExistingCollector.(*prometheus.HistogramVec)
errors.As(crmetrics.Registry.Register(reconcileErrors), err)
reconcileErrors = err.ExistingCollector.(*prometheus.CounterVec)
errors.As(crmetrics.Registry.Register(workerCount), err)
workerCount = err.ExistingCollector.(*prometheus.GaugeVec)
errors.As(crmetrics.Registry.Register(activeWorkers), err)
activeWorkers = err.ExistingCollector.(*prometheus.GaugeVec)
}