-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathbiossettings_controller.go
More file actions
1490 lines (1334 loc) · 64.4 KB
/
biossettings_controller.go
File metadata and controls
1490 lines (1334 loc) · 64.4 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
// SPDX-FileCopyrightText: 2025 SAP SE or an SAP affiliate company and IronCore contributors
// SPDX-License-Identifier: Apache-2.0
package controller
import (
"context"
"errors"
"fmt"
"maps"
"slices"
"sort"
"strconv"
"time"
"github.com/ironcore-dev/metal-operator/bmc"
"github.com/stmcginnis/gofish/schemas"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/handler"
"github.com/ironcore-dev/controller-utils/clientutils"
"github.com/ironcore-dev/controller-utils/conditionutils"
metalv1alpha1 "github.com/ironcore-dev/metal-operator/api/v1alpha1"
"github.com/ironcore-dev/metal-operator/internal/bmcutils"
)
const (
BIOSSettingsFinalizer = "metal.ironcore.dev/biossettings"
BIOSVersionUpdateConditionPending = "BIOSVersionUpdatePending"
BIOSVersionUpgradeReasonPending = "BIOSVersionNeedsTObeUpgraded"
BIOSPendingSettingConditionCheck = "BIOSSettingsCheckPendingSettings"
BIOSPendingSettingsReasonFound = "BIOSPendingSettingsFound"
BIOSSettingsConditionDuplicateKey = "BIOSSettingsDuplicateKeys"
BIOSSettingsReasonFoundDuplicateKeys = "BIOSSettingsDuplicateKeysFound"
BIOSSettingConditionUpdateStartTime = "BIOSSettingUpdateStartTime"
BIOSSettingsReasonUpdateStartTime = "BIOSSettingsUpdateHasStarted"
BIOSSettingConditionUpdateTimedOut = "BIOSSettingsTimedOut"
BIOSSettingsReasonUpdateTimedOut = "BIOSSettingsTimedOutDuringUpdate"
BIOSSettingsConditionServerPowerOn = "ServerPowerOnCondition"
BIOSSettingsReasonServerPoweredOn = "ServerPoweredHasBeenPoweredOn"
BMCConditionReset = "BMCResetIssued"
BMCReasonReset = "BMCResetIssued"
BIOSSettingsConditionIssuedUpdate = "SettingsUpdateIssued"
BIOSSettingReasonIssuedUpdate = "BIOSSettingUpdateIssued"
BIOSSettingsConditionUnknownPendingSettings = "UnknownPendingSettingState"
BIOSSettingsReasonUnexpectedPendingSettings = "UnexpectedPendingSettingsPostUpdateHasBeenIssued"
BIOSSettingsConditionRebootPostUpdate = "ServerRebootPostUpdateHasBeenIssued"
BIOSSettingsReasonSkipReboot = "SkipServerRebootPostUpdateHasBeenIssued"
BIOSSettingsReasonRebootNeeded = "RebootPostSettingUpdate"
BIOSSettingsConditionRebootPowerOff = "RebootPowerOff"
BIOSSettingsReasonRebootServerPowerOff = "PowerOffCompletedDuringReboot"
BIOSSettingsConditionRebootPowerOn = "RebootPowerOn"
BIOSSettingsReasonRebootServerPowerOn = "PowerOnCompletedDuringReboot"
BIOSSettingsConditionVerifySettings = "VerifySettingsPostUpdate"
BIOSSettingsReasonVerificationCompleted = "VerificationCompleted"
BIOSSettingsReasonVerificationNotCompleted = "VerificationNotCompleted"
BIOSSettingsConditionWrongSettings = "SettingsProvidedNotValid"
BIOSSettingsReasonWrongSettings = "SettingsProvidedAreNotValid"
)
// BIOSSettingsReconciler reconciles a BIOSSettings object
type BIOSSettingsReconciler struct {
client.Client
ManagerNamespace string
DefaultProtocol metalv1alpha1.ProtocolScheme
SkipCertValidation bool
Scheme *runtime.Scheme
BMCOptions bmc.Options
ResyncInterval time.Duration
TimeoutExpiry time.Duration
Conditions *conditionutils.Accessor
}
// +kubebuilder:rbac:groups=metal.ironcore.dev,resources=biossettings,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=metal.ironcore.dev,resources=biossettings/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=metal.ironcore.dev,resources=biossettings/finalizers,verbs=update
// +kubebuilder:rbac:groups=metal.ironcore.dev,resources=servers,verbs=get;list;watch;update
// +kubebuilder:rbac:groups=metal.ironcore.dev,resources=BMC,verbs=get;list;watch;update
// +kubebuilder:rbac:groups=metal.ironcore.dev,resources=servermaintenances,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=metal.ironcore.dev,resources=servermaintenances/status,verbs=get;update;patch
// +kubebuilder:rbac:groups="",resources=secrets,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups="batch",resources=jobs,verbs=get;list;watch;create;update;patch;delete
// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
func (r *BIOSSettingsReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
biosSettings := &metalv1alpha1.BIOSSettings{}
if err := r.Get(ctx, req.NamespacedName, biosSettings); err != nil {
return ctrl.Result{}, client.IgnoreNotFound(err)
}
return r.reconcileExists(ctx, biosSettings)
}
func (r *BIOSSettingsReconciler) reconcileExists(ctx context.Context, settings *metalv1alpha1.BIOSSettings) (ctrl.Result, error) {
if r.shouldDelete(ctx, settings) {
return r.delete(ctx, settings)
}
return r.reconcile(ctx, settings)
}
func (r *BIOSSettingsReconciler) shouldDelete(ctx context.Context, settings *metalv1alpha1.BIOSSettings) bool {
log := ctrl.LoggerFrom(ctx)
if settings.DeletionTimestamp.IsZero() {
return false
}
log.V(1).Info("Reconciling BIOSSettings")
if controllerutil.ContainsFinalizer(settings, BIOSSettingsFinalizer) &&
settings.Status.State == metalv1alpha1.BIOSSettingsStateInProgress {
log.V(1).Info("Postponing delete as BIOSSettings update is in progress")
return false
}
return true
}
func (r *BIOSSettingsReconciler) delete(ctx context.Context, settings *metalv1alpha1.BIOSSettings) (ctrl.Result, error) {
log := ctrl.LoggerFrom(ctx)
log.V(1).Info("Deleting BIOSSettings")
if err := r.cleanupReferences(ctx, settings); err != nil {
return ctrl.Result{}, fmt.Errorf("failed to cleanup references: %w", err)
}
log.V(1).Info("Ensured references were removed")
log.V(1).Info("Ensuring that the finalizer is removed")
if modified, err := clientutils.PatchEnsureNoFinalizer(ctx, r.Client, settings, BIOSSettingsFinalizer); err != nil || modified {
return ctrl.Result{}, err
}
log.V(1).Info("Ensured that the finalizer is removed")
log.V(1).Info("BIOSSettings is deleted")
return ctrl.Result{}, nil
}
func (r *BIOSSettingsReconciler) removeServerMaintenance(ctx context.Context, settings *metalv1alpha1.BIOSSettings) error {
log := ctrl.LoggerFrom(ctx)
if settings.Spec.ServerMaintenanceRef == nil {
return nil
}
maintenance, err := GetServerMaintenanceForObjectReference(ctx, r.Client, settings.Spec.ServerMaintenanceRef)
if err != nil && !apierrors.IsNotFound(err) {
return fmt.Errorf("failed to get ServerMaintenance for BIOSSettings: %w", err)
}
var condition *metav1.Condition
if err == nil && maintenance.DeletionTimestamp.IsZero() {
if metav1.IsControlledBy(maintenance, settings) {
log.V(1).Info("Deleting ServerMaintenance", "ServerMaintenance", client.ObjectKeyFromObject(maintenance), "State", maintenance.Status.State)
condition, err = GetCondition(r.Conditions, settings.Status.Conditions, ServerMaintenanceConditionDeleted)
if err != nil {
return fmt.Errorf("failed to get the delete condition for ServerMaintenance: %w", err)
}
if err := r.Conditions.Update(
condition,
conditionutils.UpdateStatus(corev1.ConditionTrue),
conditionutils.UpdateReason(ServerMaintenanceReasonDeleted),
conditionutils.UpdateMessage(fmt.Sprintf("Deleting %s", maintenance.Name)),
); err != nil {
return fmt.Errorf("failed to update deleting ServerMaintenance condition: %w", err)
}
if err := r.Delete(ctx, maintenance); err != nil {
return err
}
} else {
log.V(1).Info("ServerMaintenance is owned by someone else", "ServerMaintenance", client.ObjectKeyFromObject(maintenance), "State", maintenance.Status.State)
}
}
if apierrors.IsNotFound(err) || err == nil {
log.V(1).Info("Cleaning up ServerMaintenance ref in BIOSSettings as the object is gone")
if err := r.patchMaintenanceRef(ctx, settings, nil); err != nil {
return fmt.Errorf("failed to remove the ServerMaintenance reference in BIOSSettings status: %w", err)
}
// Update condition to reflect deletion
if err := r.updateStatus(ctx, settings, settings.Status.State, condition); err != nil {
return fmt.Errorf("failed to patch BIOSSettings conditions: %w", err)
}
}
return nil
}
func (r *BIOSSettingsReconciler) cleanupReferences(ctx context.Context, settings *metalv1alpha1.BIOSSettings) (err error) {
log := ctrl.LoggerFrom(ctx)
if settings.Spec.ServerRef == nil {
log.V(1).Info("BIOSSettings does not have a ServerRef")
return nil
}
server, err := GetServerByName(ctx, r.Client, settings.Spec.ServerRef.Name)
if apierrors.IsNotFound(err) {
log.V(1).Info("Referred Server is gone")
return nil
}
if err != nil {
return err
}
if server.Spec.BIOSSettingsRef == nil {
log.V(1).Info("Server does not have a BIOSSettingsRef")
return nil
}
if server.Spec.BIOSSettingsRef.Name != settings.Name {
return nil
}
return r.patchBIOSSettingsRefForServer(ctx, server, nil)
}
func (r *BIOSSettingsReconciler) reconcile(ctx context.Context, settings *metalv1alpha1.BIOSSettings) (ctrl.Result, error) {
log := ctrl.LoggerFrom(ctx)
if shouldIgnoreReconciliation(settings) {
log.V(1).Info("Skipping BIOSSettings reconciliation")
return ctrl.Result{}, nil
}
if settings.Spec.ServerRef == nil {
log.V(1).Info("BIOSSettings does not have a ServerRef")
return ctrl.Result{}, nil
}
server, err := GetServerByName(ctx, r.Client, settings.Spec.ServerRef.Name)
if err != nil {
if apierrors.IsNotFound(err) {
log.V(1).Info("Server not found", "ServerName", settings.Spec.ServerRef.Name)
if err := r.updateStatus(ctx, settings, metalv1alpha1.BIOSSettingsStatePending, nil); err != nil {
return ctrl.Result{}, err
}
return ctrl.Result{}, nil
}
return ctrl.Result{}, err
}
if server.Spec.BIOSSettingsRef == nil {
if err := r.patchBIOSSettingsRefForServer(ctx, server, settings); err != nil {
return ctrl.Result{}, err
}
} else if server.Spec.BIOSSettingsRef.Name != settings.Name {
referredBIOSSetting, err := r.getBIOSSettingsByName(ctx, server.Spec.BIOSSettingsRef.Name)
if err != nil {
if apierrors.IsNotFound(err) {
log.V(1).Info("Referred server contains reference to non-existing BIOSSettings object, updating reference to the current BIOSSettings")
if err := r.patchBIOSSettingsRefForServer(ctx, server, settings); err != nil {
return ctrl.Result{}, err
}
// need to requeue to make sure that reconcile re-happens here. updating server object does not trigger reconcile here.
return ctrl.Result{RequeueAfter: r.ResyncInterval}, nil
}
log.V(1).Info("Server contains a reference to a different BIOSSettings object", "BIOSSettings", server.Spec.BIOSSettingsRef.Name)
return ctrl.Result{}, err
}
// Check if the current BIOSSettings version is newer and update reference if it is newer
// todo : handle version checks correctly
if referredBIOSSetting.Spec.Version < settings.Spec.Version {
log.V(1).Info("Updating BIOSSettings reference to the latest BIOS version")
if err := r.patchBIOSSettingsRefForServer(ctx, server, settings); err != nil {
return ctrl.Result{}, err
}
}
}
if modified, err := clientutils.PatchEnsureFinalizer(ctx, r.Client, settings, BIOSSettingsFinalizer); err != nil || modified {
return ctrl.Result{}, err
}
bmcClient, err := bmcutils.GetBMCClientForServer(ctx, r.Client, server, r.DefaultProtocol, r.SkipCertValidation, r.BMCOptions)
if err != nil {
if errors.As(err, &bmcutils.BMCUnAvailableError{}) {
log.V(1).Info("BMC is not available", "BMC", server.Spec.BMCRef.Name, "Server", server.Name, "Message", err.Error())
return ctrl.Result{RequeueAfter: r.ResyncInterval}, nil
}
return ctrl.Result{}, fmt.Errorf("failed to get BMC client for server: %w", err)
}
defer bmcClient.Logout()
return r.ensureBIOSSettingsStateTransition(ctx, bmcClient, settings, server)
}
func (r *BIOSSettingsReconciler) ensureBIOSSettingsStateTransition(ctx context.Context, bmcClient bmc.BMC, settings *metalv1alpha1.BIOSSettings, server *metalv1alpha1.Server) (ctrl.Result, error) {
switch settings.Status.State {
case "", metalv1alpha1.BIOSSettingsStatePending:
return r.handleSettingPendingState(ctx, bmcClient, settings, server)
case metalv1alpha1.BIOSSettingsStateInProgress:
return r.handleSettingInProgressState(ctx, bmcClient, settings, server)
case metalv1alpha1.BIOSSettingsStateApplied:
return r.handleAppliedState(ctx, bmcClient, settings, server)
case metalv1alpha1.BIOSSettingsStateFailed:
return r.handleFailedState(ctx, settings, server)
default:
return ctrl.Result{}, fmt.Errorf("invalid BIOSSettings state: %s", settings.Status.State)
}
}
func (r *BIOSSettingsReconciler) handleSettingPendingState(ctx context.Context, bmcClient bmc.BMC, settings *metalv1alpha1.BIOSSettings, server *metalv1alpha1.Server) (ctrl.Result, error) {
log := ctrl.LoggerFrom(ctx)
if len(settings.Spec.SettingsFlow) == 0 {
log.V(1).Info("Skipping BIOSSettings because no settings flow found")
return ctrl.Result{}, r.updateStatus(ctx, settings, metalv1alpha1.BIOSSettingsStateApplied, nil)
}
pendingSettings, err := r.getPendingBIOSSettings(ctx, bmcClient, server)
if err != nil {
return ctrl.Result{}, fmt.Errorf("failed to get pending BIOS settings: %w", err)
}
if len(pendingSettings) > 0 {
log.V(1).Info("Pending BIOS setting tasks found", "TaskCount", len(pendingSettings))
pendingSettingStateCheckCondition, err := GetCondition(r.Conditions, settings.Status.Conditions, BIOSPendingSettingConditionCheck)
if err != nil {
return ctrl.Result{}, fmt.Errorf("failed to get Condition for pending BIOSSettings state %w", err)
}
if err := r.Conditions.Update(
pendingSettingStateCheckCondition,
conditionutils.UpdateStatus(corev1.ConditionTrue),
conditionutils.UpdateReason(BIOSPendingSettingsReasonFound),
conditionutils.UpdateMessage(fmt.Sprintf("Found pending BIOS settings (%d)", len(pendingSettings))),
); err != nil {
return ctrl.Result{}, fmt.Errorf("failed to update pending BIOSSettings update condition: %w", err)
}
return ctrl.Result{}, r.updateStatus(ctx, settings, metalv1alpha1.BIOSSettingsStateFailed, pendingSettingStateCheckCondition)
}
// Verify that no duplicate name and duplicate settings are found
allNames := map[string]struct{}{}
allSettingsNames := map[string]struct{}{}
duplicateName := make([]string, 0, len(settings.Spec.SettingsFlow))
var duplicateSettingsNames []string
for _, flowItem := range settings.Spec.SettingsFlow {
if _, ok := allNames[flowItem.Name]; ok {
duplicateName = append(duplicateName, flowItem.Name)
}
allNames[flowItem.Name] = struct{}{}
for key := range flowItem.Settings {
if _, ok := allSettingsNames[key]; ok {
duplicateSettingsNames = append(duplicateSettingsNames, key)
}
allSettingsNames[key] = struct{}{}
}
}
if len(duplicateName) > 0 || len(duplicateSettingsNames) > 0 {
log.V(1).Info("Found duplicate keys", "DuplicatesCount", len(duplicateName), "DuplicatesSettingsCound", len(duplicateSettingsNames))
duplicateCheckCondition, err := GetCondition(r.Conditions, settings.Status.Conditions, BIOSSettingsConditionDuplicateKey)
if err != nil {
return ctrl.Result{}, fmt.Errorf("failed to get Condition for pending BIOSSettings state %w", err)
}
if err := r.Conditions.Update(
duplicateCheckCondition,
conditionutils.UpdateStatus(corev1.ConditionTrue),
conditionutils.UpdateReason(BIOSSettingsReasonFoundDuplicateKeys),
conditionutils.UpdateMessage(fmt.Sprintf("Found duplicate keys (%d) and settings (%d)", len(duplicateName), len(duplicateSettingsNames))),
); err != nil {
return ctrl.Result{}, fmt.Errorf("failed to update pending BIOSSettings update condition: %w", err)
}
return ctrl.Result{}, r.updateStatus(ctx, settings, metalv1alpha1.BIOSSettingsStateFailed, duplicateCheckCondition)
}
// Check if all settings have been applied
biosVersion, settingsDiff, err := r.getBIOSVersionAndSettingsDiff(ctx, bmcClient, settings, server)
if err != nil {
return ctrl.Result{}, fmt.Errorf("failed to get BIOSSettings: %w", err)
}
// if setting is not different, complete the BIOS tasks, does not matter if the bios version do not match
// if conditions are present, skip this shortcut to be able to capture all conditions states (ex: verifySetting, reboot etc)
if len(settingsDiff) == 0 && len(settings.Status.Conditions) == 0 {
// move status to completed
verifySettingUpdate, err := GetCondition(r.Conditions, settings.Status.Conditions, BIOSSettingsConditionVerifySettings)
if err != nil {
return ctrl.Result{}, fmt.Errorf("failed to get Condition for verified BIOSSettings condition %w", err)
}
// move biosSettings state to completed
if err := r.Conditions.Update(
verifySettingUpdate,
conditionutils.UpdateStatus(corev1.ConditionTrue),
conditionutils.UpdateReason(BIOSSettingsReasonVerificationCompleted),
conditionutils.UpdateMessage("Required BIOS settings has been verified on the server"),
); err != nil {
return ctrl.Result{}, fmt.Errorf("failed to update verify biossetting condition: %w", err)
}
return ctrl.Result{}, r.updateStatus(ctx, settings, metalv1alpha1.BIOSSettingsStateApplied, verifySettingUpdate)
}
var state = metalv1alpha1.BIOSSettingsStateInProgress
var condition *metav1.Condition
if biosVersion != settings.Spec.Version {
versionCheckCondition, err := GetCondition(r.Conditions, settings.Status.Conditions, BIOSVersionUpdateConditionPending)
if err != nil {
return ctrl.Result{}, fmt.Errorf("failed to get Condition for pending BIOSVersion update state: %w", err)
}
if versionCheckCondition.Status == metav1.ConditionTrue {
log.V(1).Info("Pending BIOS version upgrade.", "current bios Version", biosVersion, "required version", settings.Spec.Version)
return ctrl.Result{}, nil
}
if err := r.Conditions.Update(
versionCheckCondition,
conditionutils.UpdateStatus(corev1.ConditionTrue),
conditionutils.UpdateReason(BIOSVersionUpgradeReasonPending),
conditionutils.UpdateMessage(fmt.Sprintf("Waiting to update biosVersion: %s, current biosVersion: %s", settings.Spec.Version, biosVersion)),
); err != nil {
return ctrl.Result{}, fmt.Errorf("failed to update Pending BIOSVersion update condition: %w", err)
}
state = metalv1alpha1.BIOSSettingsStatePending
condition = versionCheckCondition
}
return ctrl.Result{}, r.updateStatus(ctx, settings, state, condition)
}
func (r *BIOSSettingsReconciler) handleSettingInProgressState(ctx context.Context, bmcClient bmc.BMC, settings *metalv1alpha1.BIOSSettings, server *metalv1alpha1.Server) (ctrl.Result, error) {
log := ctrl.LoggerFrom(ctx)
if req, err := r.requestMaintenanceForServer(ctx, settings, server); err != nil || req {
return ctrl.Result{}, err
}
condition, err := GetCondition(r.Conditions, settings.Status.Conditions, ServerMaintenanceConditionWaiting)
if err != nil {
return ctrl.Result{}, err
}
if ok := r.isServerInMaintenance(ctx, settings, server); !ok {
log.V(1).Info("Server is not yet in Maintenance status, skipping")
if condition.Status != metav1.ConditionTrue {
if err := r.Conditions.Update(
condition,
conditionutils.UpdateStatus(corev1.ConditionTrue),
conditionutils.UpdateReason(ServerMaintenanceReasonWaiting),
conditionutils.UpdateMessage(fmt.Sprintf("Waiting for approval of %v", settings.Spec.ServerMaintenanceRef.Name)),
); err != nil {
return ctrl.Result{}, fmt.Errorf("failed to update creating ServerMaintenance condition: %w", err)
}
if err := r.updateStatus(ctx, settings, settings.Status.State, condition); err != nil {
return ctrl.Result{}, fmt.Errorf("failed to patch BIOSSettings ServerMaintenance waiting conditions: %w", err)
}
}
return ctrl.Result{}, nil
}
// once in maintenance, clear the waiting condition if present
if condition.Reason != ServerMaintenanceReasonApproved {
if err := r.Conditions.Update(
condition,
conditionutils.UpdateStatus(corev1.ConditionFalse),
conditionutils.UpdateReason(ServerMaintenanceReasonApproved),
conditionutils.UpdateMessage("Server is now in Maintenance mode"),
); err != nil {
return ctrl.Result{}, fmt.Errorf("failed to update creating ServerMaintenance condition: %w", err)
}
if err := r.updateStatus(ctx, settings, settings.Status.State, condition); err != nil {
return ctrl.Result{}, fmt.Errorf("failed to patch BIOSSettings ServerMaintenance waiting conditions: %w", err)
}
return ctrl.Result{}, nil
}
if ok, err := r.handleBMCReset(ctx, bmcClient, settings, server); !ok || err != nil {
return ctrl.Result{}, err
}
settingsFlow := append([]metalv1alpha1.SettingsFlowItem{}, settings.Spec.SettingsFlow...)
sort.Slice(settingsFlow, func(i, j int) bool {
return settingsFlow[i].Priority <= settingsFlow[j].Priority
})
// loop through all the sequence in priority order and verify/Apply the settings
for _, settingsFlowItem := range settingsFlow {
// check each setting in the order of priority apply and verify it
currentSettingsFlowStatus := r.getFlowItemFromSettingsStatus(settings, &settingsFlowItem)
// if the setting state is not found, create it
if currentSettingsFlowStatus == nil {
currentSettingsFlowStatus = &metalv1alpha1.BIOSSettingsFlowStatus{
Priority: settingsFlowItem.Priority,
Name: settingsFlowItem.Name,
}
return ctrl.Result{}, r.updateFlowStatus(ctx, settings, metalv1alpha1.BIOSSettingsFlowStateInProgress, currentSettingsFlowStatus, nil)
}
// if the state is InProgress, go ahead and apply/Verify the settings
if currentSettingsFlowStatus.State != metalv1alpha1.BIOSSettingsFlowStateInProgress {
// else, check if the settings is still as expected, and proceed.
settingsDiff, err := r.getSettingsDiff(ctx, bmcClient, settingsFlowItem.Settings, server)
if err != nil {
return ctrl.Result{}, fmt.Errorf("failed get current BIOS settings difference: %w", err)
}
if len(settingsDiff) > 0 {
log.V(1).Info("Found BIOSSettings difference on Server", "Server", server.Name, "SettingsDifference", settingsDiff)
}
// Handle if no setting update is needed
if len(settingsDiff) == 0 {
// if the state reflects it move on
if currentSettingsFlowStatus.State == metalv1alpha1.BIOSSettingsFlowStateApplied {
continue
}
// mark completed, and move on
verifySettingUpdate, err := GetCondition(r.Conditions, currentSettingsFlowStatus.Conditions, BIOSSettingsConditionVerifySettings)
if err != nil {
return ctrl.Result{}, fmt.Errorf("failed to get Condition for verified BIOSSettings condition: %w", err)
}
// move biosSettings state to completed
if err := r.Conditions.Update(
verifySettingUpdate,
conditionutils.UpdateStatus(corev1.ConditionTrue),
conditionutils.UpdateReason(BIOSSettingsReasonVerificationCompleted),
conditionutils.UpdateMessage("Required BIOS settings has been RE verified on the server. Hence, moving out of Pending state"),
); err != nil {
return ctrl.Result{}, fmt.Errorf("failed to update verified BIOSSettings condition: %w", err)
}
return ctrl.Result{}, r.updateFlowStatus(ctx, settings, metalv1alpha1.BIOSSettingsFlowStateApplied, currentSettingsFlowStatus, verifySettingUpdate)
}
// If the BIOS settings are different and the status was previously applied,
// make sure to reapply settings, reset any other InProgress state for higher Priority Settings.
if currentSettingsFlowStatus.State == metalv1alpha1.BIOSSettingsFlowStateApplied {
// update the state to reflect the current settings we are about to apply
// may be added condition to indicate the reapply
return ctrl.Result{}, r.updateFlowStatus(ctx, settings, metalv1alpha1.BIOSSettingsFlowStateInProgress, currentSettingsFlowStatus, nil)
}
}
if ok, err := r.applySettingUpdate(ctx, bmcClient, settings, &settingsFlowItem, currentSettingsFlowStatus, server); ok && err == nil {
if requeue, err := r.verifySettingsUpdateComplete(ctx, bmcClient, settings, &settingsFlowItem, currentSettingsFlowStatus, server); requeue && err == nil {
return ctrl.Result{RequeueAfter: r.ResyncInterval}, err
}
return ctrl.Result{}, err
} else {
return ctrl.Result{}, err
}
}
return ctrl.Result{}, r.updateStatus(ctx, settings, metalv1alpha1.BIOSSettingsStateApplied, nil)
}
func (r *BIOSSettingsReconciler) handleBMCReset(ctx context.Context, bmcClient bmc.BMC, settings *metalv1alpha1.BIOSSettings, server *metalv1alpha1.Server) (bool, error) {
log := ctrl.LoggerFrom(ctx)
resetBMC, err := GetCondition(r.Conditions, settings.Status.Conditions, BMCConditionReset)
if err != nil {
return false, fmt.Errorf("failed to get condition for reset of BMC of server %v", err)
}
if resetBMC.Status != metav1.ConditionTrue {
// once the server is powered on, reset the BMC to make sure its in stable state
// this avoids problems with some BMCs that hang up in subsequent operations
if resetBMC.Reason != BMCReasonReset {
if err := resetBMCOfServer(ctx, r.Client, server, bmcClient); err == nil {
// mark reset to be issued, wait for next reconcile
if err := r.Conditions.Update(
resetBMC,
conditionutils.UpdateStatus(corev1.ConditionFalse),
conditionutils.UpdateReason(BMCReasonReset),
conditionutils.UpdateMessage("Issued BMC reset to stabilize BMC of the server"),
); err != nil {
return false, fmt.Errorf("failed to update reset BMC condition: %w", err)
}
return false, r.updateStatus(ctx, settings, settings.Status.State, resetBMC)
} else {
return false, fmt.Errorf("failed to reset BMC: %w", err)
}
} else if server.Spec.BMCRef != nil {
// we need to wait until the BMC resource annotation is removed
bmcObj := &metalv1alpha1.BMC{}
if err := r.Get(ctx, client.ObjectKey{Name: server.Spec.BMCRef.Name}, bmcObj); err != nil {
return false, err
}
annotations := bmcObj.GetAnnotations()
if op, ok := annotations[metalv1alpha1.OperationAnnotation]; ok {
if op == metalv1alpha1.GracefulRestartBMC {
log.V(1).Info("Waiting for BMC reset as annotation on BMC object is set")
return false, nil
}
}
}
if err := r.Conditions.Update(
resetBMC,
conditionutils.UpdateStatus(corev1.ConditionTrue),
conditionutils.UpdateReason(BMCReasonReset),
conditionutils.UpdateMessage("BMC reset to stabilize BMC of the server is completed"),
); err != nil {
return false, fmt.Errorf("failed to update power on server condition: %w", err)
}
return false, r.updateStatus(ctx, settings, settings.Status.State, resetBMC)
}
return true, nil
}
func (r *BIOSSettingsReconciler) applySettingUpdate(ctx context.Context, bmcClient bmc.BMC, settings *metalv1alpha1.BIOSSettings, flowItem *metalv1alpha1.SettingsFlowItem, flowStatus *metalv1alpha1.BIOSSettingsFlowStatus, server *metalv1alpha1.Server) (bool, error) {
log := ctrl.LoggerFrom(ctx)
if modified, err := r.setTimeoutForAppliedSettings(ctx, settings, flowStatus); modified || err != nil {
return false, err
}
turnOnServer, err := GetCondition(r.Conditions, flowStatus.Conditions, BIOSSettingsConditionServerPowerOn)
if err != nil {
return false, fmt.Errorf("failed to get Condition for Initial powerOn of server %v", err)
}
if turnOnServer.Status != metav1.ConditionTrue {
if r.isServerInPowerState(server, metalv1alpha1.ServerOnPowerState) {
if err := r.Conditions.Update(
turnOnServer,
conditionutils.UpdateStatus(corev1.ConditionTrue),
conditionutils.UpdateReason(BIOSSettingsReasonServerPoweredOn),
conditionutils.UpdateMessage("Server is powered On to start the biosUpdate process"),
); err != nil {
return false, fmt.Errorf("failed to update power on server condition: %w", err)
}
return false, r.updateFlowStatus(ctx, settings, flowStatus.State, flowStatus, turnOnServer)
}
// we need to request maintenance to get the server to power-On to apply the BIOS settings
if settings.Spec.ServerMaintenanceRef == nil {
log.V(1).Info("Server powered off, request maintenance to turn the server On")
if requeue, err := r.requestMaintenanceForServer(ctx, settings, server); err != nil || requeue {
return false, err
}
}
if err := r.patchPowerState(ctx, settings, metalv1alpha1.PowerOn); err != nil {
return false, fmt.Errorf("failed to power on Server %w", err)
}
log.V(1).Info("Reconciled BIOSSettings at TurnOnServer Condition")
return false, err
}
// check if we have already determined if we need reboot of not.
// if the condition is present, we have checked the skip reboot condition.
condFound, err := r.Conditions.FindSlice(flowStatus.Conditions, BIOSSettingsConditionRebootPostUpdate, &metav1.Condition{})
if err != nil {
return false, fmt.Errorf("failed to find Condition %v. error: %v", BIOSSettingsConditionRebootPostUpdate, err)
}
if !condFound {
log.V(1).Info("Verify if the current Settings needs reboot of server")
settingsDiff, err := r.getSettingsDiff(ctx, bmcClient, flowItem.Settings, server)
if err != nil {
return false, fmt.Errorf("failed to get BIOS settings difference: %w", err)
}
if len(settingsDiff) > 0 {
log.V(1).Info("Found BIOSSettings difference on Server", "Server", server.Name, "SettingsDifference", settingsDiff)
}
resetReq, err := bmcClient.CheckBiosAttributes(settingsDiff)
if err != nil {
log.Error(err, "could not validate settings and determine if reboot needed")
var invalidSettingsErr *bmc.InvalidBIOSSettingsError
if errors.As(err, &invalidSettingsErr) {
inValidSettings, errCond := GetCondition(r.Conditions, flowStatus.Conditions, BIOSSettingsConditionWrongSettings)
if errCond != nil {
return false, fmt.Errorf("failed to get Condition for skip reboot post setting update %v", err)
}
if errCond := r.Conditions.Update(
inValidSettings,
conditionutils.UpdateStatus(corev1.ConditionTrue),
conditionutils.UpdateReason(BIOSSettingsReasonWrongSettings),
conditionutils.UpdateMessage(fmt.Sprintf("Settings provided is invalid. error: %v", err)),
); errCond != nil {
return false, fmt.Errorf("failed to update Invalid Settings condition: %w", errCond)
}
err = r.updateFlowStatus(ctx, settings, metalv1alpha1.BIOSSettingsFlowStateFailed, flowStatus, inValidSettings)
return false, errors.Join(err, r.updateStatus(ctx, settings, metalv1alpha1.BIOSSettingsStateFailed, nil))
}
return false, err
}
skipReboot, err := GetCondition(r.Conditions, flowStatus.Conditions, BIOSSettingsConditionRebootPostUpdate)
if err != nil {
return false, fmt.Errorf("failed to get Condition for skip reboot post setting update %v", err)
}
// if we dont need reboot. skip reboot steps.
if !resetReq {
log.V(1).Info("BIOSSettings update does not need reboot")
if err := r.Conditions.Update(
skipReboot,
conditionutils.UpdateStatus(corev1.ConditionTrue),
conditionutils.UpdateReason(BIOSSettingsReasonSkipReboot),
conditionutils.UpdateMessage("Settings provided does not need server reboot"),
); err != nil {
return false, fmt.Errorf("failed to update skip reboot condition: %w", err)
}
} else {
if err := r.Conditions.Update(
skipReboot,
conditionutils.UpdateStatus(corev1.ConditionFalse),
conditionutils.UpdateReason(BIOSSettingsReasonRebootNeeded),
conditionutils.UpdateMessage("Settings provided needs server reboot"),
); err != nil {
return false, fmt.Errorf("failed to update skip reboot condition: %w", err)
}
}
err = r.updateFlowStatus(ctx, settings, flowStatus.State, flowStatus, skipReboot)
log.V(1).Info("Reconciled biosSettings at check if reboot is needed")
return false, err
}
issueBiosUpdate, err := GetCondition(r.Conditions, flowStatus.Conditions, BIOSSettingsConditionIssuedUpdate)
if err != nil {
return false, fmt.Errorf("failed to get Condition for issuing BIOSSetting update to server %v", err)
}
if issueBiosUpdate.Status != metav1.ConditionTrue {
return false, r.applyBIOSSettings(ctx, bmcClient, settings, flowItem, flowStatus, server, issueBiosUpdate)
}
skipReboot, err := GetCondition(r.Conditions, flowStatus.Conditions, BIOSSettingsConditionRebootPostUpdate)
if err != nil {
return false, fmt.Errorf("failed to get Condition for reboot needed condition %v", err)
}
if skipReboot.Status != metav1.ConditionTrue {
rebootPowerOnCondition, err := GetCondition(r.Conditions, flowStatus.Conditions, BIOSSettingsConditionRebootPowerOn)
if err != nil {
return false, fmt.Errorf("failed to get Condition for reboot PowerOn condition %v", err)
}
// reboot is not yet completed
if rebootPowerOnCondition.Status != metav1.ConditionTrue {
return false, r.rebootServer(ctx, settings, flowStatus, server)
}
}
return true, nil
}
func (r *BIOSSettingsReconciler) setTimeoutForAppliedSettings(ctx context.Context, settings *metalv1alpha1.BIOSSettings, flowStatus *metalv1alpha1.BIOSSettingsFlowStatus) (bool, error) {
log := ctrl.LoggerFrom(ctx)
timeoutCheck, err := GetCondition(r.Conditions, flowStatus.Conditions, BIOSSettingConditionUpdateStartTime)
if err != nil {
return false, fmt.Errorf("failed to get condition for TimeOut during setting update %v", err)
}
if timeoutCheck.Status != metav1.ConditionTrue {
if err := r.Conditions.Update(
timeoutCheck,
conditionutils.UpdateStatus(corev1.ConditionTrue),
conditionutils.UpdateReason(BIOSSettingsReasonUpdateStartTime),
conditionutils.UpdateMessage("Settings are being updated on Server. Timeout will occur beyond this point if settings are not applied"),
); err != nil {
return false, fmt.Errorf("failed to update starting setting update condition: %w", err)
}
return true, r.updateFlowStatus(ctx, settings, flowStatus.State, flowStatus, timeoutCheck)
} else {
startTime := timeoutCheck.LastTransitionTime.Time
if time.Now().After(startTime.Add(r.TimeoutExpiry)) {
log.V(1).Info("Timeout while updating the biosSettings")
timedOut, err := GetCondition(r.Conditions, flowStatus.Conditions, BIOSSettingConditionUpdateTimedOut)
if err != nil {
return false, fmt.Errorf("failed to get Condition for Timeout of BIOSSettings update %w", err)
}
if err := r.Conditions.Update(
timedOut,
conditionutils.UpdateStatus(corev1.ConditionTrue),
conditionutils.UpdateReason(BIOSSettingsReasonUpdateTimedOut),
conditionutils.UpdateMessage(fmt.Sprintf("Timeout after: %v. startTime: %v. timedOut on: %v", r.TimeoutExpiry, startTime, time.Now().String())),
); err != nil {
return false, fmt.Errorf("failed to update timeout during settings update condition: %w", err)
}
err = r.updateFlowStatus(ctx, settings, metalv1alpha1.BIOSSettingsFlowStateFailed, flowStatus, timedOut)
return true, errors.Join(err, r.updateStatus(ctx, settings, metalv1alpha1.BIOSSettingsStateFailed, nil))
}
}
return false, nil
}
func (r *BIOSSettingsReconciler) verifySettingsUpdateComplete(ctx context.Context, bmcClient bmc.BMC, biosSettings *metalv1alpha1.BIOSSettings, flowItem *metalv1alpha1.SettingsFlowItem, flowStatus *metalv1alpha1.BIOSSettingsFlowStatus, server *metalv1alpha1.Server) (bool, error) {
log := ctrl.LoggerFrom(ctx)
verifySettingUpdate, err := GetCondition(r.Conditions, flowStatus.Conditions, BIOSSettingsConditionVerifySettings)
if err != nil {
return false, fmt.Errorf("failed to get Condition for Verification condition %w", err)
}
if verifySettingUpdate.Status != metav1.ConditionTrue {
// make sure the setting has actually applied.
settingsDiff, err := r.getSettingsDiff(ctx, bmcClient, flowItem.Settings, server)
if err != nil {
return false, fmt.Errorf("failed to get BIOS settings diff: %w", err)
}
// if setting is not different, complete the BIOS tasks
if len(settingsDiff) == 0 {
if err := r.Conditions.Update(
verifySettingUpdate,
conditionutils.UpdateStatus(corev1.ConditionTrue),
conditionutils.UpdateReason(BIOSSettingsReasonVerificationCompleted),
conditionutils.UpdateMessage("Required BIOS settings has been applied and verified on the server"),
); err != nil {
return false, fmt.Errorf("failed to update verify BIOSSetting condition: %w", err)
}
log.V(1).Info("Verified BIOS setting sequence", "Name", flowStatus.Name)
return false, r.updateFlowStatus(ctx, biosSettings, metalv1alpha1.BIOSSettingsFlowStateApplied, flowStatus, verifySettingUpdate)
}
log.V(1).Info("Waiting on the BIOS setting to take place")
if verifySettingUpdate.Reason != BIOSSettingsReasonVerificationNotCompleted {
if err := r.Conditions.Update(
verifySettingUpdate,
conditionutils.UpdateStatus(corev1.ConditionFalse),
conditionutils.UpdateReason(BIOSSettingsReasonVerificationNotCompleted),
conditionutils.UpdateMessage("Required BIOS settings has not yet verified on the server"),
); err != nil {
return false, fmt.Errorf("failed to update verify BIOSSetting condition: %w", err)
}
return false, r.updateFlowStatus(ctx, biosSettings, flowStatus.State, flowStatus, verifySettingUpdate)
}
return true, nil
}
log.V(1).Info("BIOS settings have been applied and verified on the server", "SettingsFlow", flowItem.Name)
return false, nil
}
func (r *BIOSSettingsReconciler) rebootServer(ctx context.Context, settings *metalv1alpha1.BIOSSettings, flowStatus *metalv1alpha1.BIOSSettingsFlowStatus, server *metalv1alpha1.Server) error {
log := ctrl.LoggerFrom(ctx)
rebootPowerOffCondition, err := GetCondition(r.Conditions, flowStatus.Conditions, BIOSSettingsConditionRebootPowerOff)
if err != nil {
return fmt.Errorf("failed to get PowerOff condition: %w", err)
}
if rebootPowerOffCondition.Status != metav1.ConditionTrue {
// expected state it to be off and initial state is to be on.
if r.isServerInPowerState(server, metalv1alpha1.ServerOnPowerState) {
if err := r.patchPowerState(ctx, settings, metalv1alpha1.PowerOff); err != nil {
return fmt.Errorf("failed to reboot %w", err)
}
}
if r.isServerInPowerState(server, metalv1alpha1.ServerOffPowerState) {
if err := r.Conditions.Update(
rebootPowerOffCondition,
conditionutils.UpdateStatus(corev1.ConditionTrue),
conditionutils.UpdateReason(BIOSSettingsReasonRebootServerPowerOff),
conditionutils.UpdateMessage("Server has entered power off state"),
); err != nil {
return fmt.Errorf("failed to update powerOff condition: %w", err)
}
return r.updateFlowStatus(ctx, settings, flowStatus.State, flowStatus, rebootPowerOffCondition)
}
log.V(1).Info("Reconciled BIOSSettings. Waiting for powering off the Server", "Server", server.Name)
return nil
}
rebootPowerOnCondition, err := GetCondition(r.Conditions, flowStatus.Conditions, BIOSSettingsConditionRebootPowerOn)
if err != nil {
return fmt.Errorf("failed to get PowerOn condition %v", err)
}
if rebootPowerOnCondition.Status != metav1.ConditionTrue {
// expected power state it to be on and initial state is to be off.
if r.isServerInPowerState(server, metalv1alpha1.ServerOffPowerState) {
if err := r.patchPowerState(ctx, settings, metalv1alpha1.PowerOn); err != nil {
return fmt.Errorf("failed to reboot server: %w", err)
}
}
if r.isServerInPowerState(server, metalv1alpha1.ServerOnPowerState) {
if err := r.Conditions.Update(
rebootPowerOnCondition,
conditionutils.UpdateStatus(corev1.ConditionTrue),
conditionutils.UpdateReason(BIOSSettingsReasonRebootServerPowerOn),
conditionutils.UpdateMessage("Server has entered power on state"),
); err != nil {
return fmt.Errorf("failed to update reboot server powerOn condition: %w", err)
}
return r.updateFlowStatus(ctx, settings, flowStatus.State, flowStatus, rebootPowerOnCondition)
}
log.V(1).Info("Reconciled BIOSSettings. Waiting for powering on the Server", "Server", server.Name)
return nil
}
return nil
}
func (r *BIOSSettingsReconciler) applyBIOSSettings(ctx context.Context, bmcClient bmc.BMC, settings *metalv1alpha1.BIOSSettings, flowItem *metalv1alpha1.SettingsFlowItem, flowStatus *metalv1alpha1.BIOSSettingsFlowStatus, server *metalv1alpha1.Server, issueBiosUpdate *metav1.Condition) error {
log := ctrl.LoggerFrom(ctx)
settingsDiff, err := r.getSettingsDiff(ctx, bmcClient, flowItem.Settings, server)
if err != nil {
return fmt.Errorf("failed to get BIOS settings difference: %w", err)
}
if len(settingsDiff) == 0 {
log.V(1).Info("No BIOS settings difference found to apply on server", "currentSettings Name", flowItem.Name)
if err := r.Conditions.Update(
issueBiosUpdate,
conditionutils.UpdateStatus(corev1.ConditionTrue),
conditionutils.UpdateReason(BIOSSettingReasonIssuedUpdate),
conditionutils.UpdateMessage("BIOS Settings issue has been Skipped on the server as no difference found"),
); err != nil {
return fmt.Errorf("failed to update issued settings update condition: %w", err)
}
err = r.updateFlowStatus(ctx, settings, flowStatus.State, flowStatus, issueBiosUpdate)
log.V(1).Info("Reconciled BIOSSettings at issue Settings to server state", "SettingsFlow", flowItem.Name)
return err
}
// check if the pending tasks not present on the bios settings
pendingSettings, err := r.getPendingBIOSSettings(ctx, bmcClient, server)
if err != nil {
return fmt.Errorf("failed to get pending BIOS settings: %w", err)
}
var pendingSettingsDiff schemas.SettingsAttributes
if len(pendingSettings) == 0 {
log.V(1).Info("Issuing settings Update on BMC", "settingsDiff", settingsDiff, "SettingsName", flowItem.Name)
err = bmcClient.SetBiosAttributesOnReset(ctx, server.Spec.SystemURI, settingsDiff)
if err != nil {
return fmt.Errorf("failed to set BMC settings: %w", err)
}
} else {
// this can only happen if we have issued the settings update
// or unexpected pending settings found because of spec update during Inprogress of settings
return fmt.Errorf("pending settings found on BIOS, cannot issue new settings update. pending settings: %v", pendingSettings)
}
// Get the latest pending settings and expect it to be zero different from the required settings.
pendingSettings, err = r.getPendingBIOSSettings(ctx, bmcClient, server)
if err != nil {
return fmt.Errorf("failed to get pending BIOS settings: %w", err)
}
skipReboot, err := GetCondition(r.Conditions, flowStatus.Conditions, BIOSSettingsConditionRebootPostUpdate)
if err != nil {
return fmt.Errorf("failed to get Condition for reboot needed condition %w", err)
}
// At this point the BIOS setting update needs to be already issued.
// if no reboot is required, most likely the settings is already applied,
// hence no pending task will be present.
if len(pendingSettings) == 0 && skipReboot.Status == metav1.ConditionFalse {
// todo: fail after X amount of time
log.V(1).Info("BIOSSettings update issued to BMC was not accepted. retrying....")
return errors.Join(err, fmt.Errorf("bios setting issued to bmc not accepted"))
}
pendingSettingsDiff = make(schemas.SettingsAttributes, len(settingsDiff))
for name, value := range settingsDiff {
if pendingValue, ok := pendingSettings[name]; ok && value != pendingValue {
pendingSettingsDiff[name] = pendingValue
}
}
// all required settings should in pending settings.
if len(pendingSettingsDiff) > 0 {
log.V(1).Info("Difference between the pending settings and that of required", "SettingsDiff", pendingSettingsDiff)
unexpectedPendingSettings, err := GetCondition(r.Conditions, flowStatus.Conditions, BIOSSettingsConditionUnknownPendingSettings)
if err != nil {
return fmt.Errorf("failed to get Condition for unexpected pending BIOSSetting state %v", err)
}
if err := r.Conditions.Update(
unexpectedPendingSettings,
conditionutils.UpdateStatus(corev1.ConditionTrue),
conditionutils.UpdateReason(BIOSSettingsReasonUnexpectedPendingSettings),
conditionutils.UpdateMessage(fmt.Sprintf("Found unexpected settings after issuing settings update for BIOS. unexpected settings %v", pendingSettingsDiff)),
); err != nil {
return fmt.Errorf("failed to update unexpected pending BIOSSettings found condition: %w", err)
}
err = r.updateFlowStatus(ctx, settings, metalv1alpha1.BIOSSettingsFlowStateFailed, flowStatus, unexpectedPendingSettings)
return errors.Join(err, r.updateStatus(ctx, settings, metalv1alpha1.BIOSSettingsStateFailed, nil))
}
if err := r.Conditions.Update(
issueBiosUpdate,
conditionutils.UpdateStatus(corev1.ConditionTrue),
conditionutils.UpdateReason(BIOSSettingReasonIssuedUpdate),
conditionutils.UpdateMessage("BIOS settings update has been triggered on the server"),
); err != nil {
return fmt.Errorf("failed to update issued BIOSSettings update condition: %w", err)
}
return r.updateFlowStatus(ctx, settings, flowStatus.State, flowStatus, issueBiosUpdate)
}
func (r *BIOSSettingsReconciler) ensureNoStrandedStatus(ctx context.Context, settings *metalv1alpha1.BIOSSettings) (bool, error) {
// In case the settings Spec got changed during in progress and left behind Stale states clean it up.
settingsNamePriorityMap := map[string]int32{}
settingsBase := settings.DeepCopy()
for _, flowItem := range settings.Spec.SettingsFlow {
settingsNamePriorityMap[flowItem.Name] = flowItem.Priority
}
nextFlowStatuses := make([]metalv1alpha1.BIOSSettingsFlowStatus, 0)
for _, flowStatus := range settings.Status.FlowState {
if value, ok := settingsNamePriorityMap[flowStatus.Name]; ok && value == flowStatus.Priority {
nextFlowStatuses = append(nextFlowStatuses, flowStatus)
}
}
if len(nextFlowStatuses) != len(settings.Status.FlowState) {
settings.Status.FlowState = nextFlowStatuses
if err := r.Status().Patch(ctx, settings, client.MergeFrom(settingsBase)); err != nil {
return false, fmt.Errorf("failed to patch BIOSSettings FlowState status: %w", err)
}
return true, nil
}
return false, nil
}
func (r *BIOSSettingsReconciler) handleAppliedState(ctx context.Context, bmcClient bmc.BMC, settings *metalv1alpha1.BIOSSettings, server *metalv1alpha1.Server) (ctrl.Result, error) {
log := ctrl.LoggerFrom(ctx)
if err := r.removeServerMaintenance(ctx, settings); err != nil {
return ctrl.Result{}, err
}