-
Notifications
You must be signed in to change notification settings - Fork 473
/
healtcheck_actuator.go
284 lines (254 loc) · 10.1 KB
/
healtcheck_actuator.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
// 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 healthcheck
import (
"context"
"fmt"
"strings"
"sync"
"time"
extensionscontroller "github.com/gardener/gardener/extensions/pkg/controller"
"github.com/gardener/gardener/extensions/pkg/util"
gardencorev1beta1 "github.com/gardener/gardener/pkg/apis/core/v1beta1"
"github.com/go-logr/logr"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/rest"
"k8s.io/utils/pointer"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log"
)
// Actuator contains all the health checks and the means to execute them
type Actuator struct {
logger logr.Logger
restConfig *rest.Config
seedClient client.Client
scheme *runtime.Scheme
decoder runtime.Decoder
provider string
extensionKind string
getExtensionObjFunc GetExtensionObjectFunc
healthChecks []ConditionTypeToHealthCheck
}
// NewActuator creates a new Actuator.
func NewActuator(provider, extensionKind string, getExtensionObjFunc GetExtensionObjectFunc, healthChecks []ConditionTypeToHealthCheck) HealthCheckActuator {
return &Actuator{
healthChecks: healthChecks,
getExtensionObjFunc: getExtensionObjFunc,
provider: provider,
extensionKind: extensionKind,
logger: log.Log.WithName(fmt.Sprintf("%s-%s-healthcheck-actuator", provider, extensionKind)),
}
}
func (a *Actuator) InjectScheme(scheme *runtime.Scheme) error {
a.scheme = scheme
a.decoder = serializer.NewCodecFactory(a.scheme).UniversalDecoder()
return nil
}
func (a *Actuator) InjectClient(client client.Client) error {
a.seedClient = client
return nil
}
func (a *Actuator) InjectConfig(config *rest.Config) error {
a.restConfig = config
return nil
}
type healthCheckUnsuccessful struct {
reason string
detail string
}
type healthCheckProgressing struct {
reason string
detail string
threshold *time.Duration
}
type channelResult struct {
healthConditionType string
healthCheckResult *SingleCheckResult
error error
}
type checkResultForConditionType struct {
failedChecks []error
unsuccessfulChecks []healthCheckUnsuccessful
progressingChecks []healthCheckProgressing
successfulChecks int
codes []gardencorev1beta1.ErrorCode
}
// ExecuteHealthCheckFunctions executes all the health check functions, injects clients and logger & aggregates the results.
// returns an Result for each HealthConditionType (e.g ControlPlaneHealthy)
func (a *Actuator) ExecuteHealthCheckFunctions(ctx context.Context, request types.NamespacedName) (*[]Result, error) {
var (
shootClient client.Client
channel = make(chan channelResult)
wg sync.WaitGroup
)
wg.Add(len(a.healthChecks))
for _, hc := range a.healthChecks {
// clone to avoid problems during parallel execution
check := hc.HealthCheck.DeepCopy()
SeedClientInto(a.seedClient, check)
if _, ok := check.(ShootClient); ok {
if shootClient == nil {
var err error
_, shootClient, err = util.NewClientForShoot(ctx, a.seedClient, request.Namespace, client.Options{})
if err != nil {
msg := fmt.Errorf("failed to create shoot client in namespace '%s': %v", request.Namespace, err)
a.logger.Error(err, msg.Error())
return nil, msg
}
}
ShootClientInto(shootClient, check)
}
check.SetLoggerSuffix(a.provider, a.extensionKind)
go func(ctx context.Context, request types.NamespacedName, check HealthCheck, preCheckFunc PreCheckFunc, healthConditionType string) {
defer wg.Done()
if preCheckFunc != nil {
obj := a.getExtensionObjFunc()
if err := a.seedClient.Get(ctx, client.ObjectKey{Namespace: request.Namespace, Name: request.Name}, obj); err != nil {
channel <- channelResult{
healthCheckResult: &SingleCheckResult{
Status: gardencorev1beta1.ConditionFalse,
Detail: err.Error(),
Reason: "ReadExtensionObjectFailed",
},
error: err,
healthConditionType: healthConditionType,
}
return
}
cluster, err := extensionscontroller.GetCluster(ctx, a.seedClient, request.Namespace)
if err != nil {
channel <- channelResult{
healthCheckResult: &SingleCheckResult{
Status: gardencorev1beta1.ConditionFalse,
Detail: err.Error(),
Reason: "ReadClusterObjectFailed",
},
error: err,
healthConditionType: healthConditionType,
}
return
}
if !preCheckFunc(obj, cluster) {
a.logger.V(6).Info("Skipping health check as pre check function returned false", "condition type", healthConditionType)
channel <- channelResult{
healthCheckResult: &SingleCheckResult{
Status: gardencorev1beta1.ConditionTrue,
},
error: nil,
healthConditionType: healthConditionType,
}
return
}
}
healthCheckResult, err := check.Check(ctx, request)
channel <- channelResult{
healthCheckResult: healthCheckResult,
error: err,
healthConditionType: healthConditionType,
}
}(ctx, request, check, hc.PreCheckFunc, hc.ConditionType)
}
// close channel when wait group has 0 counter
go func() {
wg.Wait()
close(channel)
}()
groupedHealthCheckResults := make(map[string]*checkResultForConditionType)
// loop runs until channel is closed
for channelResult := range channel {
if groupedHealthCheckResults[channelResult.healthConditionType] == nil {
groupedHealthCheckResults[channelResult.healthConditionType] = &checkResultForConditionType{}
}
if channelResult.error != nil {
groupedHealthCheckResults[channelResult.healthConditionType].failedChecks = append(groupedHealthCheckResults[channelResult.healthConditionType].failedChecks, channelResult.error)
continue
}
if channelResult.healthCheckResult.Status == gardencorev1beta1.ConditionFalse {
groupedHealthCheckResults[channelResult.healthConditionType].unsuccessfulChecks = append(groupedHealthCheckResults[channelResult.healthConditionType].unsuccessfulChecks, healthCheckUnsuccessful{reason: channelResult.healthCheckResult.Reason, detail: channelResult.healthCheckResult.Detail})
groupedHealthCheckResults[channelResult.healthConditionType].codes = append(groupedHealthCheckResults[channelResult.healthConditionType].codes, channelResult.healthCheckResult.Codes...)
continue
}
if channelResult.healthCheckResult.Status == gardencorev1beta1.ConditionProgressing {
groupedHealthCheckResults[channelResult.healthConditionType].progressingChecks = append(groupedHealthCheckResults[channelResult.healthConditionType].progressingChecks, healthCheckProgressing{reason: channelResult.healthCheckResult.Reason, detail: channelResult.healthCheckResult.Detail, threshold: channelResult.healthCheckResult.ProgressingThreshold})
groupedHealthCheckResults[channelResult.healthConditionType].codes = append(groupedHealthCheckResults[channelResult.healthConditionType].codes, channelResult.healthCheckResult.Codes...)
continue
}
groupedHealthCheckResults[channelResult.healthConditionType].successfulChecks++
}
var checkResults []Result
for conditionType, result := range groupedHealthCheckResults {
if len(result.unsuccessfulChecks) > 0 || len(result.failedChecks) > 0 {
var details strings.Builder
if len(result.unsuccessfulChecks) > 0 {
details.WriteString("Unsuccessful checks: ")
}
for index, check := range result.unsuccessfulChecks {
details.WriteString(fmt.Sprintf("%d) %s: %s. ", index+1, check.reason, check.detail))
}
if len(result.progressingChecks) > 0 {
details.WriteString("Progressing checks: ")
}
for index, check := range result.progressingChecks {
details.WriteString(fmt.Sprintf("%d) %s: %s. ", index+1, check.reason, check.detail))
}
if len(result.failedChecks) > 0 {
details.WriteString("Failed checks: ")
}
for index, err := range result.failedChecks {
details.WriteString(fmt.Sprintf("%d) %s. ", index+1, err.Error()))
}
checkResults = append(checkResults, Result{
HealthConditionType: conditionType,
Status: gardencorev1beta1.ConditionFalse,
Detail: pointer.StringPtr(details.String()),
SuccessfulChecks: result.successfulChecks,
UnsuccessfulChecks: len(result.unsuccessfulChecks),
FailedChecks: len(result.failedChecks),
Codes: result.codes,
})
continue
}
if len(result.progressingChecks) > 0 {
var (
details strings.Builder
threshold *time.Duration
)
details.WriteString("Progressing checks: ")
for index, check := range result.progressingChecks {
details.WriteString(fmt.Sprintf("%d) %s: %s. ", index+1, check.reason, check.detail))
if check.threshold != nil && (threshold == nil || *threshold > *check.threshold) {
threshold = check.threshold
}
}
checkResults = append(checkResults, Result{
HealthConditionType: conditionType,
Status: gardencorev1beta1.ConditionProgressing,
ProgressingThreshold: threshold,
Detail: pointer.StringPtr(details.String()),
SuccessfulChecks: result.successfulChecks,
ProgressingChecks: len(result.progressingChecks),
Codes: result.codes,
})
continue
}
checkResults = append(checkResults, Result{
HealthConditionType: conditionType,
Status: gardencorev1beta1.ConditionTrue,
SuccessfulChecks: result.successfulChecks,
})
}
return &checkResults, nil
}