-
Notifications
You must be signed in to change notification settings - Fork 308
Expand file tree
/
Copy pathbaremetalhost_controller.go
More file actions
2618 lines (2272 loc) · 96.8 KB
/
baremetalhost_controller.go
File metadata and controls
2618 lines (2272 loc) · 96.8 KB
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
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 controllers
import (
"context"
"encoding/json"
"errors"
"fmt"
"reflect"
"runtime"
"slices"
"strings"
"time"
"github.com/go-logr/logr"
metal3api "github.com/metal3-io/baremetal-operator/apis/metal3.io/v1alpha1"
"github.com/metal3-io/baremetal-operator/apis/metal3.io/v1alpha1/profile"
"github.com/metal3-io/baremetal-operator/pkg/hardwareutils/bmc"
"github.com/metal3-io/baremetal-operator/pkg/imageprovider"
"github.com/metal3-io/baremetal-operator/pkg/provisioner"
"github.com/metal3-io/baremetal-operator/pkg/secretutils"
"github.com/prometheus/client_golang/prometheus"
corev1 "k8s.io/api/core/v1"
apiequality "k8s.io/apimachinery/pkg/api/equality"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/tools/record"
"sigs.k8s.io/cluster-api/util/conditions"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/builder"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/predicate"
)
const (
hostErrorRetryDelay = time.Second * 10
unmanagedRetryDelay = time.Minute * 10
preprovImageRetryDelay = time.Minute * 5
provisionerNotReadyRetryDelay = time.Second * 30
subResourceNotReadyRetryDelay = time.Second * 60
clarifySoftPoweroffFailure = "Continuing with hard poweroff after soft poweroff fails. More details: "
hardwareDataFinalizer = metal3api.BareMetalHostFinalizer + "/hardwareData"
NotReady = "Not ready"
)
// BareMetalHostReconciler reconciles a BareMetalHost object.
type BareMetalHostReconciler struct {
client.Client
Log logr.Logger
ProvisionerFactory provisioner.Factory
APIReader client.Reader
Recorder record.EventRecorder
}
// Instead of passing a zillion arguments to the action of a phase,
// hold them in a struct.
type reconcileInfo struct {
log logr.Logger
host *metal3api.BareMetalHost
request ctrl.Request
bmcCredsSecret *corev1.Secret
events []corev1.Event
postSaveCallbacks []func()
}
// match the provisioner.EventPublisher interface.
func (info *reconcileInfo) publishEvent(reason, message string) {
info.events = append(info.events, info.host.NewEvent(reason, message))
}
// +kubebuilder:rbac:groups=metal3.io,resources=baremetalhosts,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=metal3.io,resources=baremetalhosts/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=metal3.io,resources=baremetalhosts/finalizers,verbs=update
// +kubebuilder:rbac:groups=metal3.io,resources=preprovisioningimages,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=metal3.io,resources=hardwaredata,verbs=get;list;watch;create;delete;patch;update
// +kubebuilder:rbac:groups=metal3.io,resources=hardware/finalizers,verbs=update
// +kubebuilder:rbac:groups="",resources=secrets,verbs=get;list;watch;update
// +kubebuilder:rbac:groups="",resources=events,verbs=create;update;patch
// Allow for managing hostfirmwaresettings, firmwareschema, bmceventsubscriptions and hostfirmwarecomponents
// +kubebuilder:rbac:groups=metal3.io,resources=hostfirmwaresettings,verbs=get;list;watch;create;update;patch
// +kubebuilder:rbac:groups=metal3.io,resources=firmwareschemas,verbs=get;list;watch;create;update;patch
// +kubebuilder:rbac:groups=metal3.io,resources=bmceventsubscriptions,verbs=get;list;watch;create;update;patch
// +kubebuilder:rbac:groups=metal3.io,resources=hostfirmwarecomponents,verbs=get;list;watch;create;update;patch
// Allow for updating dataimage
// +kubebuilder:rbac:groups=metal3.io,resources=dataimages,verbs=get;list;watch;create;update;patch
// +kubebuilder:rbac:groups=metal3.io,resources=dataimages/status,verbs=get;update;patch
// Allow for updating hostupdatepolicies
// +kubebuilder:rbac:groups=metal3.io,resources=hostupdatepolicies,verbs=get;list;watch;update
// Allow reading Ironic resources
// +kubebuilder:rbac:groups=ironic.metal3.io,resources=ironics,verbs=get;list;watch
// Reconcile handles changes to BareMetalHost resources.
func (r *BareMetalHostReconciler) Reconcile(ctx context.Context, request ctrl.Request) (result ctrl.Result, err error) {
reconcileCounters.With(hostMetricLabels(request)).Inc()
defer func() {
if err != nil {
reconcileErrorCounter.Inc()
}
}()
reqLogger := r.Log.WithValues("baremetalhost", request.NamespacedName)
reqLogger.Info("start")
// Fetch the BareMetalHost
host := &metal3api.BareMetalHost{}
err = r.Get(ctx, request.NamespacedName, host)
if err != nil {
if k8serrors.IsNotFound(err) {
// Request object not found, could have been deleted after
// reconcile request. Owned objects are automatically
// garbage collected. For additional cleanup logic use
// finalizers. Return and don't requeue
return ctrl.Result{}, nil
}
// Error reading the object - requeue the request.
return ctrl.Result{}, fmt.Errorf("could not load host data: %w", err)
}
// If the reconciliation is paused, requeue
annotations := host.GetAnnotations()
if annotations != nil {
if _, ok := annotations[metal3api.PausedAnnotation]; ok {
reqLogger.Info("host is paused, no work to do")
return ctrl.Result{Requeue: false}, nil
}
}
hostData, err := r.reconcileHostData(ctx, host, request)
if err != nil {
return ctrl.Result{}, fmt.Errorf("could not reconcile host data: %w", err)
} else if hostData.Requeue {
return ctrl.Result{Requeue: true}, nil
}
// Consume hardwaredetails from annotation if present
hwdUpdated, err := r.updateHardwareDetails(ctx, request, host)
if err != nil {
return ctrl.Result{}, fmt.Errorf("could not update hardware details: %w", err)
} else if hwdUpdated {
return ctrl.Result{Requeue: true}, nil
}
// NOTE(dhellmann): Handle a few steps outside of the phase
// structure because they require extra data lookup (like the
// credential checks) or have to be done "first" (like delete
// handling) to avoid looping.
// Add a finalizer to newly created objects.
if host.DeletionTimestamp.IsZero() && !hostHasFinalizer(host) {
reqLogger.Info(
"adding finalizer",
"existingFinalizers", host.Finalizers,
"newValue", metal3api.BareMetalHostFinalizer,
)
host.Finalizers = append(host.Finalizers,
metal3api.BareMetalHostFinalizer)
err = r.Update(ctx, host)
if err != nil {
return ctrl.Result{}, fmt.Errorf("failed to add finalizer: %w", err)
}
return ctrl.Result{Requeue: true}, nil
}
// Retrieve the BMC details from the host spec and validate host
// BMC details and build the credentials for talking to the
// management controller.
var bmcCreds *bmc.Credentials
var bmcCredsSecret *corev1.Secret
haveCreds := false
switch host.Status.Provisioning.State {
case metal3api.StateNone, metal3api.StateUnmanaged:
bmcCreds = &bmc.Credentials{}
default:
bmcCreds, bmcCredsSecret, err = r.buildAndValidateBMCCredentials(ctx, request, host)
if err != nil || bmcCreds == nil {
if !host.DeletionTimestamp.IsZero() {
// If we are in the process of deletion, try with empty credentials
bmcCreds = &bmc.Credentials{}
bmcCredsSecret = &corev1.Secret{}
} else {
return r.credentialsErrorResult(ctx, err, request, host)
}
} else {
haveCreds = true
}
}
initialState := host.Status.Provisioning.State
info := &reconcileInfo{
log: reqLogger.WithValues("provisioningState", initialState),
host: host,
request: request,
bmcCredsSecret: bmcCredsSecret,
}
prov, err := r.ProvisionerFactory.NewProvisioner(ctx, provisioner.BuildHostData(*host, *bmcCreds), info.publishEvent)
if err != nil {
return ctrl.Result{}, fmt.Errorf("failed to create provisioner: %w", err)
}
ready, err := prov.TryInit(ctx)
if err != nil || !ready {
var msg string
if err == nil {
msg = NotReady
} else {
msg = err.Error()
}
provisionerNotReady.Inc()
reqLogger.Info("provisioner is not ready", "Error", msg, "RequeueAfter", provisionerNotReadyRetryDelay)
return ctrl.Result{Requeue: true, RequeueAfter: provisionerNotReadyRetryDelay}, nil
}
stateMachine := newHostStateMachine(host, r, prov, haveCreds)
actResult := stateMachine.ReconcileState(ctx, info)
result, err = actResult.Result()
if err != nil {
err = fmt.Errorf("action %q failed: %w", initialState, err)
return result, err
}
// Always compute conditions since some (e.g. Healthy) can change
// based on external state from Ironic regardless of state machine
// transitions.
conditionsBefore := slices.Clone(host.GetConditions())
computeConditions(ctx, host, prov)
conditionsChanged := !reflect.DeepEqual(conditionsBefore, host.GetConditions())
// Only save status when we're told to, otherwise we
// introduce an infinite loop reconciling the same object over and
// over when there is an unrecoverable error (tracked through the
// error state of the host).
if actResult.Dirty() || conditionsChanged {
info.log.Info("saving host status",
"operational status", host.OperationalStatus(),
"provisioning state", host.Status.Provisioning.State)
err = r.saveHostStatus(ctx, host)
if err != nil {
return ctrl.Result{}, fmt.Errorf("failed to save host status after %q: %w", initialState, err)
}
for _, cb := range info.postSaveCallbacks {
cb()
}
}
for _, e := range info.events {
r.publishEvent(ctx, request, e)
}
logResult(info, result)
return result, nil
}
// Consume inspect.metal3.io/hardwaredetails when either
// inspect.metal3.io=disabled or there are no existing HardwareDetails.
func (r *BareMetalHostReconciler) updateHardwareDetails(ctx context.Context, request ctrl.Request, host *metal3api.BareMetalHost) (bool, error) {
updated := false
if host.Status.HardwareDetails == nil || host.InspectionDisabled() {
hardwareData := &metal3api.HardwareData{}
hardwareDataKey := client.ObjectKey{
Name: host.Name,
Namespace: host.Namespace,
}
err := r.Client.Get(ctx, hardwareDataKey, hardwareData)
if err != nil && !k8serrors.IsNotFound(err) {
return updated, fmt.Errorf("error loading HardwareData: %w", err)
}
objHardwareDetails := hardwareData.Spec.HardwareDetails
if objHardwareDetails == nil {
objHardwareDetails, err = r.getHardwareDetailsFromAnnotation(host)
if err != nil {
return updated, fmt.Errorf("error parsing HardwareDetails from annotation: %w", err)
}
}
if objHardwareDetails != nil && !reflect.DeepEqual(host.Status.HardwareDetails, objHardwareDetails) {
host.Status.HardwareDetails = objHardwareDetails
err = r.saveHostStatus(ctx, host)
if err != nil {
return updated, fmt.Errorf("could not update hardwaredetails from existing hardware data or annotation: %w", err)
}
r.publishEvent(ctx, request, host.NewEvent("UpdateHardwareDetails", "Set HardwareDetails from hardware data or annotation"))
updated = true
}
}
// We either just processed the annotation, or the status is already set
// so we remove it
annotations := host.GetAnnotations()
if _, present := annotations[metal3api.HardwareDetailsAnnotation]; present {
delete(host.Annotations, metal3api.HardwareDetailsAnnotation)
err := r.Update(ctx, host)
if err != nil {
return updated, fmt.Errorf("could not update removing hardwaredetails annotation: %w", err)
}
// In the case where the value was not just consumed, generate an event
if !updated {
r.publishEvent(ctx, request, host.NewEvent("RemoveAnnotation", "HardwareDetails annotation ignored, status already set and inspection is not disabled"))
}
}
return updated, nil
}
func logResult(info *reconcileInfo, result ctrl.Result) {
if result.Requeue || result.RequeueAfter != 0 ||
!slices.Contains(info.host.Finalizers,
metal3api.BareMetalHostFinalizer) {
info.log.Info("done",
"requeue", result.Requeue,
"after", result.RequeueAfter)
} else {
info.log.Info("stopping on host error",
"message", info.host.Status.ErrorMessage)
}
}
func recordActionFailure(info *reconcileInfo, errorType metal3api.ErrorType, errorMessage string) actionFailed {
setErrorMessage(info.host, errorType, errorMessage)
eventType := map[metal3api.ErrorType]string{
metal3api.DetachError: "DetachError",
metal3api.ProvisionedRegistrationError: "ProvisionedRegistrationError",
metal3api.RegistrationError: "RegistrationError",
metal3api.InspectionError: "InspectionError",
metal3api.ProvisioningError: "ProvisioningError",
metal3api.PowerManagementError: "PowerManagementError",
metal3api.PreparationError: "PreparationError",
metal3api.ServicingError: "ServicingError",
}[errorType]
counter := actionFailureCounters.WithLabelValues(eventType)
info.postSaveCallbacks = append(info.postSaveCallbacks, counter.Inc)
info.publishEvent(eventType, errorMessage)
return actionFailed{dirty: true, ErrorType: errorType, errorCount: info.host.Status.ErrorCount}
}
func recordActionDelayed(info *reconcileInfo, state metal3api.ProvisioningState) actionResult {
var counter prometheus.Counter
if state == metal3api.StateDeprovisioning {
counter = delayedDeprovisioningHostCounters.With(hostMetricLabels(info.request))
} else {
counter = delayedProvisioningHostCounters.With(hostMetricLabels(info.request))
}
info.postSaveCallbacks = append(info.postSaveCallbacks, counter.Inc)
info.host.SetOperationalStatus(metal3api.OperationalStatusDelayed)
return actionDelayed{}
}
func (r *BareMetalHostReconciler) credentialsErrorResult(ctx context.Context, err error, request ctrl.Request, host *metal3api.BareMetalHost) (ctrl.Result, error) {
// In the event a credential secret is defined, but we cannot find it
// we requeue the host as we will not know if they create the secret
// at some point in the future.
if errors.As(err, new(*ResolveBMCSecretRefError)) {
credentialsMissing.Inc()
saveErr := r.setErrorCondition(ctx, request, host, metal3api.RegistrationError, err.Error())
if saveErr != nil {
return ctrl.Result{Requeue: true}, saveErr
}
r.publishEvent(ctx, request, host.NewEvent("BMCCredentialError", err.Error()))
return ctrl.Result{Requeue: true, RequeueAfter: hostErrorRetryDelay}, nil
}
// If a managed Host is missing a BMC address or secret, or
// we have found the secret but it is missing the required fields,
// or the BMC address is defined but malformed, we set the
// host into an error state but we do not Requeue it
// as fixing the secret or the host BMC info will trigger
// the host to be reconciled again
if errors.As(err, new(*EmptyBMCAddressError)) || errors.As(err, new(*EmptyBMCSecretError)) ||
errors.As(err, new(*bmc.CredentialsValidationError)) || errors.As(err, new(*bmc.UnknownBMCTypeError)) {
credentialsInvalid.Inc()
saveErr := r.setErrorCondition(ctx, request, host, metal3api.RegistrationError, err.Error())
if saveErr != nil {
return ctrl.Result{Requeue: true}, saveErr
}
// Only publish the event if we do not have an error
// after saving so that we only publish one time.
r.publishEvent(ctx, request, host.NewEvent("BMCCredentialError", err.Error()))
return ctrl.Result{}, nil
}
unhandledCredentialsError.Inc()
return ctrl.Result{}, fmt.Errorf("an unhandled failure occurred with the BMC secret: %w", err)
}
// hasRebootAnnotation checks for existence of reboot annotations and returns true if at least one exist.
func hasRebootAnnotation(info *reconcileInfo, expectForce bool) (hasReboot bool, rebootMode metal3api.RebootMode) {
rebootMode = metal3api.RebootModeSoft
for annotation, value := range info.host.GetAnnotations() {
if isRebootAnnotation(annotation) {
newReboot := getRebootAnnotationArguments(value, info)
if expectForce && !newReboot.Force {
continue
}
hasReboot = true
// If any annotation has asked for a hard reboot, that
// mode takes precedence.
if newReboot.Mode == metal3api.RebootModeHard {
rebootMode = newReboot.Mode
}
// Don't use a break here as we may have multiple clients setting
// reboot annotations and we always want hard requests honoured
}
}
return
}
func getRebootAnnotationArguments(annotation string, info *reconcileInfo) (result metal3api.RebootAnnotationArguments) {
result.Mode = metal3api.RebootModeSoft
if annotation == "" {
info.log.Info("No reboot annotation value specified, assuming soft-reboot.")
return
}
err := json.Unmarshal([]byte(annotation), &result)
if err != nil {
info.publishEvent("InvalidAnnotationValue", fmt.Sprintf("could not parse reboot annotation (%s) - invalid json, assuming soft-reboot", annotation))
info.log.Info(fmt.Sprintf("Could not parse reboot annotation (%q) - invalid json, assuming soft-reboot", annotation))
return
}
return
}
// isRebootAnnotation returns true if the provided annotation is a reboot annotation (either suffixed or not).
func isRebootAnnotation(annotation string) bool {
return strings.HasPrefix(annotation, metal3api.RebootAnnotationPrefix+"/") || annotation == metal3api.RebootAnnotationPrefix
}
// clearRebootAnnotations deletes all reboot annotations exist on the provided host.
func clearRebootAnnotations(host *metal3api.BareMetalHost) (dirty bool) {
for annotation := range host.Annotations {
if isRebootAnnotation(annotation) {
delete(host.Annotations, annotation)
dirty = true
}
}
return
}
// inspectionRefreshRequested checks for existence of inspect.metal3.io
// annotation and returns true if it exist.
func inspectionRefreshRequested(host *metal3api.BareMetalHost) bool {
annotations := host.GetAnnotations()
if annotations != nil {
if expect, ok := annotations[metal3api.InspectAnnotationPrefix]; ok && expect != metal3api.InspectAnnotationValueDisabled {
return true
}
}
return false
}
// clearErrorWithStatus removes any existing error message and sets operational status.
func clearErrorWithStatus(host *metal3api.BareMetalHost, status metal3api.OperationalStatus) (dirty bool) {
dirty = host.SetOperationalStatus(status)
var emptyErrType metal3api.ErrorType
if host.Status.ErrorType != emptyErrType {
host.Status.ErrorType = emptyErrType
dirty = true
}
if host.Status.ErrorMessage != "" {
host.Status.ErrorMessage = ""
dirty = true
}
return dirty
}
// clearError removes any existing error message.
func clearError(host *metal3api.BareMetalHost) (dirty bool) {
return clearErrorWithStatus(host, metal3api.OperationalStatusOK)
}
// setErrorMessage updates the ErrorMessage in the host Status struct
// and increases the ErrorCount.
func setErrorMessage(host *metal3api.BareMetalHost, errType metal3api.ErrorType, message string) {
host.Status.OperationalStatus = metal3api.OperationalStatusError
host.Status.ErrorType = errType
host.Status.ErrorMessage = message
host.Status.ErrorCount++
}
func (r *BareMetalHostReconciler) actionPowerOffBeforeDeleting(ctx context.Context, prov provisioner.Provisioner, info *reconcileInfo) actionResult {
if info.host.Spec.DisablePowerOff {
info.log.Info("Skipping host powered off as Power Off has been disabled")
return actionComplete{}
}
info.log.Info("host ready to be powered off")
provResult, err := prov.PowerOff(
ctx,
metal3api.RebootModeHard,
info.host.Status.ErrorType == metal3api.PowerManagementError,
info.host.Spec.AutomatedCleaningMode)
if err != nil {
return actionError{fmt.Errorf("failed to power off before deleting node: %w", err)}
}
if provResult.ErrorMessage != "" {
return recordActionFailure(info, metal3api.PowerManagementError, provResult.ErrorMessage)
}
if provResult.Dirty {
result := actionContinue{provResult.RequeueAfter}
if clearError(info.host) {
return actionUpdate{result}
}
return result
}
return actionComplete{}
}
// Manage deletion of the host.
func (r *BareMetalHostReconciler) actionDeleting(ctx context.Context, prov provisioner.Provisioner, info *reconcileInfo) actionResult {
info.log.Info(
"marked to be deleted",
"timestamp", info.host.DeletionTimestamp,
)
// no-op if finalizer has been removed.
if !slices.Contains(info.host.Finalizers, metal3api.BareMetalHostFinalizer) {
info.log.Info("ready to be deleted")
return deleteComplete{}
}
provResult, err := prov.Delete(ctx)
if err != nil {
return actionError{fmt.Errorf("failed to delete: %w", err)}
}
if provResult.Dirty {
return actionContinue{provResult.RequeueAfter}
}
// Remove finalizer to allow deletion
secretManager := secretutils.NewSecretManager(info.log, r.Client, r.APIReader)
err = secretManager.ReleaseSecret(ctx, info.bmcCredsSecret)
if err != nil {
return actionError{err}
}
if controllerutil.RemoveFinalizer(info.host, metal3api.BareMetalHostFinalizer) {
info.log.Info("cleanup is complete, removed finalizer",
"remaining", info.host.Finalizers)
if err := r.Update(ctx, info.host); err != nil {
return actionError{fmt.Errorf("failed to remove finalizer: %w", err)}
}
}
return deleteComplete{}
}
func (r *BareMetalHostReconciler) actionUnmanaged(_ context.Context, _ provisioner.Provisioner, info *reconcileInfo) actionResult {
if info.host.HasBMCDetails() {
return actionComplete{}
}
return actionContinue{unmanagedRetryDelay}
}
// getCurrentImage() returns the current image that has been or is being
// provisioned.
func getCurrentImage(host *metal3api.BareMetalHost) *metal3api.Image {
// If an image is currently provisioned, return it
if host.Status.Provisioning.Image.URL != "" {
return host.Status.Provisioning.Image.DeepCopy()
}
// If we are in the process of provisioning an image, return that image
switch host.Status.Provisioning.State {
case metal3api.StateProvisioning, metal3api.StateExternallyProvisioned:
if host.Spec.Image != nil && host.Spec.Image.URL != "" {
return host.Spec.Image.DeepCopy()
}
default:
}
return nil
}
func hasCustomDeploy(host *metal3api.BareMetalHost) bool {
if host.Status.Provisioning.CustomDeploy != nil && host.Status.Provisioning.CustomDeploy.Method != "" {
return true
}
switch host.Status.Provisioning.State {
case metal3api.StateProvisioning, metal3api.StateExternallyProvisioned:
return host.Spec.CustomDeploy != nil && host.Spec.CustomDeploy.Method != ""
default:
return false
}
}
// detachHost() detaches the host from the Provisioner.
func (r *BareMetalHostReconciler) detachHost(ctx context.Context, prov provisioner.Provisioner, info *reconcileInfo) actionResult {
provResult, err := prov.Detach(ctx)
if err != nil {
return actionError{fmt.Errorf("failed to detach: %w", err)}
}
if provResult.ErrorMessage != "" {
return recordActionFailure(info, metal3api.DetachError, provResult.ErrorMessage)
}
if provResult.Dirty {
if info.host.Status.ErrorType == metal3api.DetachError && clearError(info.host) {
return actionUpdate{actionContinue{provResult.RequeueAfter}}
}
return actionContinue{provResult.RequeueAfter}
}
slowPoll := actionContinue{unmanagedRetryDelay}
if info.host.Status.ErrorType == metal3api.DetachError {
clearError(info.host)
info.host.Status.ErrorCount = 0
}
if info.host.SetOperationalStatus(metal3api.OperationalStatusDetached) {
info.log.Info("host is detached, removed from provisioner")
return actionUpdate{slowPoll}
}
return slowPoll
}
type imageBuildError struct {
Message string
}
func (ibe imageBuildError) Error() string {
return ibe.Message
}
func (r *BareMetalHostReconciler) preprovImageAvailable(ctx context.Context, info *reconcileInfo, image *metal3api.PreprovisioningImage) (bool, error) {
if image.Status.Architecture != image.Spec.Architecture {
info.log.Info("pre-provisioning image architecture mismatch",
"wanted", image.Spec.Architecture,
"current", image.Status.Architecture)
return false, nil
}
validFormat := slices.Contains(image.Spec.AcceptFormats, image.Status.Format)
if !validFormat {
info.log.Info("pre-provisioning image format not accepted",
"format", image.Status.Format)
return false, nil
}
if image.Spec.NetworkDataName != "" {
secretKey := client.ObjectKey{
Name: image.Spec.NetworkDataName,
Namespace: image.ObjectMeta.Namespace,
}
secretManager := r.secretManager(ctx, info.log)
networkData, err := secretManager.AcquireSecret(ctx, secretKey, info.host, false)
if err != nil {
return false, err
}
if image.Status.NetworkData.Version != networkData.GetResourceVersion() {
info.log.Info("network data in pre-provisioning image is out of date",
"latestVersion", networkData.GetResourceVersion(),
"currentVersion", image.Status.NetworkData.Version)
return false, nil
}
}
if image.Status.NetworkData.Name != image.Spec.NetworkDataName {
info.log.Info("network data location in pre-provisioning image is out of date")
return false, nil
}
if errCond := meta.FindStatusCondition(image.Status.Conditions, string(metal3api.ConditionImageError)); errCond != nil && errCond.Status == metav1.ConditionTrue {
info.log.Info("error building PreprovisioningImage",
"message", errCond.Message)
return false, imageBuildError{errCond.Message}
}
if readyCond := meta.FindStatusCondition(image.Status.Conditions, string(metal3api.ConditionImageReady)); readyCond != nil && readyCond.Status == metav1.ConditionTrue && readyCond.ObservedGeneration == image.Generation {
return true, nil
}
info.log.Info("pending PreprovisioningImage not ready")
return false, nil
}
// getControllerArchitecture returns the CPU architecture of the currently
// running Go program in a format that mimics the output of "uname -p".
func getControllerArchitecture() string {
switch runtime.GOARCH {
case "amd64":
return "x86_64"
case "arm64":
return "aarch64"
default:
return runtime.GOARCH
}
}
func getHostArchitecture(host *metal3api.BareMetalHost) string {
if host.Spec.Architecture != "" {
return host.Spec.Architecture
}
// FIXME(dtantsur): this relies on the essentially deprecated HardwareDetails field.
if host.Status.HardwareDetails != nil &&
host.Status.HardwareDetails.CPU.Arch != "" {
return host.Status.HardwareDetails.CPU.Arch
}
return getControllerArchitecture()
}
func (r *BareMetalHostReconciler) getPreprovImage(ctx context.Context, info *reconcileInfo, formats []metal3api.ImageFormat) (*provisioner.PreprovisioningImage, error) {
if formats == nil {
// No image build requested
return nil, nil //nolint:nilnil
}
if len(formats) == 0 {
return nil, imageBuildError{"no acceptable formats for preprovisioning image"}
}
expectedSpec := metal3api.PreprovisioningImageSpec{
NetworkDataName: info.host.Spec.PreprovisioningNetworkDataName,
Architecture: getHostArchitecture(info.host),
AcceptFormats: formats,
}
preprovImage := metal3api.PreprovisioningImage{}
key := client.ObjectKey{
Name: info.host.Name,
Namespace: info.host.Namespace,
}
err := r.Get(ctx, key, &preprovImage)
if k8serrors.IsNotFound(err) {
info.log.Info("creating new PreprovisioningImage")
preprovImage = metal3api.PreprovisioningImage{
ObjectMeta: metav1.ObjectMeta{
Name: key.Name,
Namespace: key.Namespace,
Labels: info.host.Labels,
},
Spec: expectedSpec,
}
err = controllerutil.SetControllerReference(info.host, &preprovImage, r.Scheme())
if err != nil {
return nil, fmt.Errorf("failed to set controller reference for PreprovisioningImage due to %w", err)
}
err = r.Create(ctx, &preprovImage)
return nil, err
}
if err != nil {
return nil, fmt.Errorf("failed to retrieve pre-provisioning image data: %w", err)
}
// If the PreprovisioningImage is being deleted, treat it as unavailable
if !preprovImage.DeletionTimestamp.IsZero() {
info.log.Info("PreprovisioningImage is being deleted, waiting for new one")
return nil, nil //nolint:nilnil
}
needsUpdate := false
if preprovImage.Labels == nil && len(info.host.Labels) > 0 {
preprovImage.Labels = make(map[string]string, len(info.host.Labels))
}
for k, v := range info.host.Labels {
if cur, ok := preprovImage.Labels[k]; !ok || cur != v {
preprovImage.Labels[k] = v
needsUpdate = true
}
}
if !apiequality.Semantic.DeepEqual(preprovImage.Spec, expectedSpec) {
info.log.Info("updating PreprovisioningImage spec")
preprovImage.Spec = expectedSpec
needsUpdate = true
}
if needsUpdate {
info.log.Info("updating PreprovisioningImage")
err = r.Update(ctx, &preprovImage)
return nil, err
}
if available, err := r.preprovImageAvailable(ctx, info, &preprovImage); err != nil || !available {
return nil, err
}
image := provisioner.PreprovisioningImage{
GeneratedImage: imageprovider.GeneratedImage{
ImageURL: preprovImage.Status.ImageUrl,
KernelURL: preprovImage.Status.KernelUrl,
ExtraKernelParams: preprovImage.Status.ExtraKernelParams,
},
Format: preprovImage.Status.Format,
}
info.log.Info("using PreprovisioningImage", "Image", image)
return &image, nil
}
// Test the credentials by connecting to the management controller.
func (r *BareMetalHostReconciler) registerHost(ctx context.Context, prov provisioner.Provisioner, info *reconcileInfo) actionResult {
info.log.V(1).Info("registering and validating access to management controller",
"credentials", info.host.Status.TriedCredentials)
dirty := false
credsChanged := !info.host.Status.TriedCredentials.Match(*info.bmcCredsSecret)
if credsChanged {
info.log.Info("new credentials")
info.host.UpdateTriedCredentials(*info.bmcCredsSecret)
info.postSaveCallbacks = append(info.postSaveCallbacks, updatedCredentials.Inc)
dirty = true
}
preprovImgFormats, err := prov.PreprovisioningImageFormats(ctx)
if err != nil {
return actionError{err}
}
switch info.host.Status.Provisioning.State {
case metal3api.StateRegistering, metal3api.StateDeleting, metal3api.StatePoweringOffBeforeDelete:
// No need to create PreprovisioningImage if host is not yet registered
preprovImgFormats = nil
case metal3api.StateProvisioned, metal3api.StateExternallyProvisioned:
// Provisioned hosts only need the image for servicing
if info.host.Status.OperationalStatus != metal3api.OperationalStatusServicing {
preprovImgFormats = nil
}
case metal3api.StateDeprovisioning:
// PreprovisioningImage is not required for deprovisioning when cleaning is disabled
if info.host.Spec.AutomatedCleaningMode == metal3api.CleaningModeDisabled {
preprovImgFormats = nil
}
default:
}
preprovImg, err := r.getPreprovImage(ctx, info, preprovImgFormats)
if err != nil {
if errors.As(err, &imageBuildError{}) {
return recordActionFailure(info, metal3api.RegistrationError, err.Error())
}
return actionError{err}
}
hostConf := &hostConfigData{
host: info.host,
log: info.log.WithName("host_config_data"),
secretManager: r.secretManager(ctx, info.log),
}
preprovisioningNetworkData, err := hostConf.PreprovisioningNetworkData(ctx)
if err != nil {
return recordActionFailure(info, metal3api.RegistrationError, "failed to read preprovisioningNetworkData")
}
provResult, provID, err := prov.Register(
ctx,
provisioner.ManagementAccessData{
BootMode: info.host.Status.Provisioning.BootMode,
AutomatedCleaningMode: info.host.Spec.AutomatedCleaningMode,
State: info.host.Status.Provisioning.State,
OperationalStatus: info.host.Status.OperationalStatus,
CurrentImage: getCurrentImage(info.host),
PreprovisioningImage: preprovImg,
PreprovisioningNetworkData: preprovisioningNetworkData,
HasCustomDeploy: hasCustomDeploy(info.host),
DisablePowerOff: info.host.Spec.DisablePowerOff,
CPUArchitecture: getHostArchitecture(info.host),
},
credsChanged,
info.host.Status.ErrorType == metal3api.RegistrationError)
if errors.Is(err, provisioner.ErrNeedsPreprovisioningImage) &&
preprovImgFormats != nil {
if preprovImg == nil {
waitingForPreprovImage.Inc()
return actionContinue{preprovImageRetryDelay}
}
return recordActionFailure(info, metal3api.RegistrationError,
"Preprovisioning Image is not acceptable to provisioner")
}
if err != nil {
noManagementAccess.Inc()
return actionError{fmt.Errorf("failed to validate BMC access: %w", err)}
}
if provResult.ErrorMessage != "" {
return recordActionFailure(info, metal3api.RegistrationError, provResult.ErrorMessage)
}
if provID != "" && info.host.Status.Provisioning.ID != provID {
info.log.Info("setting provisioning id", "ID", provID)
info.host.Status.Provisioning.ID = provID
if info.host.Status.Provisioning.State == metal3api.StatePreparing {
clearHostProvisioningSettings(info.host)
}
dirty = true
}
if provResult.Dirty {
info.log.Info("host not ready", "wait", provResult.RequeueAfter)
result := actionContinue{provResult.RequeueAfter}
if clearError(info.host) {
dirty = true
}
if dirty {
return actionUpdate{result}
}
return result
}
dirty, err = r.matchProfile(info)
if err != nil {
return recordActionFailure(info, metal3api.RegistrationError, err.Error())
}
if dirty {
return actionUpdate{}
}
// Check if the host can support firmware components before creating the resource
_, errGetFirmwareComponents := prov.GetFirmwareComponents(ctx)
supportsFirmwareComponents := !errors.Is(errGetFirmwareComponents, provisioner.ErrFirmwareUpdateUnsupported)
// Create the hostFirmwareSettings resource with same host name/namespace if it doesn't exist
// Create the hostFirmwareComponents resource with same host name/namespace if it doesn't exist
if info.host.Name != "" {
if !info.host.DeletionTimestamp.IsZero() {
info.log.Info("will not attempt to create new hostFirmwareSettings and hostFirmwareComponents in " + info.host.Namespace)
} else {
if err = r.createHostFirmwareSettings(ctx, info); err != nil {
info.log.Info("failed creating hostfirmwaresettings")
return actionError{fmt.Errorf("failed to validate BMC access: %w", err)}
}
if supportsFirmwareComponents {
if err = r.createHostFirmwareComponents(ctx, info); err != nil {
info.log.Info("failed creating hostfirmwarecomponents")
return actionError{fmt.Errorf("failed creating hostFirmwareComponents: %w", err)}
}
}
if _, err = r.acquireHostUpdatePolicy(ctx, info); err != nil {
info.log.Info("failed setting owner reference on hostupdatepolicy")
return actionError{fmt.Errorf("failed setting owner reference on hostUpdatePolicy: %w", err)}
}
}
}
// Reaching this point means the credentials are valid and worked,
// so clear any previous error and record the success in the
// status block.
registeredNewCreds := !info.host.Status.GoodCredentials.Match(*info.bmcCredsSecret)
if registeredNewCreds {
info.log.Info("updating credentials success status fields")
info.host.UpdateGoodCredentials(*info.bmcCredsSecret)
info.publishEvent("BMCAccessValidated", "Verified access to BMC")
dirty = true
} else {
info.log.V(1).Info("verified access to the BMC")
}
if info.host.Status.ErrorType == metal3api.RegistrationError || registeredNewCreds {
info.log.Info("clearing previous error message")
dirty = clearError(info.host)
}
if dirty {
return actionComplete{}
}
return nil
}
func updateRootDeviceHints(host *metal3api.BareMetalHost, info *reconcileInfo) (dirty bool, err error) {
// Ensure the root device hints we're going to use are stored.
//
// If the user has provided explicit root device hints, they take
// precedence. Otherwise use the values from the hardware profile.
hintSource := host.Spec.RootDeviceHints
if hintSource == nil {
hwProf, err := profile.GetProfile(host.HardwareProfile())
if err != nil {