-
Notifications
You must be signed in to change notification settings - Fork 207
/
machinehealthcheck_controller.go
363 lines (321 loc) · 11.9 KB
/
machinehealthcheck_controller.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
package machinehealthcheck
import (
"context"
golangerrors "errors"
"time"
"github.com/golang/glog"
mapiv1 "github.com/openshift/cluster-api/pkg/apis/machine/v1beta1"
healthcheckingv1alpha1 "github.com/openshift/machine-api-operator/pkg/apis/healthchecking/v1alpha1"
"github.com/openshift/machine-api-operator/pkg/util"
"github.com/openshift/machine-api-operator/pkg/util/conditions"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/tools/cache"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/controller-runtime/pkg/source"
)
const (
machineAnnotationKey = "machine.openshift.io/machine"
ownerControllerKind = "MachineSet"
)
// Add creates a new MachineHealthCheck Controller and adds it to the Manager. The Manager will set fields on the Controller
// and start it when the Manager is started.
func Add(mgr manager.Manager) error {
r, err := newReconciler(mgr)
if err != nil {
return err
}
return add(mgr, r)
}
// newReconciler returns a new reconcile.Reconciler
func newReconciler(mgr manager.Manager) (reconcile.Reconciler, error) {
r := &ReconcileMachineHealthCheck{
client: mgr.GetClient(),
scheme: mgr.GetScheme(),
}
ns, err := util.GetNamespace(util.ServiceAccountNamespaceFile)
if err != nil {
return r, err
}
r.namespace = ns
return r, nil
}
// add adds a new Controller to mgr with r as the reconcile.Reconciler
func add(mgr manager.Manager, r reconcile.Reconciler) error {
// Create a new controller
c, err := controller.New("machinehealthcheck-controller", mgr, controller.Options{Reconciler: r})
if err != nil {
return err
}
return c.Watch(&source.Kind{Type: &corev1.Node{}}, &handler.EnqueueRequestForObject{})
}
var _ reconcile.Reconciler = &ReconcileMachineHealthCheck{}
// ReconcileMachineHealthCheck reconciles a MachineHealthCheck object
type ReconcileMachineHealthCheck struct {
// This client, initialized using mgr.Client() above, is a split client
// that reads objects from the cache and writes to the apiserver
client client.Client
scheme *runtime.Scheme
namespace string
}
// Reconcile reads that state of the cluster for MachineHealthCheck, machine and nodes objects and makes changes based on the state read
// and what is in the MachineHealthCheck.Spec
// Note:
// The Controller will requeue the Request to be processed again if the returned error is non-nil or
// Result.Requeue is true, otherwise upon completion it will remove the work from the queue.
func (r *ReconcileMachineHealthCheck) Reconcile(request reconcile.Request) (reconcile.Result, error) {
glog.Infof("Reconciling MachineHealthCheck triggered by %s/%s\n", request.Namespace, request.Name)
// Get node from request
node := &corev1.Node{}
err := r.client.Get(context.TODO(), request.NamespacedName, node)
glog.V(4).Infof("Reconciling, getting node %v", node.Name)
if err != nil {
if errors.IsNotFound(err) {
// Request object not found, could have been deleted after reconcile request.
// Owned objects are automatically garbage collected. For additional cleanup logic use finalizers.
// Return and don't requeue
return reconcile.Result{}, nil
}
// Error reading the object - requeue the request.
return reconcile.Result{}, err
}
machineKey, ok := node.Annotations[machineAnnotationKey]
if !ok {
glog.Warningf("No machine annotation for node %s", node.Name)
return reconcile.Result{}, nil
}
glog.Infof("Node %s is annotated with machine %s", node.Name, machineKey)
machine := &mapiv1.Machine{}
namespace, machineName, err := cache.SplitMetaNamespaceKey(machineKey)
if err != nil {
return reconcile.Result{}, err
}
key := &types.NamespacedName{
Namespace: namespace,
Name: machineName,
}
err = r.client.Get(context.TODO(), *key, machine)
if err != nil {
if errors.IsNotFound(err) {
glog.Warningf("machine %s not found", machineKey)
// Request object not found, could have been deleted after reconcile request.
// Owned objects are automatically garbage collected. For additional cleanup logic use finalizers.
// Return and don't requeue
return reconcile.Result{}, nil
}
// Error reading the object - requeue the request.
glog.Errorf("error getting machine %s. Error: %v. Requeuing...", machineKey, err)
return reconcile.Result{}, err
}
// If the current machine matches any existing MachineHealthCheck CRD
allMachineHealthChecks := &healthcheckingv1alpha1.MachineHealthCheckList{}
err = r.client.List(context.Background(), getMachineHealthCheckListOptions(), allMachineHealthChecks)
if err != nil {
glog.Errorf("failed to list MachineHealthChecks, %v", err)
return reconcile.Result{}, err
}
for _, hc := range allMachineHealthChecks.Items {
if hasMatchingLabels(&hc, machine) {
glog.V(4).Infof("Machine %s has a matching machineHealthCheck: %s", machineKey, hc.Name)
return remediate(r, machine)
}
}
glog.Infof("Machine %s has no MachineHealthCheck associated", machineName)
return reconcile.Result{}, nil
}
// This is set so the fake client can be used for unit test. See:
// https://github.com/kubernetes-sigs/controller-runtime/issues/168
func getMachineHealthCheckListOptions() *client.ListOptions {
return &client.ListOptions{
Raw: &metav1.ListOptions{
TypeMeta: metav1.TypeMeta{
APIVersion: "healthchecking.openshift.io/v1alpha1",
Kind: "MachineHealthCheck",
},
},
}
}
func remediate(r *ReconcileMachineHealthCheck, machine *mapiv1.Machine) (reconcile.Result, error) {
glog.Infof("Initialising remediation logic for machine %s", machine.Name)
if isMaster(*machine, r.client) {
glog.Infof("The machine %s is a master node, skipping remediation", machine.Name)
return reconcile.Result{}, nil
}
if !hasMachineSetOwner(*machine) {
glog.Infof("Machine %s has no machineSet controller owner, skipping remediation", machine.Name)
return reconcile.Result{}, nil
}
node, err := getNodeFromMachine(*machine, r.client)
if err != nil {
if errors.IsNotFound(err) {
glog.Warningf("Node %s not found for machine %s", node.Name, machine.Name)
return reconcile.Result{}, nil
}
// Error reading the object - requeue the request.
return reconcile.Result{}, err
}
cmUnhealtyConditions, err := getUnhealthyConditionsConfigMap(r)
if err != nil {
return reconcile.Result{}, err
}
nodeUnhealthyConditions, err := conditions.GetNodeUnhealthyConditions(node, cmUnhealtyConditions)
if err != nil {
return reconcile.Result{}, err
}
var result *reconcile.Result
var minimalConditionTimeout time.Duration
minimalConditionTimeout = 0
for _, c := range nodeUnhealthyConditions {
nodeCondition := conditions.GetNodeCondition(node, c.Name)
// skip when current node condition is different from the one reported in the config map
if nodeCondition == nil || !isConditionsStatusesEqual(nodeCondition, &c) {
continue
}
conditionTimeout, err := time.ParseDuration(c.Timeout)
if err != nil {
return reconcile.Result{}, err
}
// apply remediation logic, if at least one condition last more than specified timeout
if unhealthyForTooLong(nodeCondition, conditionTimeout) {
glog.Infof("machine %s has been unhealthy for too long, deleting", machine.Name)
if err := r.client.Delete(context.TODO(), machine); err != nil {
glog.Errorf("failed to delete machine %s, requeuing referenced node", machine.Name)
return reconcile.Result{}, err
}
return reconcile.Result{}, nil
}
now := time.Now()
durationUnhealthy := now.Sub(nodeCondition.LastTransitionTime.Time)
glog.Warningf(
"Machine %s has unhealthy node %s with the condition %s and the timeout %s for %s. Requeuing...",
machine.Name,
node.Name,
nodeCondition.Type,
c.Timeout,
durationUnhealthy.String(),
)
// be sure that we will use timeout with the minimal value for the reconcile.Result
if minimalConditionTimeout == 0 || minimalConditionTimeout > conditionTimeout {
minimalConditionTimeout = conditionTimeout
}
result = &reconcile.Result{Requeue: true, RequeueAfter: minimalConditionTimeout}
}
// requeue
if result != nil {
return *result, nil
}
glog.Infof("No remediaton action was taken. Machine %s with node %v is healthy", machine.Name, node.Name)
return reconcile.Result{}, nil
}
func getUnhealthyConditionsConfigMap(r *ReconcileMachineHealthCheck) (*corev1.ConfigMap, error) {
cmUnhealtyConditions := &corev1.ConfigMap{}
cmKey := types.NamespacedName{
Name: healthcheckingv1alpha1.ConfigMapNodeUnhealthyConditions,
Namespace: r.namespace,
}
err := r.client.Get(context.TODO(), cmKey, cmUnhealtyConditions)
if err != nil {
// Error reading the object - requeue the request
if !errors.IsNotFound(err) {
return nil, err
}
// creates dummy config map with default values if it does not exist
cmUnhealtyConditions, err = conditions.CreateDummyUnhealthyConditionsConfigMap()
if err != nil {
return nil, err
}
glog.Infof(
"ConfigMap %s not found under the namespace %s, fallback to default values: %s",
healthcheckingv1alpha1.ConfigMapNodeUnhealthyConditions,
r.namespace,
cmUnhealtyConditions.Data["conditions"],
)
}
return cmUnhealtyConditions, nil
}
func isConditionsStatusesEqual(cond *corev1.NodeCondition, unhealthyCond *conditions.UnhealthyCondition) bool {
return cond.Status == unhealthyCond.Status
}
func getNodeFromMachine(machine mapiv1.Machine, client client.Client) (*corev1.Node, error) {
if machine.Status.NodeRef == nil {
glog.Errorf("node NodeRef not found in machine %s", machine.Name)
return nil, golangerrors.New("node NodeRef not found in machine")
}
node := &corev1.Node{}
nodeKey := types.NamespacedName{
Namespace: machine.Status.NodeRef.Namespace,
Name: machine.Status.NodeRef.Name,
}
err := client.Get(context.TODO(), nodeKey, node)
return node, err
}
func unhealthyForTooLong(nodeCondition *corev1.NodeCondition, timeout time.Duration) bool {
now := time.Now()
if nodeCondition.LastTransitionTime.Add(timeout).Before(now) {
return true
}
return false
}
func hasMachineSetOwner(machine mapiv1.Machine) bool {
ownerRefs := machine.ObjectMeta.GetOwnerReferences()
for _, or := range ownerRefs {
if or.Kind == ownerControllerKind {
return true
}
}
return false
}
func hasMatchingLabels(machineHealthCheck *healthcheckingv1alpha1.MachineHealthCheck, machine *mapiv1.Machine) bool {
selector, err := metav1.LabelSelectorAsSelector(&machineHealthCheck.Spec.Selector)
if err != nil {
glog.Warningf("unable to convert selector: %v", err)
return false
}
// If a deployment with a nil or empty selector creeps in, it should match nothing, not everything.
if selector.Empty() {
glog.V(2).Infof("%v machineHealthCheck has empty selector", machineHealthCheck.Name)
return false
}
if !selector.Matches(labels.Set(machine.Labels)) {
glog.V(4).Infof("%v machine has mismatched labels", machine.Name)
return false
}
return true
}
func isMaster(machine mapiv1.Machine, client client.Client) bool {
machineMasterLabels := []string{
"machine.openshift.io/cluster-api-machine-role",
"machine.openshift.io/cluster-api-machine-type",
"sigs.k8s.io/cluster-api-machine-role",
"sigs.k8s.io/cluster-api-machine-type",
}
nodeMasterLabels := []string{
"node-role.kubernetes.io/master",
}
machineLabels := labels.Set(machine.Labels)
for _, masterLabel := range machineMasterLabels {
if machineLabels.Get(masterLabel) == "master" {
return true
}
}
node, err := getNodeFromMachine(machine, client)
if err != nil {
glog.Warningf("Couldn't get node for machine %s", machine.Name)
return false
}
nodeLabels := labels.Set(node.Labels)
for _, masterLabel := range nodeMasterLabels {
if nodeLabels.Has(masterLabel) {
return true
}
}
return false
}