-
Notifications
You must be signed in to change notification settings - Fork 472
/
reconciler.go
338 lines (283 loc) · 11.5 KB
/
reconciler.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
// Copyright (c) 2020 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
//
// 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 reference
import (
"context"
"fmt"
"sync/atomic"
gardencorev1beta1 "github.com/gardener/gardener/pkg/apis/core/v1beta1"
v1beta1constants "github.com/gardener/gardener/pkg/apis/core/v1beta1/constants"
"github.com/gardener/gardener/pkg/controllermanager/apis/config"
"github.com/gardener/gardener/pkg/controllerutils"
"github.com/gardener/gardener/pkg/utils"
"github.com/gardener/gardener/pkg/utils/flow"
kutil "github.com/gardener/gardener/pkg/utils/kubernetes"
"github.com/go-logr/logr"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/selection"
"k8s.io/apimachinery/pkg/util/sets"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
)
// FinalizerName is the name of the finalizer used for the reference protection.
const FinalizerName = "gardener.cloud/reference-protection"
// Reconciler checks the shoot in the given request for references to further objects in order to protect them from
// deletions as long as they are still referenced.
type Reconciler struct {
Client client.Client
Config config.ShootReferenceControllerConfiguration
}
// Reconcile checks the shoot in the given request for references to further objects in order to protect them from
// deletions as long as they are still referenced.
func (r *Reconciler) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) {
log := logf.FromContext(ctx)
shoot := &gardencorev1beta1.Shoot{}
if err := r.Client.Get(ctx, request.NamespacedName, shoot); err != nil {
if apierrors.IsNotFound(err) {
log.V(1).Info("Object is gone, stop reconciling")
return reconcile.Result{}, nil
}
return reconcile.Result{}, fmt.Errorf("error retrieving object from store: %w", err)
}
// Iterate over all user secrets in project namespace and check if they can be released.
if err := r.releaseUnreferencedSecrets(ctx, log, shoot); err != nil {
return reconcile.Result{}, err
}
// Iterate over all user configmaps in project namespace and check if they can be released.
if err := r.releaseUnreferencedConfigMaps(ctx, log, shoot); err != nil {
return reconcile.Result{}, err
}
// Remove finalizer from shoot in case it's being deleted and not handled by Gardener anymore.
if shoot.DeletionTimestamp != nil && !controllerutil.ContainsFinalizer(shoot, gardencorev1beta1.GardenerName) {
if controllerutil.ContainsFinalizer(shoot, FinalizerName) {
log.Info("Removing finalizer")
if err := controllerutils.RemoveFinalizers(ctx, r.Client, shoot, FinalizerName); err != nil {
return reconcile.Result{}, fmt.Errorf("failed to remove finalizer: %w", err)
}
}
return reconcile.Result{}, nil
}
// Add finalizer to referenced secrets that are not managed by Gardener.
addedFinalizerToSecret, err := r.handleReferencedSecrets(ctx, log, r.Client, shoot)
if err != nil {
return reconcile.Result{}, err
}
addedFinalizerToConfigMap, err := r.handleReferencedConfigMap(ctx, log, r.Client, shoot)
if err != nil {
return reconcile.Result{}, err
}
// Manage finalizers on shoot.
var (
hasFinalizer = controllerutil.ContainsFinalizer(shoot, FinalizerName)
needsFinalizer = addedFinalizerToSecret || addedFinalizerToConfigMap
)
if needsFinalizer && !hasFinalizer {
log.Info("Adding finalizer")
if err := controllerutils.AddFinalizers(ctx, r.Client, shoot, FinalizerName); err != nil {
return reconcile.Result{}, fmt.Errorf("failed to add finalizer: %w", err)
}
return reconcile.Result{}, nil
}
if !needsFinalizer && hasFinalizer {
log.Info("Removing finalizer")
if err := controllerutils.RemoveFinalizers(ctx, r.Client, shoot, FinalizerName); err != nil {
return reconcile.Result{}, fmt.Errorf("failed to remove finalizer: %w", err)
}
}
return reconcile.Result{}, nil
}
func (r *Reconciler) handleReferencedSecrets(ctx context.Context, log logr.Logger, c client.Client, shoot *gardencorev1beta1.Shoot) (bool, error) {
var (
fns []flow.TaskFn
added = uint32(0)
dnsSecretNames = secretNamesForDNSProviders(shoot)
)
for _, dnsSecretName := range dnsSecretNames {
name := dnsSecretName
fns = append(fns, func(ctx context.Context) error {
secret := &corev1.Secret{}
s := shoot
if err := c.Get(ctx, kutil.Key(s.Namespace, name), secret); err != nil {
return err
}
// Don't handle Gardener managed secrets.
if _, ok := secret.Labels[v1beta1constants.GardenRole]; ok {
return nil
}
atomic.StoreUint32(&added, 1)
if !controllerutil.ContainsFinalizer(secret, FinalizerName) {
log.Info("Adding finalizer to secret", "secret", client.ObjectKeyFromObject(secret))
if err := controllerutils.AddFinalizers(ctx, r.Client, secret, FinalizerName); err != nil {
return fmt.Errorf("failed to add finalizer to secret: %w", err)
}
}
return nil
})
}
err := flow.Parallel(fns...)(ctx)
return added != 0, err
}
func (r *Reconciler) handleReferencedConfigMap(ctx context.Context, log logr.Logger, c client.Client, shoot *gardencorev1beta1.Shoot) (bool, error) {
if configMapRef := getAuditPolicyConfigMapRef(shoot.Spec.Kubernetes.KubeAPIServer); configMapRef != nil {
configMap := &corev1.ConfigMap{}
if err := c.Get(ctx, kutil.Key(shoot.Namespace, configMapRef.Name), configMap); err != nil {
return false, err
}
if !controllerutil.ContainsFinalizer(configMap, FinalizerName) {
log.Info("Adding finalizer to ConfigMap", "configMap", client.ObjectKeyFromObject(configMap))
if err := controllerutils.AddFinalizers(ctx, r.Client, configMap, FinalizerName); err != nil {
return true, fmt.Errorf("failed to add finalizer to ConfigMap: %w", err)
}
}
return true, nil
}
return false, nil
}
func (r *Reconciler) releaseUnreferencedSecrets(ctx context.Context, log logr.Logger, shoot *gardencorev1beta1.Shoot) error {
secrets, err := r.getUnreferencedSecrets(ctx, shoot)
if err != nil {
return err
}
var fns []flow.TaskFn
for _, secret := range secrets {
s := secret
fns = append(fns, func(ctx context.Context) error {
if controllerutil.ContainsFinalizer(&s, FinalizerName) {
log.Info("Removing finalizer from secret", "secret", client.ObjectKeyFromObject(&s))
if err := controllerutils.RemoveFinalizers(ctx, r.Client, &s, FinalizerName); err != nil {
return fmt.Errorf("failed to remove finalizer from secret: %w", err)
}
}
return nil
})
}
return flow.Parallel(fns...)(ctx)
}
func (r *Reconciler) releaseUnreferencedConfigMaps(ctx context.Context, log logr.Logger, shoot *gardencorev1beta1.Shoot) error {
configMaps, err := r.getUnreferencedConfigMaps(ctx, shoot)
if err != nil {
return err
}
var fns []flow.TaskFn
for _, configMap := range configMaps {
cm := configMap
fns = append(fns, func(ctx context.Context) error {
if controllerutil.ContainsFinalizer(&cm, FinalizerName) {
log.Info("Removing finalizer from ConfigMap", "configMap", client.ObjectKeyFromObject(&cm))
if err := controllerutils.RemoveFinalizers(ctx, r.Client, &cm, FinalizerName); err != nil {
return fmt.Errorf("failed to remove finalizer from ConfigMap: %w", err)
}
}
return nil
})
}
return flow.Parallel(fns...)(ctx)
}
var (
noGardenRole = utils.MustNewRequirement(v1beta1constants.GardenRole, selection.DoesNotExist)
// UserManagedSelector is a selector for objects which are managed by users and not created by Gardener.
UserManagedSelector = client.MatchingLabelsSelector{Selector: labels.NewSelector().Add(noGardenRole)}
)
func (r *Reconciler) getUnreferencedSecrets(ctx context.Context, shoot *gardencorev1beta1.Shoot) ([]corev1.Secret, error) {
namespace := shoot.Namespace
secrets := &corev1.SecretList{}
if err := r.Client.List(ctx, secrets, client.InNamespace(namespace), UserManagedSelector); err != nil {
return nil, err
}
shoots := &gardencorev1beta1.ShootList{}
if err := r.Client.List(ctx, shoots, client.InNamespace(namespace)); err != nil {
return nil, err
}
referencedSecrets := sets.NewString()
for _, s := range shoots.Items {
// Ignore own references if shoot is in deletion and references are not needed any more by Gardener.
if s.Name == shoot.Name && shoot.DeletionTimestamp != nil && !controllerutil.ContainsFinalizer(&s, gardencorev1beta1.GardenerName) {
continue
}
referencedSecrets.Insert(secretNamesForDNSProviders(&s)...)
}
var secretsToRelease []corev1.Secret
for _, secret := range secrets.Items {
if !controllerutil.ContainsFinalizer(&secret, FinalizerName) {
continue
}
if referencedSecrets.Has(secret.Name) {
continue
}
secretsToRelease = append(secretsToRelease, secret)
}
return secretsToRelease, nil
}
func (r *Reconciler) getUnreferencedConfigMaps(ctx context.Context, shoot *gardencorev1beta1.Shoot) ([]corev1.ConfigMap, error) {
namespace := shoot.Namespace
configMaps := &corev1.ConfigMapList{}
if err := r.Client.List(ctx, configMaps, client.InNamespace(namespace)); err != nil {
return nil, err
}
// Exit early if there are no ConfigMaps at all in the namespace
if len(configMaps.Items) == 0 {
return nil, nil
}
shoots := &gardencorev1beta1.ShootList{}
if err := r.Client.List(ctx, shoots, client.InNamespace(namespace)); err != nil {
return nil, err
}
referencedConfigMaps := sets.NewString()
for _, s := range shoots.Items {
// Ignore own references if shoot is in deletion and references are not needed any more by Gardener.
if s.Name == shoot.Name && shoot.DeletionTimestamp != nil && !controllerutil.ContainsFinalizer(&s, gardencorev1beta1.GardenerName) {
continue
}
if configMapRef := getAuditPolicyConfigMapRef(s.Spec.Kubernetes.KubeAPIServer); configMapRef != nil {
referencedConfigMaps.Insert(configMapRef.Name)
}
}
var configMapsToRelease []corev1.ConfigMap
for _, configMap := range configMaps.Items {
if !controllerutil.ContainsFinalizer(&configMap, FinalizerName) {
continue
}
if referencedConfigMaps.Has(configMap.Name) {
continue
}
configMapsToRelease = append(configMapsToRelease, configMap)
}
return configMapsToRelease, nil
}
func secretNamesForDNSProviders(shoot *gardencorev1beta1.Shoot) []string {
if shoot.Spec.DNS == nil {
return nil
}
var names = make([]string, 0, len(shoot.Spec.DNS.Providers))
for _, provider := range shoot.Spec.DNS.Providers {
if provider.SecretName == nil {
continue
}
names = append(names, *provider.SecretName)
}
return names
}
func getAuditPolicyConfigMapRef(apiServerConfig *gardencorev1beta1.KubeAPIServerConfig) *corev1.ObjectReference {
if apiServerConfig != nil &&
apiServerConfig.AuditConfig != nil &&
apiServerConfig.AuditConfig.AuditPolicy != nil &&
apiServerConfig.AuditConfig.AuditPolicy.ConfigMapRef != nil {
return apiServerConfig.AuditConfig.AuditPolicy.ConfigMapRef
}
return nil
}