/
remediation.go
287 lines (238 loc) · 10.2 KB
/
remediation.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
/*
Copyright 2022 The Kubernetes 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 remediation implements functions to manage the lifecycle of baremetal remediation.
package remediation
import (
"context"
"encoding/json"
"fmt"
"strings"
"time"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
capi "sigs.k8s.io/cluster-api/api/v1beta1"
"sigs.k8s.io/cluster-api/util"
"sigs.k8s.io/cluster-api/util/conditions"
"sigs.k8s.io/cluster-api/util/patch"
"sigs.k8s.io/cluster-api/util/record"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
infrav1 "github.com/syself/cluster-api-provider-hetzner/api/v1beta1"
"github.com/syself/cluster-api-provider-hetzner/pkg/scope"
)
// Service defines struct with BareMetalRemediationScope to reconcile HetznerBareMetalRemediations.
type Service struct {
scope *scope.BareMetalRemediationScope
}
// NewService outs a new service with BareMetalRemediationScope.
func NewService(scope *scope.BareMetalRemediationScope) *Service {
return &Service{
scope: scope,
}
}
// Reconcile implements reconcilement of HetznerBareMetalRemediations.
func (s *Service) Reconcile(ctx context.Context) (res reconcile.Result, err error) {
// try to get information about host from bare metal machine annotations
key, err := objectKeyFromAnnotations(s.scope.BareMetalMachine.ObjectMeta.GetAnnotations())
if err != nil {
if err := s.setOwnerRemediatedConditionNew(ctx); err != nil {
err = fmt.Errorf("failed to set remediated condition on capi machine: %w", err)
record.Warn(s.scope.BareMetalRemediation, "FailedSettingConditionOnMachine", err.Error())
return res, err
}
record.Event(s.scope.BareMetalRemediation, "ExitRemediation", "exit remediation because bare metal machine has no host annotation")
return res, nil
}
// get host
var host infrav1.HetznerBareMetalHost
if err := s.scope.Client.Get(ctx, key, &host); err != nil {
if apierrors.IsNotFound(err) {
if err := s.setOwnerRemediatedConditionNew(ctx); err != nil {
err = fmt.Errorf("failed to set remediated condition on capi machine: %w", err)
record.Warn(s.scope.BareMetalRemediation, "FailedSettingConditionOnMachine", err.Error())
return res, err
}
record.Event(s.scope.BareMetalRemediation, "ExitRemediation", "host not found - exit remediation")
return res, nil
}
err := fmt.Errorf("failed to find the unhealthy host: %w", err)
record.Warn(s.scope.BareMetalRemediation, "FailedToFindHost", err.Error())
return res, err
}
// if host is not provisioned or in maintenance mode, then we do not try to reboot server
if host.Spec.Status.ProvisioningState != infrav1.StateProvisioned ||
host.Spec.MaintenanceMode != nil && *host.Spec.MaintenanceMode {
if err := s.setOwnerRemediatedConditionNew(ctx); err != nil {
err := fmt.Errorf("failed to set remediated condition on capi machine: %w", err)
record.Warn(s.scope.BareMetalRemediation, "FailedSettingConditionOnMachine", err.Error())
return res, err
}
record.Eventf(
s.scope.BareMetalRemediation,
"ExitRemediation",
"exit remediation because host is not provisioned or in maintenance mode. Provisioning state: %s. Maintenance mode: %v",
host.Spec.Status.ProvisioningState, host.Spec.MaintenanceMode != nil && *host.Spec.MaintenanceMode,
)
return res, nil
}
if s.scope.BareMetalRemediation.Spec.Strategy.Type != infrav1.RemediationTypeReboot {
record.Warn(s.scope.BareMetalRemediation, "UnsupportedRemediationStrategy", "unsupported remediation strategy")
return res, nil
}
// If no phase set, default to running
if s.scope.BareMetalRemediation.Status.Phase == "" {
s.scope.BareMetalRemediation.Status.Phase = infrav1.PhaseRunning
}
switch s.scope.BareMetalRemediation.Status.Phase {
case infrav1.PhaseRunning:
return s.handlePhaseRunning(ctx, host)
case infrav1.PhaseWaiting:
return s.handlePhaseWaiting(ctx)
}
return res, nil
}
func (s *Service) handlePhaseRunning(ctx context.Context, host infrav1.HetznerBareMetalHost) (res reconcile.Result, err error) {
// if host has not been remediated yet, do that now
if s.scope.BareMetalRemediation.Status.LastRemediated == nil {
if err := s.remediate(ctx, host); err != nil {
return reconcile.Result{}, fmt.Errorf("failed remediate host: %w", err)
}
}
// if no retries are left, then change to phase waiting and return
if !s.scope.HasRetriesLeft() {
s.scope.BareMetalRemediation.Status.Phase = infrav1.PhaseWaiting
return
}
nextRemediation := s.timeUntilNextRemediation(time.Now())
if nextRemediation > 0 {
// requeue until it is time for the remediation
return reconcile.Result{RequeueAfter: nextRemediation}, nil
}
// remediate now
if err := s.remediate(ctx, host); err != nil {
return reconcile.Result{}, fmt.Errorf("failed remediate host: %w", err)
}
return res, nil
}
func (s *Service) remediate(ctx context.Context, host infrav1.HetznerBareMetalHost) error {
var err error
patchHelper, err := patch.NewHelper(&host, s.scope.Client)
if err != nil {
return fmt.Errorf("failed to init patch helper: %s %s/%s %w", host.Kind, host.Namespace, host.Name, err)
}
// add annotation to host so that it reboots
host.Annotations, err = addRebootAnnotation(host.Annotations)
if err != nil {
record.Warn(s.scope.BareMetalRemediation, "FailedAddingRebootAnnotation", err.Error())
return fmt.Errorf("failed to add reboot annotation: %w", err)
}
if err := patchHelper.Patch(ctx, &host); err != nil {
return fmt.Errorf("failed to patch: %s %s/%s %w", host.Kind, host.Namespace, host.Name, err)
}
record.Event(s.scope.BareMetalRemediation, "AnnotationAdded", "Reboot annotation is added to the BareMetalHost")
// update status of BareMetalRemediation object
now := metav1.Now()
s.scope.BareMetalRemediation.Status.LastRemediated = &now
s.scope.BareMetalRemediation.Status.RetryCount++
return nil
}
func (s *Service) handlePhaseWaiting(ctx context.Context) (res reconcile.Result, err error) {
nextCheck := s.timeUntilNextRemediation(time.Now())
if nextCheck > 0 {
// Not yet time to stop remediation, requeue
return reconcile.Result{RequeueAfter: nextCheck}, nil
}
// When machine is still unhealthy after remediation, setting of OwnerRemediatedCondition
// moves control to CAPI machine controller. The owning controller will do
// preflight checks and handles the Machine deletion
s.scope.BareMetalRemediation.Status.Phase = infrav1.PhaseDeleting
if err := s.setOwnerRemediatedConditionNew(ctx); err != nil {
err := fmt.Errorf("failed to set remediated condition on capi machine: %w", err)
record.Warn(s.scope.BareMetalRemediation, "FailedSettingConditionOnMachine", err.Error())
return res, err
}
record.Event(s.scope.BareMetalRemediation, "SetOwnerRemediatedCondition", "because retryLimit is reached and reboot timed out")
return res, nil
}
// timeUntilNextRemediation checks if it is time to execute a next remediation step
// and returns seconds to next remediation time.
func (s *Service) timeUntilNextRemediation(now time.Time) time.Duration {
timeout := s.scope.BareMetalRemediation.Spec.Strategy.Timeout.Duration
// status is not updated yet
if s.scope.BareMetalRemediation.Status.LastRemediated == nil {
return timeout
}
if s.scope.BareMetalRemediation.Status.LastRemediated.Add(timeout).Before(now) {
return time.Duration(0)
}
lastRemediated := now.Sub(s.scope.BareMetalRemediation.Status.LastRemediated.Time)
nextRemediation := timeout - lastRemediated + time.Second
return nextRemediation
}
// setOwnerRemediatedConditionNew sets MachineOwnerRemediatedCondition on CAPI machine object
// that have failed a healthcheck.
func (s *Service) setOwnerRemediatedConditionNew(ctx context.Context) error {
capiMachine, err := util.GetOwnerMachine(ctx, s.scope.Client, s.scope.BareMetalRemediation.ObjectMeta)
if err != nil {
return fmt.Errorf("failed to get capi machine: %w", err)
}
patchHelper, err := patch.NewHelper(capiMachine, s.scope.Client)
if err != nil {
return fmt.Errorf("failed to init patch helper: %s %s/%s %w", capiMachine.Kind, capiMachine.Namespace, capiMachine.Name, err)
}
conditions.MarkFalse(
capiMachine,
capi.MachineOwnerRemediatedCondition,
capi.WaitingForRemediationReason,
capi.ConditionSeverityWarning,
"remediation through reboot failed",
)
if err := patchHelper.Patch(ctx, capiMachine); err != nil {
return fmt.Errorf("failed to patch: %s %s/%s %w", capiMachine.Kind, capiMachine.Namespace, capiMachine.Name, err)
}
return nil
}
func objectKeyFromAnnotations(annotations map[string]string) (client.ObjectKey, error) {
if annotations == nil {
return client.ObjectKey{}, fmt.Errorf("unable to get annotations")
}
hostKey, ok := annotations[infrav1.HostAnnotation]
if !ok {
return client.ObjectKey{}, fmt.Errorf("unable to get HostAnnotation")
}
hostNamespace, hostName, err := splitHostKey(hostKey)
if err != nil {
return client.ObjectKey{}, fmt.Errorf("failed to parse host key %q: %w", hostKey, err)
}
return client.ObjectKey{Name: hostName, Namespace: hostNamespace}, nil
}
// addRebootAnnotation sets reboot annotation on unhealthy host.
func addRebootAnnotation(annotations map[string]string) (map[string]string, error) {
rebootAnnotationArguments := infrav1.RebootAnnotationArguments{Type: infrav1.RebootTypeHardware}
b, err := json.Marshal(rebootAnnotationArguments)
if err != nil {
return nil, fmt.Errorf("failed to marshal reboot annotation arguments %+v: %w", rebootAnnotationArguments, err)
}
if annotations == nil {
annotations = make(map[string]string)
}
annotations[infrav1.RebootAnnotation] = string(b)
return annotations, nil
}
func splitHostKey(key string) (namespace, name string, err error) {
parts := strings.Split(key, "/")
if len(parts) != 2 {
return "", "", fmt.Errorf("unexpected host key")
}
return parts[0], parts[1], nil
}