-
Notifications
You must be signed in to change notification settings - Fork 458
/
healthcheck_actuator.go
285 lines (251 loc) · 10.3 KB
/
healthcheck_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
285
// Copyright 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"
"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"
extensionsconfig "github.com/gardener/gardener/extensions/pkg/apis/config"
extensionscontroller "github.com/gardener/gardener/extensions/pkg/controller"
"github.com/gardener/gardener/extensions/pkg/util"
gardencorev1beta1 "github.com/gardener/gardener/pkg/apis/core/v1beta1"
)
// Actuator contains all the health checks and the means to execute them
type Actuator struct {
restConfig *rest.Config
seedClient client.Client
scheme *runtime.Scheme
decoder runtime.Decoder
provider string
extensionKind string
getExtensionObjFunc GetExtensionObjectFunc
healthChecks []ConditionTypeToHealthCheck
shootRESTOptions extensionsconfig.RESTOptions
}
// NewActuator creates a new Actuator.
func NewActuator(provider, extensionKind string, getExtensionObjFunc GetExtensionObjectFunc, healthChecks []ConditionTypeToHealthCheck, shootRESTOptions extensionsconfig.RESTOptions) HealthCheckActuator {
return &Actuator{
healthChecks: healthChecks,
getExtensionObjFunc: getExtensionObjFunc,
provider: provider,
extensionKind: extensionKind,
shootRESTOptions: shootRESTOptions,
}
}
// InjectScheme injects the given runtime.Scheme into this Actuator.
func (a *Actuator) InjectScheme(scheme *runtime.Scheme) error {
a.scheme = scheme
a.decoder = serializer.NewCodecFactory(a.scheme).UniversalDecoder()
return nil
}
// InjectClient injects the given client.Client into this Actuator.
func (a *Actuator) InjectClient(client client.Client) error {
a.seedClient = client
return nil
}
// InjectConfig injects the given rest.Config into this Actuator.
func (a *Actuator) InjectConfig(config *rest.Config) error {
a.restConfig = config
return nil
}
type healthCheckUnsuccessful struct {
detail string
}
type healthCheckProgressing struct {
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, log logr.Logger, request types.NamespacedName) (*[]Result, error) {
var (
shootClient client.Client
channel = make(chan channelResult, len(a.healthChecks))
wg sync.WaitGroup
)
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{}, a.shootRESTOptions)
if err != nil {
// don't return here, as we might have started some goroutines already to prevent leakage
channel <- channelResult{
healthCheckResult: &SingleCheckResult{
Status: gardencorev1beta1.ConditionFalse,
Detail: fmt.Sprintf("failed to create shoot client: %v", err),
},
error: err,
healthConditionType: hc.ConditionType,
}
continue
}
}
ShootClientInto(shootClient, check)
}
check.SetLoggerSuffix(a.provider, a.extensionKind)
wg.Add(1)
go func(ctx context.Context, request types.NamespacedName, check HealthCheck, preCheckFunc PreCheckFunc, errorCodeCheckFunc ErrorCodeCheckFunc, 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: fmt.Sprintf("failed to read the extension resource: %v", err),
},
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: fmt.Sprintf("failed to read the cluster resource: %v", err),
},
error: err,
healthConditionType: healthConditionType,
}
return
}
if !preCheckFunc(ctx, a.seedClient, obj, cluster) {
log.V(1).Info("Skipping health check as pre check function returned false", "conditionType", healthConditionType)
channel <- channelResult{
healthCheckResult: &SingleCheckResult{
Status: gardencorev1beta1.ConditionTrue,
},
error: nil,
healthConditionType: healthConditionType,
}
return
}
}
healthCheckResult, err := check.Check(ctx, request)
if errorCodeCheckFunc != nil {
healthCheckResult.Codes = append(healthCheckResult.Codes, errorCodeCheckFunc(fmt.Errorf("%s", healthCheckResult.Detail))...)
}
channel <- channelResult{
healthCheckResult: healthCheckResult,
error: err,
healthConditionType: healthConditionType,
}
}(ctx, request, check, hc.PreCheckFunc, hc.ErrorCodeCheckFunc, 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{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{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
result.appendFailedChecksDetails(&details)
result.appendUnsuccessfulChecksDetails(&details)
result.appendProgressingChecksDetails(&details)
checkResults = append(checkResults, Result{
HealthConditionType: conditionType,
Status: gardencorev1beta1.ConditionFalse,
Detail: pointer.String(trimTrailingWhitespace(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
)
for index, check := range result.progressingChecks {
if len(result.progressingChecks) == 1 {
details.WriteString(ensureTrailingDot(check.detail))
} else {
details.WriteString(fmt.Sprintf("%d) %s ", index+1, ensureTrailingDot(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.String(trimTrailingWhitespace(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
}