-
Notifications
You must be signed in to change notification settings - Fork 459
/
reconciler.go
181 lines (151 loc) · 7.93 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
// Copyright (c) 2019 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 health
import (
"context"
"fmt"
"time"
gardencorev1beta1 "github.com/gardener/gardener/pkg/apis/core/v1beta1"
v1beta1helper "github.com/gardener/gardener/pkg/apis/core/v1beta1/helper"
resourcesv1alpha1 "github.com/gardener/gardener/pkg/apis/resources/v1alpha1"
"github.com/gardener/gardener/pkg/resourcemanager/predicate"
"github.com/go-logr/logr"
apiequality "k8s.io/apimachinery/pkg/api/equality"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
)
type reconciler struct {
log logr.Logger
client client.Client
targetClient client.Client
targetScheme *runtime.Scheme
classFilter *predicate.ClassFilter
syncPeriod time.Duration
}
// InjectClient injects a client into the reconciler.
func (r *reconciler) InjectClient(c client.Client) error {
r.client = c
return nil
}
// InjectLogger injects a logger into the reconciler.
func (r *reconciler) InjectLogger(l logr.Logger) error {
r.log = l.WithName(ControllerName)
return nil
}
// Reconcile performs health checks.
func (r *reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
log := r.log.WithValues("object", req)
log.Info("Starting ManagedResource health checks")
mr := &resourcesv1alpha1.ManagedResource{}
if err := r.client.Get(ctx, req.NamespacedName, mr); err != nil {
if apierrors.IsNotFound(err) {
log.Info("Stopping health checks for ManagedResource, as it has been deleted")
return reconcile.Result{}, nil
}
return reconcile.Result{}, fmt.Errorf("could not fetch ManagedResource: %+v", err)
}
// Check responsibility
if _, responsible := r.classFilter.Active(mr); !responsible {
log.Info("Stopping health checks as the responsibility changed")
return ctrl.Result{}, nil // Do not requeue
}
healthCheckCtx, cancel := context.WithTimeout(ctx, time.Minute)
defer cancel()
// Initialize condition based on the current status.
conditionResourcesHealthy := v1beta1helper.GetOrInitCondition(mr.Status.Conditions, resourcesv1alpha1.ResourcesHealthy)
if !mr.DeletionTimestamp.IsZero() {
conditionResourcesHealthy = v1beta1helper.UpdatedCondition(conditionResourcesHealthy, gardencorev1beta1.ConditionFalse, resourcesv1alpha1.ConditionDeletionPending, "The resources are currently being deleted.")
if err := updateConditions(ctx, r.client, mr, conditionResourcesHealthy); err != nil {
return ctrl.Result{}, fmt.Errorf("could not update the ManagedResource status: %w", err)
}
log.Info("Stopping health checks for ManagedResource, as it has been deleted (deletionTimestamp is set)")
return reconcile.Result{}, nil
}
// skip health checks until ManagedResource has been reconciled completely successfully to prevent writing
// falsy health condition (resources may need a second try to apply, e.g. CRDs and CRs in the same MR)
conditionResourcesApplied := v1beta1helper.GetCondition(mr.Status.Conditions, resourcesv1alpha1.ResourcesApplied)
if conditionResourcesApplied == nil || conditionResourcesApplied.Status == gardencorev1beta1.ConditionProgressing || conditionResourcesApplied.Status == gardencorev1beta1.ConditionFalse {
log.Info("Skipping health checks for ManagedResource, as it is has not been reconciled successfully yet.")
return ctrl.Result{RequeueAfter: r.syncPeriod}, nil
}
var (
oldConditions = []gardencorev1beta1.Condition{conditionResourcesHealthy}
resourcesObjectReferences = mr.Status.Resources
)
for _, ref := range resourcesObjectReferences {
var obj client.Object
// sigs.k8s.io/controller-runtime/pkg/client.DelegatingReader does not use the cache for unstructured.Unstructured
// objects, so we create a new object of the object's type to use the caching client
runtimeObject, err := r.targetScheme.New(ref.GroupVersionKind())
if err != nil {
log.Info("Could not create new object of kind for health checks (probably not registered in the used scheme), falling back to unstructured request",
"GroupVersionKind", ref.GroupVersionKind().String(), "error", err.Error())
// fallback to unstructured requests if the object's type is not registered in the scheme
unstructuredObj := &unstructured.Unstructured{}
unstructuredObj.SetAPIVersion(ref.APIVersion)
unstructuredObj.SetKind(ref.Kind)
obj = unstructuredObj
} else {
var ok bool
if obj, ok = runtimeObject.(client.Object); !ok {
err := fmt.Errorf("expected client.Object but got %T", obj)
log.Error(err, "Could not execute health check", "GroupVersionKind", ref.GroupVersionKind().String())
// do not requeue because there anyway will be another update event to fix the problem
return ctrl.Result{}, nil
}
}
if err := r.targetClient.Get(healthCheckCtx, client.ObjectKey{Namespace: ref.Namespace, Name: ref.Name}, obj); err != nil {
if apierrors.IsNotFound(err) {
log.Info("Could not get object", "namespace", ref.Namespace, "name", ref.Name)
var (
reason = ref.Kind + "Missing"
message = fmt.Sprintf("Required %s %q in namespace %q is missing.", ref.Kind, ref.Name, ref.Namespace)
)
conditionResourcesHealthy = v1beta1helper.UpdatedCondition(conditionResourcesHealthy, gardencorev1beta1.ConditionFalse, reason, message)
if err := updateConditions(ctx, r.client, mr, conditionResourcesHealthy); err != nil {
return ctrl.Result{}, fmt.Errorf("could not update the ManagedResource status: %w", err)
}
return ctrl.Result{RequeueAfter: r.syncPeriod}, nil // We do not want to run in the exponential backoff for the condition check.
}
return ctrl.Result{}, err
}
if err := CheckHealth(healthCheckCtx, r.targetClient, r.targetScheme, obj); err != nil {
var (
reason = ref.Kind + "Unhealthy"
message = fmt.Sprintf("Required %s %q in namespace %q is unhealthy: %v", ref.Kind, ref.Name, ref.Namespace, err.Error())
)
conditionResourcesHealthy = v1beta1helper.UpdatedCondition(conditionResourcesHealthy, gardencorev1beta1.ConditionFalse, reason, message)
if err := updateConditions(ctx, r.client, mr, conditionResourcesHealthy); err != nil {
return ctrl.Result{}, fmt.Errorf("could not update the ManagedResource status: %w", err)
}
return ctrl.Result{RequeueAfter: r.syncPeriod}, nil // We do not want to run in the exponential backoff for the condition check.
}
}
conditionResourcesHealthy = v1beta1helper.UpdatedCondition(conditionResourcesHealthy, gardencorev1beta1.ConditionTrue, "ResourcesHealthy", "All resources are healthy.")
if !apiequality.Semantic.DeepEqual(oldConditions, []gardencorev1beta1.Condition{conditionResourcesHealthy}) {
if err := updateConditions(ctx, r.client, mr, conditionResourcesHealthy); err != nil {
return ctrl.Result{}, fmt.Errorf("could not update the ManagedResource status: %w", err)
}
}
log.Info("Finished ManagedResource health checks")
return ctrl.Result{RequeueAfter: r.syncPeriod}, nil
}
func updateConditions(ctx context.Context, c client.Client, mr *resourcesv1alpha1.ManagedResource, condition gardencorev1beta1.Condition) error {
mr.Status.Conditions = v1beta1helper.MergeConditions(mr.Status.Conditions, condition)
return c.Status().Update(ctx, mr)
}