/
healthscope_controller.go
257 lines (216 loc) · 8.16 KB
/
healthscope_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
/*
Copyright 2020 The Crossplane Authors.
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 healthscope
import (
"context"
"strings"
"sync"
"time"
"github.com/pkg/errors"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
runtimev1alpha1 "github.com/crossplane/crossplane-runtime/apis/core/v1alpha1"
"github.com/crossplane/crossplane-runtime/pkg/event"
"github.com/crossplane/crossplane-runtime/pkg/logging"
"github.com/crossplane/crossplane-runtime/pkg/resource"
"github.com/xishengcai/oam/apis/core/v1alpha2"
"github.com/xishengcai/oam/pkg/controller"
)
const (
reconcileTimeout = 1 * time.Minute
longWait = 10 * time.Second
)
// Reconcile error strings.
const (
errGetHealthScope = "cannot get health scope"
errUpdateHealthScopeStatus = "cannot update health scope status"
)
// Reconcile event reasons.
const (
reasonHealthCheck = "HealthCheck"
)
// Setup adds a controller that reconciles HealthScope.
func Setup(mgr ctrl.Manager, args controller.Args) error {
name := "oam/" + strings.ToLower(v1alpha2.HealthScopeGroupKind)
return ctrl.NewControllerManagedBy(mgr).
Named(name).
For(&v1alpha2.HealthScope{}).
Complete(NewReconciler(mgr,
WithRecorder(event.NewAPIRecorder(mgr.GetEventRecorderFor(name))),
))
}
// A Reconciler reconciles OAM Scopes by keeping track of the health status of components.
type Reconciler struct {
client client.Client
log logging.Logger
record event.Recorder
// traitChecker represents checker fetching health condition from HealthCheckTrait
traitChecker WorloadHealthChecker
// checkers represents a set of built-in checkers
checkers []WorloadHealthChecker
// unknownChecker represents checker handling workloads that
// cannot be hanlded by traitChecker nor built-in checkers
unknownChecker WorloadHealthChecker
}
// A ReconcilerOption configures a Reconciler.
type ReconcilerOption func(*Reconciler)
// WithLogger specifies how the Reconciler should log messages.
func WithLogger(l logging.Logger) ReconcilerOption {
return func(r *Reconciler) {
r.log = l
}
}
// WithRecorder specifies how the Reconciler should record events.
func WithRecorder(er event.Recorder) ReconcilerOption {
return func(r *Reconciler) {
r.record = er
}
}
// WithTraitChecker adds health checker based on HealthCheckTrait
func WithTraitChecker(c WorloadHealthChecker) ReconcilerOption {
return func(r *Reconciler) {
r.traitChecker = c
}
}
// WithChecker adds workload health checker
func WithChecker(c WorloadHealthChecker) ReconcilerOption {
return func(r *Reconciler) {
if r.checkers == nil {
r.checkers = make([]WorloadHealthChecker, 0)
}
r.checkers = append(r.checkers, c)
}
}
// NewReconciler returns a Reconciler that reconciles HealthScope by keeping track of its healthstatus.
func NewReconciler(m ctrl.Manager, o ...ReconcilerOption) *Reconciler {
r := &Reconciler{
client: m.GetClient(),
log: logging.NewNopLogger(),
record: event.NewNopRecorder(),
traitChecker: WorkloadHealthCheckFn(CheckByHealthCheckTrait),
checkers: []WorloadHealthChecker{
WorkloadHealthCheckFn(CheckPodSpecWorkloadHealth),
WorkloadHealthCheckFn(CheckContainerziedWorkloadHealth),
WorkloadHealthCheckFn(CheckDeploymentHealth),
WorkloadHealthCheckFn(CheckStatefulsetHealth),
WorkloadHealthCheckFn(CheckDaemonsetHealth),
},
unknownChecker: WorkloadHealthCheckFn(CheckUnknownWorkload),
}
for _, ro := range o {
ro(r)
}
return r
}
// Reconcile an OAM HealthScope by keeping track of its health status.
func (r *Reconciler) Reconcile(req reconcile.Request) (reconcile.Result, error) {
log := r.log.WithValues("request", req)
log.Debug("Reconciling")
ctx, cancel := context.WithTimeout(context.Background(), reconcileTimeout)
defer cancel()
hs := &v1alpha2.HealthScope{}
if err := r.client.Get(ctx, req.NamespacedName, hs); err != nil {
return reconcile.Result{}, errors.Wrap(resource.IgnoreNotFound(err), errGetHealthScope)
}
interval := longWait
if hs.Spec.ProbeInterval != nil {
interval = time.Duration(*hs.Spec.ProbeInterval) * time.Second
}
if interval <= 0 {
interval = longWait
}
start := time.Now()
log = log.WithValues("uid", hs.GetUID(), "version", hs.GetResourceVersion())
scopeCondition, wlConditions := r.GetScopeHealthStatus(ctx, hs)
log.Debug("Successfully ran health check", "scope", hs.Name)
r.record.Event(hs, event.Normal(reasonHealthCheck, "Successfully ran health check"))
elapsed := time.Since(start)
hs.Status.ScopeHealthCondition = scopeCondition
hs.Status.WorkloadHealthConditions = wlConditions
return reconcile.Result{RequeueAfter: interval - elapsed}, errors.Wrap(r.client.Status().Update(ctx, hs), errUpdateHealthScopeStatus)
}
// GetScopeHealthStatus get the status of the healthscope based on workload resources.
func (r *Reconciler) GetScopeHealthStatus(ctx context.Context, healthScope *v1alpha2.HealthScope) (ScopeHealthCondition, []*WorkloadHealthCondition) {
log := r.log.WithValues("get scope health status", healthScope.GetName())
scopeCondition := ScopeHealthCondition{
HealthStatus: StatusHealthy, // if no workload referenced, scope is healthy by default
}
scopeWLRefs := healthScope.Spec.WorkloadReferences
if len(scopeWLRefs) == 0 {
return scopeCondition, []*WorkloadHealthCondition{}
}
timeout := defaultTimeout
if healthScope.Spec.ProbeTimeout != nil {
timeout = time.Duration(*healthScope.Spec.ProbeTimeout) * time.Second
}
ctxWithTimeout, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
// process workloads concurrently
workloadHealthConditionsC := make(chan *WorkloadHealthCondition, len(scopeWLRefs))
var wg sync.WaitGroup
wg.Add(len(scopeWLRefs))
for _, workloadRef := range scopeWLRefs {
go func(resRef runtimev1alpha1.TypedReference) {
defer wg.Done()
var wlHealthCondition *WorkloadHealthCondition
wlHealthCondition = r.traitChecker.Check(ctx, r.client, resRef, healthScope.GetNamespace())
if wlHealthCondition != nil {
log.Debug("get health condition from health check trait ", "workload", resRef, "healthCondition", wlHealthCondition)
// get healthCondition from HealthCheckTrait
workloadHealthConditionsC <- wlHealthCondition
return
}
for _, checker := range r.checkers {
wlHealthCondition = checker.Check(ctxWithTimeout, r.client, resRef, healthScope.GetNamespace())
if wlHealthCondition != nil {
log.Debug("get health condition from built-in checker", "workload", resRef, "healthCondition", wlHealthCondition)
// found matched checker and get health condition
workloadHealthConditionsC <- wlHealthCondition
return
}
}
// handle unknown workload
log.Debug("get unknown workload", "workload", resRef)
workloadHealthConditionsC <- r.unknownChecker.Check(ctx, r.client, resRef, healthScope.GetNamespace())
}(workloadRef)
}
go func() {
wg.Wait()
close(workloadHealthConditionsC)
}()
var healthyCount, unhealthyCount, unknownCount int64
workloadHealthConditions := []*WorkloadHealthCondition{}
for wlC := range workloadHealthConditionsC {
workloadHealthConditions = append(workloadHealthConditions, wlC)
switch wlC.HealthStatus { //nolint:exhaustive
case StatusHealthy:
healthyCount++
case StatusUnhealthy:
unhealthyCount++
case StatusUnknown:
unknownCount++
default:
unknownCount++
}
}
if unhealthyCount > 0 || unknownCount > 0 {
// ANY unhealthy or unknown worloads make the whole scope unhealthy
scopeCondition.HealthStatus = StatusUnhealthy
}
scopeCondition.Total = int64(len(scopeWLRefs))
scopeCondition.HealthyWorkloads = healthyCount
scopeCondition.UnhealthyWorkloads = unhealthyCount
scopeCondition.UnknownWorkloads = unknownCount
return scopeCondition, workloadHealthConditions
}