-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
controller_fetcher.go
349 lines (303 loc) · 11.6 KB
/
controller_fetcher.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
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
/*
Copyright 2019 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 controllerfetcher
import (
"context"
"fmt"
"time"
appsv1 "k8s.io/api/apps/v1"
autoscalingapi "k8s.io/api/autoscaling/v1"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
apimeta "k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/discovery"
cacheddiscovery "k8s.io/client-go/discovery/cached"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/informers"
kube_client "k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/restmapper"
"k8s.io/client-go/scale"
"k8s.io/client-go/tools/cache"
klog "k8s.io/klog/v2"
)
type wellKnownController string
const (
cronJob wellKnownController = "CronJob"
daemonSet wellKnownController = "DaemonSet"
deployment wellKnownController = "Deployment"
node wellKnownController = "Node"
job wellKnownController = "Job"
replicaSet wellKnownController = "ReplicaSet"
replicationController wellKnownController = "ReplicationController"
statefulSet wellKnownController = "StatefulSet"
)
const (
discoveryResetPeriod time.Duration = 5 * time.Minute
)
// ControllerKey identifies a controller.
type ControllerKey struct {
Namespace string
Kind string
Name string
}
// ControllerKeyWithAPIVersion identifies a controller and API it's defined in.
type ControllerKeyWithAPIVersion struct {
ControllerKey
ApiVersion string
}
// ControllerFetcher is responsible for finding the topmost well-known or scalable controller
type ControllerFetcher interface {
// FindTopMostWellKnownOrScalable returns topmost well-known or scalable controller. Error is returned if controller cannot be found.
FindTopMostWellKnownOrScalable(controller *ControllerKeyWithAPIVersion) (*ControllerKeyWithAPIVersion, error)
}
type controllerFetcher struct {
scaleNamespacer scale.ScalesGetter
mapper apimeta.RESTMapper
informersMap map[wellKnownController]cache.SharedIndexInformer
scaleSubresourceCacheStorage controllerCacheStorage
}
func (f *controllerFetcher) periodicallyRefreshCache(ctx context.Context, period time.Duration) {
for {
select {
case <-ctx.Done():
return
case <-time.After(period):
keysToRefresh := f.scaleSubresourceCacheStorage.GetKeysToRefresh()
klog.V(5).Info("Starting to refresh entries in controllerFetchers scaleSubresourceCacheStorage")
for _, item := range keysToRefresh {
scale, err := f.scaleNamespacer.Scales(item.namespace).Get(context.TODO(), item.groupResource, item.name, metav1.GetOptions{})
f.scaleSubresourceCacheStorage.Refresh(item.namespace, item.groupResource, item.name, scale, err)
}
klog.V(5).Infof("Finished refreshing %d entries in controllerFetchers scaleSubresourceCacheStorage", len(keysToRefresh))
f.scaleSubresourceCacheStorage.RemoveExpired()
}
}
}
func (f *controllerFetcher) Start(ctx context.Context, loopPeriod time.Duration) {
go f.periodicallyRefreshCache(ctx, loopPeriod)
}
// NewControllerFetcher returns a new instance of controllerFetcher
func NewControllerFetcher(config *rest.Config, kubeClient kube_client.Interface, factory informers.SharedInformerFactory, betweenRefreshes, lifeTime time.Duration, jitterFactor float64) *controllerFetcher {
discoveryClient, err := discovery.NewDiscoveryClientForConfig(config)
if err != nil {
klog.Fatalf("Could not create discoveryClient: %v", err)
}
resolver := scale.NewDiscoveryScaleKindResolver(discoveryClient)
restClient := kubeClient.CoreV1().RESTClient()
cachedDiscoveryClient := cacheddiscovery.NewMemCacheClient(discoveryClient)
mapper := restmapper.NewDeferredDiscoveryRESTMapper(cachedDiscoveryClient)
go wait.Until(func() {
mapper.Reset()
}, discoveryResetPeriod, make(chan struct{}))
informersMap := map[wellKnownController]cache.SharedIndexInformer{
daemonSet: factory.Apps().V1().DaemonSets().Informer(),
deployment: factory.Apps().V1().Deployments().Informer(),
replicaSet: factory.Apps().V1().ReplicaSets().Informer(),
statefulSet: factory.Apps().V1().StatefulSets().Informer(),
replicationController: factory.Core().V1().ReplicationControllers().Informer(),
job: factory.Batch().V1().Jobs().Informer(),
cronJob: factory.Batch().V1().CronJobs().Informer(),
}
for kind, informer := range informersMap {
stopCh := make(chan struct{})
go informer.Run(stopCh)
synced := cache.WaitForCacheSync(stopCh, informer.HasSynced)
if !synced {
klog.Warningf("Could not sync cache for %s: %v", kind, err)
} else {
klog.Infof("Initial sync of %s completed", kind)
}
}
scaleNamespacer := scale.New(restClient, mapper, dynamic.LegacyAPIPathResolverFunc, resolver)
return &controllerFetcher{
scaleNamespacer: scaleNamespacer,
mapper: mapper,
informersMap: informersMap,
scaleSubresourceCacheStorage: newControllerCacheStorage(betweenRefreshes, lifeTime, jitterFactor),
}
}
func getOwnerController(owners []metav1.OwnerReference, namespace string) *ControllerKeyWithAPIVersion {
for _, owner := range owners {
if owner.Controller != nil && *owner.Controller {
return &ControllerKeyWithAPIVersion{
ControllerKey: ControllerKey{
Namespace: namespace,
Kind: owner.Kind,
Name: owner.Name,
},
ApiVersion: owner.APIVersion,
}
}
}
return nil
}
func getParentOfWellKnownController(informer cache.SharedIndexInformer, controllerKey ControllerKeyWithAPIVersion) (*ControllerKeyWithAPIVersion, error) {
namespace := controllerKey.Namespace
name := controllerKey.Name
kind := controllerKey.Kind
obj, exists, err := informer.GetStore().GetByKey(namespace + "/" + name)
if err != nil {
return nil, err
}
if !exists {
return nil, fmt.Errorf("%s %s/%s does not exist", kind, namespace, name)
}
switch apiObj := obj.(type) {
case (*appsv1.DaemonSet):
return getOwnerController(apiObj.OwnerReferences, namespace), nil
case (*appsv1.Deployment):
return getOwnerController(apiObj.OwnerReferences, namespace), nil
case (*appsv1.StatefulSet):
return getOwnerController(apiObj.OwnerReferences, namespace), nil
case (*appsv1.ReplicaSet):
return getOwnerController(apiObj.OwnerReferences, namespace), nil
case (*batchv1.Job):
return getOwnerController(apiObj.OwnerReferences, namespace), nil
case (*batchv1.CronJob):
return getOwnerController(apiObj.OwnerReferences, namespace), nil
case (*corev1.ReplicationController):
return getOwnerController(apiObj.OwnerReferences, namespace), nil
}
return nil, fmt.Errorf("don't know how to read owner controller")
}
func (f *controllerFetcher) getParentOfController(controllerKey ControllerKeyWithAPIVersion) (*ControllerKeyWithAPIVersion, error) {
kind := wellKnownController(controllerKey.Kind)
informer, exists := f.informersMap[kind]
if exists {
return getParentOfWellKnownController(informer, controllerKey)
}
groupKind, err := controllerKey.groupKind()
if err != nil {
return nil, err
}
owner, err := f.getOwnerForScaleResource(groupKind, controllerKey.Namespace, controllerKey.Name)
if apierrors.IsNotFound(err) {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("Unhandled targetRef %s / %s / %s, last error %v",
controllerKey.ApiVersion, controllerKey.Kind, controllerKey.Name, err)
}
return owner, nil
}
func (c *ControllerKeyWithAPIVersion) groupKind() (schema.GroupKind, error) {
// TODO: cache response
groupVersion, err := schema.ParseGroupVersion(c.ApiVersion)
if err != nil {
return schema.GroupKind{}, err
}
groupKind := schema.GroupKind{
Group: groupVersion.Group,
Kind: c.ControllerKey.Kind,
}
return groupKind, nil
}
func (f *controllerFetcher) isWellKnown(key *ControllerKeyWithAPIVersion) bool {
kind := wellKnownController(key.ControllerKey.Kind)
_, exists := f.informersMap[kind]
return exists
}
func (f *controllerFetcher) getScaleForResource(namespace string, groupResource schema.GroupResource, name string) (controller *autoscalingapi.Scale, err error) {
if ok, scale, err := f.scaleSubresourceCacheStorage.Get(namespace, groupResource, name); ok {
return scale, err
}
scale, err := f.scaleNamespacer.Scales(namespace).Get(context.TODO(), groupResource, name, metav1.GetOptions{})
f.scaleSubresourceCacheStorage.Insert(namespace, groupResource, name, scale, err)
return scale, err
}
func (f *controllerFetcher) isWellKnownOrScalable(key *ControllerKeyWithAPIVersion) bool {
if f.isWellKnown(key) {
return true
}
if gk, err := key.groupKind(); err != nil && wellKnownController(gk.Kind) == node {
return false
}
//if not well known check if it supports scaling
groupKind, err := key.groupKind()
if err != nil {
klog.Errorf("Could not find groupKind for %s/%s: %v", key.Namespace, key.Name, err)
return false
}
mappings, err := f.mapper.RESTMappings(groupKind)
if err != nil {
klog.Errorf("Could not find mappings for %s: %v", groupKind, err)
return false
}
for _, mapping := range mappings {
groupResource := mapping.Resource.GroupResource()
scale, err := f.getScaleForResource(key.Namespace, groupResource, key.Name)
if err == nil && scale != nil {
return true
}
}
return false
}
func (f *controllerFetcher) getOwnerForScaleResource(groupKind schema.GroupKind, namespace, name string) (*ControllerKeyWithAPIVersion, error) {
if wellKnownController(groupKind.Kind) == node {
// Some pods specify nods as their owners. This causes performance problems
// in big clusters when VPA tries to get all nodes. We know nodes aren't
// valid controllers so we can skip trying to fetch them.
return nil, fmt.Errorf("node is not a valid owner")
}
mappings, err := f.mapper.RESTMappings(groupKind)
if err != nil {
return nil, err
}
var lastError error
for _, mapping := range mappings {
groupResource := mapping.Resource.GroupResource()
scale, err := f.getScaleForResource(namespace, groupResource, name)
if err == nil {
return getOwnerController(scale.OwnerReferences, namespace), nil
}
lastError = err
}
// nothing found, apparently the resource doesn't support scale (or we lack RBAC)
return nil, lastError
}
func (f *controllerFetcher) FindTopMostWellKnownOrScalable(key *ControllerKeyWithAPIVersion) (*ControllerKeyWithAPIVersion, error) {
if key == nil {
return nil, nil
}
var topMostWellKnownOrScalable *ControllerKeyWithAPIVersion
wellKnownOrScalable := f.isWellKnownOrScalable(key)
if wellKnownOrScalable {
topMostWellKnownOrScalable = key
}
visited := make(map[ControllerKeyWithAPIVersion]bool)
visited[*key] = true
for {
owner, err := f.getParentOfController(*key)
if err != nil {
return nil, err
}
if owner == nil {
return topMostWellKnownOrScalable, nil
}
wellKnownOrScalable = f.isWellKnownOrScalable(owner)
if wellKnownOrScalable {
topMostWellKnownOrScalable = owner
}
_, alreadyVisited := visited[*owner]
if alreadyVisited {
return nil, fmt.Errorf("Cycle detected in ownership chain")
}
visited[*key] = true
key = owner
}
}