/
health.go
416 lines (356 loc) · 15.5 KB
/
health.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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
// Copyright (c) 2018 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 (
"fmt"
"net/http"
"time"
gardencorev1alpha1 "github.com/gardener/gardener/pkg/apis/core/v1alpha1"
v1alpha1constants "github.com/gardener/gardener/pkg/apis/core/v1alpha1/constants"
"github.com/gardener/gardener/pkg/apis/core/v1alpha1/helper"
extensionsv1alpha1 "github.com/gardener/gardener/pkg/apis/extensions/v1alpha1"
machinev1alpha1 "github.com/gardener/machine-controller-manager/pkg/apis/machine/v1alpha1"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
apiequality "k8s.io/apimachinery/pkg/api/equality"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/client-go/rest"
)
func requiredConditionMissing(conditionType string) error {
return fmt.Errorf("condition %q is missing", conditionType)
}
func checkConditionState(conditionType string, expected, actual, reason, message string) error {
if expected != actual {
return fmt.Errorf("condition %q has invalid status %s (expected %s) due to %s: %s",
conditionType, actual, expected, reason, message)
}
return nil
}
func getDeploymentCondition(conditions []appsv1.DeploymentCondition, conditionType appsv1.DeploymentConditionType) *appsv1.DeploymentCondition {
for _, condition := range conditions {
if condition.Type == conditionType {
return &condition
}
}
return nil
}
func getMachineDeploymentCondition(conditions []machinev1alpha1.MachineDeploymentCondition, conditionType machinev1alpha1.MachineDeploymentConditionType) *machinev1alpha1.MachineDeploymentCondition {
for _, condition := range conditions {
if condition.Type == conditionType {
return &condition
}
}
return nil
}
func getNodeCondition(conditions []corev1.NodeCondition, conditionType corev1.NodeConditionType) *corev1.NodeCondition {
for _, condition := range conditions {
if condition.Type == conditionType {
return &condition
}
}
return nil
}
var (
trueDeploymentConditionTypes = []appsv1.DeploymentConditionType{
appsv1.DeploymentAvailable,
}
trueOptionalDeploymentConditionTypes = []appsv1.DeploymentConditionType{
appsv1.DeploymentProgressing,
}
falseOptionalDeploymentConditionTypes = []appsv1.DeploymentConditionType{
appsv1.DeploymentReplicaFailure,
}
)
// CheckDeployment checks whether the given Deployment is healthy.
// A deployment is considered healthy if the controller observed its current revision and
// if the number of updated replicas is equal to the number of replicas.
func CheckDeployment(deployment *appsv1.Deployment) error {
if deployment.Status.ObservedGeneration < deployment.Generation {
return fmt.Errorf("observed generation outdated (%d/%d)", deployment.Status.ObservedGeneration, deployment.Generation)
}
for _, trueConditionType := range trueDeploymentConditionTypes {
conditionType := string(trueConditionType)
condition := getDeploymentCondition(deployment.Status.Conditions, trueConditionType)
if condition == nil {
return requiredConditionMissing(conditionType)
}
if err := checkConditionState(conditionType, string(corev1.ConditionTrue), string(condition.Status), condition.Reason, condition.Message); err != nil {
return err
}
}
for _, trueOptionalConditionType := range trueOptionalDeploymentConditionTypes {
conditionType := string(trueOptionalConditionType)
condition := getDeploymentCondition(deployment.Status.Conditions, trueOptionalConditionType)
if condition == nil {
continue
}
if err := checkConditionState(conditionType, string(corev1.ConditionTrue), string(condition.Status), condition.Reason, condition.Message); err != nil {
return err
}
}
for _, falseOptionalConditionType := range falseOptionalDeploymentConditionTypes {
conditionType := string(falseOptionalConditionType)
condition := getDeploymentCondition(deployment.Status.Conditions, falseOptionalConditionType)
if condition == nil {
continue
}
if err := checkConditionState(conditionType, string(corev1.ConditionFalse), string(condition.Status), condition.Reason, condition.Message); err != nil {
return err
}
}
return nil
}
// CheckStatefulSet checks whether the given StatefulSet is healthy.
// A StatefulSet is considered healthy if its controller observed its current revision,
// it is not in an update (i.e. UpdateRevision is empty) and if its current replicas are equal to
// its desired replicas.
func CheckStatefulSet(statefulSet *appsv1.StatefulSet) error {
if statefulSet.Status.ObservedGeneration < statefulSet.Generation {
return fmt.Errorf("observed generation outdated (%d/%d)", statefulSet.Status.ObservedGeneration, statefulSet.Generation)
}
replicas := int32(1)
if statefulSet.Spec.Replicas != nil {
replicas = *statefulSet.Spec.Replicas
}
if statefulSet.Status.ReadyReplicas < replicas {
return fmt.Errorf("not enough ready replicas (%d/%d)", statefulSet.Status.ReadyReplicas, replicas)
}
return nil
}
func daemonSetMaxUnavailable(daemonSet *appsv1.DaemonSet) int32 {
if daemonSet.Status.DesiredNumberScheduled == 0 || daemonSet.Spec.UpdateStrategy.Type != appsv1.RollingUpdateDaemonSetStrategyType {
return 0
}
rollingUpdate := daemonSet.Spec.UpdateStrategy.RollingUpdate
if rollingUpdate == nil {
return 0
}
maxUnavailable, err := intstr.GetValueFromIntOrPercent(rollingUpdate.MaxUnavailable, int(daemonSet.Status.DesiredNumberScheduled), false)
if err != nil {
return 0
}
return int32(maxUnavailable)
}
// CheckDaemonSet checks whether the given DaemonSet is healthy.
// A DaemonSet is considered healthy if its controller observed its current revision and if
// its desired number of scheduled pods is equal to its updated number of scheduled pods.
func CheckDaemonSet(daemonSet *appsv1.DaemonSet) error {
if daemonSet.Status.ObservedGeneration < daemonSet.Generation {
return fmt.Errorf("observed generation outdated (%d/%d)", daemonSet.Status.ObservedGeneration, daemonSet.Generation)
}
maxUnavailable := daemonSetMaxUnavailable(daemonSet)
if requiredAvailable := daemonSet.Status.DesiredNumberScheduled - maxUnavailable; daemonSet.Status.CurrentNumberScheduled < requiredAvailable {
return fmt.Errorf("not enough available replicas (%d/%d)", daemonSet.Status.CurrentNumberScheduled, requiredAvailable)
}
return nil
}
var (
trueNodeConditionTypes = []corev1.NodeConditionType{
corev1.NodeReady,
}
falseNodeConditionTypes = []corev1.NodeConditionType{
corev1.NodeDiskPressure,
corev1.NodeMemoryPressure,
corev1.NodeNetworkUnavailable,
corev1.NodeOutOfDisk,
corev1.NodePIDPressure,
}
)
// CheckNode checks whether the given Node is healthy.
// A node is considered healthy if it has a `corev1.NodeReady` condition and this condition reports
// `corev1.ConditionTrue`.
func CheckNode(node *corev1.Node) error {
for _, trueConditionType := range trueNodeConditionTypes {
conditionType := string(trueConditionType)
condition := getNodeCondition(node.Status.Conditions, trueConditionType)
if condition == nil {
return requiredConditionMissing(conditionType)
}
if err := checkConditionState(conditionType, string(corev1.ConditionTrue), string(condition.Status), condition.Reason, condition.Message); err != nil {
return err
}
}
for _, falseConditionType := range falseNodeConditionTypes {
conditionType := string(falseConditionType)
condition := getNodeCondition(node.Status.Conditions, falseConditionType)
if condition == nil {
continue
}
if err := checkConditionState(conditionType, string(corev1.ConditionFalse), string(condition.Status), condition.Reason, condition.Message); err != nil {
return err
}
}
return nil
}
var (
trueMachineDeploymentConditionTypes = []machinev1alpha1.MachineDeploymentConditionType{
machinev1alpha1.MachineDeploymentAvailable,
}
trueOptionalMachineDeploymentConditionTypes = []machinev1alpha1.MachineDeploymentConditionType{
machinev1alpha1.MachineDeploymentProgressing,
}
falseMachineDeploymentConditionTypes = []machinev1alpha1.MachineDeploymentConditionType{
machinev1alpha1.MachineDeploymentReplicaFailure,
machinev1alpha1.MachineDeploymentFrozen,
}
)
// CheckMachineDeployment checks whether the given MachineDeployment is healthy.
// A MachineDeployment is considered healthy if its controller observed its current revision and if
// its desired number of replicas is equal to its updated replicas.
func CheckMachineDeployment(deployment *machinev1alpha1.MachineDeployment) error {
if deployment.Status.ObservedGeneration < deployment.Generation {
return fmt.Errorf("observed generation outdated (%d/%d)", deployment.Status.ObservedGeneration, deployment.Generation)
}
for _, trueConditionType := range trueMachineDeploymentConditionTypes {
conditionType := string(trueConditionType)
condition := getMachineDeploymentCondition(deployment.Status.Conditions, trueConditionType)
if condition == nil {
return requiredConditionMissing(conditionType)
}
if err := checkConditionState(conditionType, string(corev1.ConditionTrue), string(condition.Status), condition.Reason, condition.Message); err != nil {
return err
}
}
for _, trueOptionalConditionType := range trueOptionalMachineDeploymentConditionTypes {
conditionType := string(trueOptionalConditionType)
condition := getMachineDeploymentCondition(deployment.Status.Conditions, trueOptionalConditionType)
if condition == nil {
continue
}
if err := checkConditionState(conditionType, string(corev1.ConditionTrue), string(condition.Status), condition.Reason, condition.Message); err != nil {
return err
}
}
for _, falseConditionType := range falseMachineDeploymentConditionTypes {
conditionType := string(falseConditionType)
condition := getMachineDeploymentCondition(deployment.Status.Conditions, falseConditionType)
if condition == nil {
continue
}
if err := checkConditionState(conditionType, string(corev1.ConditionFalse), string(condition.Status), condition.Reason, condition.Message); err != nil {
return err
}
}
return nil
}
var (
trueSeedConditionTypes = []gardencorev1alpha1.ConditionType{
gardencorev1alpha1.SeedGardenletReady,
gardencorev1alpha1.SeedBootstrapped,
}
)
// CheckSeed checks if the Seed is up-to-date and if its extensions have been successfully bootstrapped.
func CheckSeed(seed *gardencorev1alpha1.Seed, identity *gardencorev1alpha1.Gardener) error {
if seed.Status.ObservedGeneration < seed.Generation {
return fmt.Errorf("observed generation outdated (%d/%d)", seed.Status.ObservedGeneration, seed.Generation)
}
if !apiequality.Semantic.DeepEqual(seed.Status.Gardener, identity) {
return fmt.Errorf("observing Gardener version not up to date (%v/%v)", seed.Status.Gardener, identity)
}
for _, trueConditionType := range trueSeedConditionTypes {
conditionType := string(trueConditionType)
condition := helper.GetCondition(seed.Status.Conditions, trueConditionType)
if condition == nil {
return requiredConditionMissing(conditionType)
}
if err := checkConditionState(conditionType, string(gardencorev1alpha1.ConditionTrue), string(condition.Status), condition.Reason, condition.Message); err != nil {
return err
}
}
return nil
}
// CheckExtensionObject checks if an extension Object is healthy or not.
// An extension object is healthy if
// * Its observed generation is up-to-date
// * No gardener.cloud/operation is set
// * No lastError is in the status
// * A last operation is state succeeded is present
func CheckExtensionObject(obj extensionsv1alpha1.Object) error {
status := obj.GetExtensionStatus()
if status.GetObservedGeneration() != obj.GetGeneration() {
return fmt.Errorf("observed generation outdated (%d/%d)", status.GetObservedGeneration(), obj.GetGeneration())
}
op, ok := obj.GetAnnotations()[v1alpha1constants.GardenerOperation]
if ok {
return fmt.Errorf("gardener operation %q is not yet picked up by extension controller", op)
}
if lastErr := status.GetLastError(); lastErr != nil {
return fmt.Errorf("extension encountered error during reconciliation: %s", lastErr.GetDescription())
}
lastOp := status.GetLastOperation()
if lastOp == nil {
return fmt.Errorf("extension did not record a last operation yet")
}
if lastOp.GetState() != gardencorev1alpha1.LastOperationStateSucceeded {
return fmt.Errorf("extension state is not succeeded but %v", lastOp.GetState())
}
return nil
}
// CheckBackupBucket checks if an backup bucket Object is healthy or not.
// An extension object is healthy if
// * Its observed generation is up-to-date
// * No gardener.cloud/operation is set
// * No lastError is in the status
// * A last operation is state succeeded is present
func CheckBackupBucket(obj *gardencorev1alpha1.BackupBucket) error {
status := obj.Status
if status.ObservedGeneration != obj.Generation {
return fmt.Errorf("observed generation outdated (%d/%d)", status.ObservedGeneration, obj.Generation)
}
op, ok := obj.GetAnnotations()[v1alpha1constants.GardenerOperation]
if ok {
return fmt.Errorf("gardener operation %q is not yet picked up by controller", op)
}
if lastErr := status.LastError; lastErr != nil {
return fmt.Errorf("backup bucket encountered error during reconciliation: %s", lastErr.GetDescription())
}
lastOp := status.LastOperation
if lastOp == nil {
return fmt.Errorf("backup bucket did not record a last operation yet")
}
if lastOp.GetState() != gardencorev1alpha1.LastOperationStateSucceeded {
return fmt.Errorf("backup bucket state is not succeeded but %v", lastOp.GetState())
}
return nil
}
// Now determines the current time.
var Now = time.Now
// ConditionerFunc to update a condition with type and message
type conditionerFunc func(conditionType string, message string) gardencorev1alpha1.Condition
// CheckAPIServerAvailability checks if the API server of a cluster is reachable and measure the response time.
func CheckAPIServerAvailability(condition gardencorev1alpha1.Condition, restClient rest.Interface, conditioner conditionerFunc) gardencorev1alpha1.Condition {
now := Now()
response := restClient.Get().AbsPath("/healthz").Do()
responseDurationText := fmt.Sprintf("[response_time:%dms]", Now().Sub(now).Nanoseconds()/time.Millisecond.Nanoseconds())
if response.Error() != nil {
message := fmt.Sprintf("Request to API server /healthz endpoint failed. %s (%s)", responseDurationText, response.Error().Error())
return conditioner("HealthzRequestFailed", message)
}
// Determine the status code of the response.
var statusCode int
response.StatusCode(&statusCode)
if statusCode != http.StatusOK {
var body string
bodyRaw, err := response.Raw()
if err != nil {
body = fmt.Sprintf("Could not parse response body: %s", err.Error())
} else {
body = string(bodyRaw)
}
message := fmt.Sprintf("API server /healthz endpoint endpoint check returned a non ok status code %d. %s (%s)", statusCode, responseDurationText, body)
return conditioner("HealthzRequestError", message)
}
message := fmt.Sprintf("API server /healthz endpoint responded with success status code. %s", responseDurationText)
return helper.UpdatedCondition(condition, gardencorev1alpha1.ConditionTrue, "HealthzRequestSucceeded", message)
}