forked from openshift/assisted-service
/
bmh_agent_controller.go
1775 lines (1553 loc) · 64.3 KB
/
bmh_agent_controller.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
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
/*
Copyright 2021.
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 (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"reflect"
"sort"
"strings"
"text/template"
"time"
bmh_v1alpha1 "github.com/metal3-io/baremetal-operator/apis/metal3.io/v1alpha1"
aiv1beta1 "github.com/openshift/assisted-service/api/v1beta1"
"github.com/openshift/assisted-service/internal/host/hostutil"
"github.com/openshift/assisted-service/internal/ignition"
"github.com/openshift/assisted-service/internal/spoke_k8s_client"
"github.com/openshift/assisted-service/models"
"github.com/openshift/assisted-service/pkg/conversions"
logutil "github.com/openshift/assisted-service/pkg/log"
conditionsv1 "github.com/openshift/custom-resource-status/conditions/v1"
hivev1 "github.com/openshift/hive/apis/hive/v1"
machinev1beta1 "github.com/openshift/machine-api-operator/pkg/apis/machine/v1beta1"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/thoas/go-funk"
corev1 "k8s.io/api/core/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/kubectl/pkg/drain"
ctrl "sigs.k8s.io/controller-runtime"
"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/handler"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/controller-runtime/pkg/source"
)
type BMACConfig struct {
MaxConcurrentReconciles int `envconfig:"BMAC_MAX_CONCURRENT_RECONCILES" default:"1"`
}
// BMACReconciler reconciles a Agent object
type BMACReconciler struct {
client.Client
APIReader client.Reader
Log logrus.FieldLogger
Scheme *runtime.Scheme
SpokeK8sClientFactory spoke_k8s_client.SpokeK8sClientFactory
spokeClient client.Client
ConvergedFlowEnabled bool
Drainer Drainer
Config *BMACConfig
}
const (
AGENT_BMH_LABEL = "agent-install.openshift.io/bmh"
BMH_AGENT_ROLE = "bmac.agent-install.openshift.io/role"
BMH_AGENT_HOSTNAME = "bmac.agent-install.openshift.io/hostname"
BMH_AGENT_MACHINE_CONFIG_POOL = "bmac.agent-install.openshift.io/machine-config-pool"
BMH_INFRA_ENV_LABEL = "infraenvs.agent-install.openshift.io"
BMH_AGENT_INSTALLER_ARGS = "bmac.agent-install.openshift.io/installer-args"
BMH_ANNOTATION = "metal3.io/BareMetalHost"
BMH_API_VERSION = "baremetal.cluster.k8s.io/v1alpha1"
BMH_DETACHED_ANNOTATION = "baremetalhost.metal3.io/detached"
BMH_INSPECT_ANNOTATION = "inspect.metal3.io"
BMH_HARDWARE_DETAILS_ANNOTATION = "inspect.metal3.io/hardwaredetails"
BMH_AGENT_IGNITION_CONFIG_OVERRIDES = "bmac.agent-install.openshift.io/ignition-config-overrides"
BMH_FINALIZER_NAME = "bmac.agent-install.openshift.io/deprovision"
BMH_DELETE_ANNOTATION = "bmac.agent-install.openshift.io/remove-agent-and-node-on-delete"
MACHINE_ROLE = "machine.openshift.io/cluster-api-machine-role"
MACHINE_TYPE = "machine.openshift.io/cluster-api-machine-type"
MCS_CERT_NAME = "ca.crt"
OPENSHIFT_MACHINE_API_NAMESPACE = "openshift-machine-api"
ASSISTED_DEPLOY_METHOD = "start_assisted_install"
NODE_LABEL_PREFIX = "bmac.agent-install.openshift.io.node-label."
BMH_NODE_DRAIN_START_ANNOTATION = "bmac.agent-install.openshift.io/drain-started-at"
BMH_NODE_DRAIN_TIMEOUT_ANNOTATION = "bmac.agent-install.openshift.io/drain-timeout" // in time.Duration format
BMH_NODE_DRAIN_STATUS_ANNOTATION = "bmac.agent-install.openshift.io/drain-status"
drainStatusSuccess = "drain succeeded"
drainStatusInProgress = "draining in progress"
drainStatusTimeout = "drain timed out"
)
var (
InfraEnvImageCooldownPeriod = 60 * time.Second
// Possible names Hypershift might give the root-CA, we look for any of them
kubeRootCAHypershiftNames = []string{
"kube-root-ca",
"kube-root-ca.crt",
}
)
const certificateAuthoritiesIgnitionOverride = `{
"ignition": {
"version": "3.1.0",
"security": {
"tls": {
"certificateAuthorities": [{
"source": "{{.SOURCE}}"
}]
}
}
}
}`
// reconcileResult is an interface that encapsulates the result of a Reconcile
// call, as returned by the action corresponding to the current state.
//
// Set the `dirty` flag when the BMH CR (or any CR) has been modified and an `Update`
// is required.
//
// Set the `stop` flag when the `Reconcile` flow should be stopped. For example, the
// required data for the current step is not ready yet. This will prevent the Reconcile
// from going to the next step.
type reconcileResult interface {
Result() (reconcile.Result, error)
Dirty() bool
Stop(ctx context.Context) bool
}
// reconcileComplete is a result indicating that the current reconcile has completed,
// and there is nothing else to do. It allows for setting the implementation or the
// stop flag.
type reconcileComplete struct {
dirty bool
stop bool
}
func (r reconcileComplete) Result() (result reconcile.Result, err error) {
return
}
func (r reconcileComplete) Dirty() bool {
return r.dirty
}
func (r reconcileComplete) Stop(ctx context.Context) bool {
return r.stop || ctx.Err() != nil
}
type reconcileRequeue struct {
requeueAfter time.Duration
dirty bool
}
func (r reconcileRequeue) Result() (result reconcile.Result, err error) {
result = reconcile.Result{
Requeue: true,
RequeueAfter: r.requeueAfter,
}
return result, err
}
func (r reconcileRequeue) Dirty() bool {
return r.dirty
}
func (r reconcileRequeue) Stop(ctx context.Context) bool {
return true
}
// reconcileError is a result indicating that an error occurred while attempting
// to advance the current reconcile, and that reconciliation should be retried.
type reconcileError struct {
err error
dirty bool
}
func (r reconcileError) Result() (result reconcile.Result, err error) {
err = r.err
return
}
func (r reconcileError) Dirty() bool {
return r.dirty
}
func (r reconcileError) Stop(ctx context.Context) bool {
return true
}
func (r *BMACReconciler) handleReconcileResult(ctx context.Context, log logrus.FieldLogger, result reconcileResult, obj client.Object) reconcileResult {
if result.Dirty() {
log.Debugf("Updating dirty object %v", obj)
err := r.Client.Update(ctx, obj)
if err != nil {
return reconcileError{err: err}
}
}
if result.Stop(ctx) {
log.Debugf("Stopping reconcile")
return result
}
return nil
}
// +kubebuilder:rbac:groups=metal3.io,resources=baremetalhosts,verbs=get;list;watch;update;patch
func (r *BMACReconciler) Reconcile(origCtx context.Context, req ctrl.Request) (ctrl.Result, error) {
ctx := addRequestIdIfNeeded(origCtx)
log := logutil.FromContext(ctx, r.Log).WithFields(
logrus.Fields{
"bare_metal_host": req.Name,
"bare_metal_host_namespace": req.Namespace,
})
defer func() {
log.Info("BareMetalHost Reconcile ended")
}()
log.Info("BareMetalHost Reconcile started")
bmh := &bmh_v1alpha1.BareMetalHost{}
if err := r.Get(ctx, req.NamespacedName, bmh); err != nil {
if !k8serrors.IsNotFound(err) {
return reconcileError{err: err}.Result()
}
return reconcileComplete{}.Result()
}
// Should we check the status of the BMH resource?
// Provisioning / Deprovisioning ?
// What happens if we do the reconcile on a BMH that
// is in a Deprovisioning state?
agent := r.findAgent(ctx, bmh)
if agent != nil {
log = log.WithFields(logrus.Fields{
"agent": agent.Name,
"agent_namespace": agent.Namespace,
})
}
result := r.handleBMHFinalizer(ctx, log, bmh, agent)
if res := r.handleReconcileResult(ctx, log, result, bmh); res != nil {
return res.Result()
}
if agent != nil && agentIsUnbindingPendingUserAction(agent) {
result = reconcileUnboundAgent(log, bmh, r.ConvergedFlowEnabled)
if res := r.handleReconcileResult(ctx, log, result, bmh); res != nil {
return res.Result()
}
}
result = r.reconcileBMH(ctx, log, bmh, agent)
if res := r.handleReconcileResult(ctx, log, result, bmh); res != nil {
return res.Result()
}
// handle multiple agents matching the
// same BMH's Mac Address
if agent == nil {
log.Debugf("Stopping BMAC reconcile after reconcileBMH")
return result.Result()
}
// if we get to this point, it means we have found an Agent that is associated
// with the BMH being reconciled. We will call both, reconcileAgentSpec and
// reconcileAgentInventory, every time. The logic to decide whether there's
// any action to take is implemented in each function respectively.
result = r.reconcileAgentSpec(log, bmh, agent)
if res := r.handleReconcileResult(ctx, log, result, agent); res != nil {
return res.Result()
}
// In the converged flow ironic will reconcile the BMH_HARDWARE_DETAILS_ANNOTATION
if !r.ConvergedFlowEnabled {
result = r.reconcileAgentInventory(log, bmh, agent)
if res := r.handleReconcileResult(ctx, log, result, bmh); res != nil {
return res.Result()
}
}
result = r.ensureMCSCert(ctx, log, bmh, agent)
if res := r.handleReconcileResult(ctx, log, result, bmh); res != nil {
return res.Result()
}
if r.ConvergedFlowEnabled {
result = r.addBMHDetachedAnnotationIfBmhIsProvisioned(log, bmh, agent)
} else {
// After the agent has started installation, Ironic should not manage the host.
// Adding the detached annotation to the BMH stops Ironic from managing it.
result = r.addBMHDetachedAnnotationIfAgentHasStartedInstallation(log, bmh, agent)
}
if res := r.handleReconcileResult(ctx, log, result, bmh); res != nil {
return res.Result()
}
result = r.reconcileSpokeBMH(ctx, log, bmh, agent)
if result.Dirty() {
err := r.Client.Update(ctx, bmh)
if err != nil {
log.WithError(err).Errorf("Error adding BMH detached annotation after creating spoke BMH")
return reconcileError{err: err}.Result()
}
}
return result.Result()
}
// handleBMHFinalizer adds a finalizer to the BMH if it isn't being deleted and the finalizer isn't already present
// If the BMH is being deleted, the associated node is drained and the agent (if any) is annotated and deleted before the BMH is allowed to be removed
// Finalizer handling is only run if the user has annotated the BMH and converged flow is enabled
func (r *BMACReconciler) handleBMHFinalizer(ctx context.Context, log logrus.FieldLogger, bmh *bmh_v1alpha1.BareMetalHost, agent *aiv1beta1.Agent) reconcileResult {
if _, has_annotation := bmh.GetAnnotations()[BMH_DELETE_ANNOTATION]; !has_annotation || !r.ConvergedFlowEnabled {
return reconcileComplete{}
}
bmhHasFinalizer := funk.ContainsString(bmh.GetFinalizers(), BMH_FINALIZER_NAME)
if bmh.ObjectMeta.DeletionTimestamp.IsZero() {
if !bmhHasFinalizer {
controllerutil.AddFinalizer(bmh, BMH_FINALIZER_NAME)
return reconcileComplete{dirty: true}
}
return reconcileComplete{}
}
// BMH is being deleted and finalizer is gone, ensure detached is gone and return
if !bmhHasFinalizer {
dirty := removeBMHDetachedAnnotation(log, bmh)
return reconcileComplete{stop: true, dirty: dirty}
}
log.Info("Handling BMH delete")
// agent could be nil here if it wasn't created yet, or if we deleted it, then failed to remove the finalizer for some reason
// if the agent is missing, just allow the BMH to be removed
if agent == nil {
removeBMHDetachedAnnotation(log, bmh)
controllerutil.RemoveFinalizer(bmh, BMH_FINALIZER_NAME)
return reconcileComplete{stop: true, dirty: true}
}
dirty := false
if agent.Spec.ClusterDeploymentName != nil {
var res reconcileResult
dirty, res = r.handleDrain(ctx, log, agent, bmh)
if res.Stop(ctx) {
return res
}
if updated := configureBMHForCleaning(ctx, log, bmh); updated {
return reconcileComplete{stop: true, dirty: true}
}
// annotate the agent to inform the agent controller to remove the spoke node when the BMH finishes deprovisioning
if _, ok := agent.GetAnnotations()[BMH_FINALIZER_NAME]; !ok {
setAnnotation(&agent.ObjectMeta, BMH_FINALIZER_NAME, "true")
if err := r.Update(ctx, agent); err != nil {
log.WithError(err).Errorf("failed to set %s annotation on agent", BMH_FINALIZER_NAME)
return reconcileError{err: err, dirty: dirty}
}
}
}
if err := r.Delete(ctx, agent); err != nil {
log.WithError(err).Errorf("Failed to delete agent as a part of BMH removal")
return reconcileError{err: err, dirty: dirty}
}
log.Infof("Removing BMH finalizer %s", BMH_FINALIZER_NAME)
controllerutil.RemoveFinalizer(bmh, BMH_FINALIZER_NAME)
return reconcileComplete{stop: true, dirty: true}
}
// This reconcile step takes care of copying data from the BMH into the Agent.
//
// The Agent's spec reconcile will only happen for non-Approved agents. These are
// considered to be `new` and, at this point, the agent has not started the deployment
// yet.
//
// We are only interested in the following data:
//
// - Agent role: bmac.agent-install.openshift.io/role
// - Hostname: bmac.agent-install.openshift.io/hostname
// - Machine Config Pool: bmac.agent-install.openshift.io/machine-config-pool
//
// Unless there are errors, the agent should be `Approved` at the end of this
// reconcile and a label should be set on it referencing the BMH. No changes to
// the BMH should happen in this reconcile step.
func (r *BMACReconciler) reconcileAgentSpec(log logrus.FieldLogger, bmh *bmh_v1alpha1.BareMetalHost, agent *aiv1beta1.Agent) reconcileResult {
log.Debugf("Setting agent spec according to BMH")
// Do all the copying from the BMH annotations to the agent.
var dirty bool
annotations := bmh.ObjectMeta.GetAnnotations()
if val, ok := annotations[BMH_AGENT_ROLE]; ok {
if agent.Spec.Role != models.HostRole(val) {
agent.Spec.Role = models.HostRole(val)
dirty = true
}
}
if val, ok := annotations[BMH_AGENT_HOSTNAME]; ok {
if agent.Spec.Hostname != val {
agent.Spec.Hostname = val
dirty = true
}
}
if val, ok := annotations[BMH_AGENT_MACHINE_CONFIG_POOL]; ok {
if agent.Spec.MachineConfigPool != val {
agent.Spec.MachineConfigPool = val
dirty = true
}
}
if val, ok := annotations[BMH_AGENT_INSTALLER_ARGS]; ok {
if agent.Spec.InstallerArgs != val {
agent.Spec.InstallerArgs = val
dirty = true
}
}
if val, ok := annotations[BMH_AGENT_IGNITION_CONFIG_OVERRIDES]; ok {
if agent.Spec.IgnitionConfigOverrides != val {
agent.Spec.IgnitionConfigOverrides = val
dirty = true
}
}
if !agent.Spec.Approved {
agent.Spec.Approved = true
dirty = true
}
if agent.ObjectMeta.Labels == nil {
agent.ObjectMeta.Labels = make(map[string]string)
dirty = true
}
// Label the agent with the reference to this BMH
name, ok := agent.ObjectMeta.Labels[AGENT_BMH_LABEL]
if !ok || name != bmh.Name {
agent.ObjectMeta.Labels[AGENT_BMH_LABEL] = bmh.Name
dirty = true
}
// findInstallationDiskID will return an empty string
// if no disk is found from the list. Should be find
// to "overwrite" this value everytime as the default
// is ""
installationDiskID := r.findInstallationDiskID(agent.Status.Inventory.Disks, bmh.Spec.RootDeviceHints)
if installationDiskID != "" && bmh.Spec.RootDeviceHints != nil && agent.Spec.InstallationDiskID != installationDiskID {
agent.Spec.InstallationDiskID = installationDiskID
dirty = true
}
if r.reconcileNodeLabels(bmh, agent) {
dirty = true
}
log.Debugf("Agent spec reconcile finished: %v", agent)
return reconcileComplete{dirty: dirty}
}
func (r *BMACReconciler) reconcileNodeLabels(bmh *bmh_v1alpha1.BareMetalHost, agent *aiv1beta1.Agent) bool {
nodeLabels := make(map[string]string)
funk.ForEach(bmh.ObjectMeta.GetAnnotations(), func(key, value string) {
if strings.HasPrefix(key, NODE_LABEL_PREFIX) {
nodeLabels[key[len(NODE_LABEL_PREFIX):]] = value
}
})
agentNodeLabels := agent.Spec.NodeLabels
if agentNodeLabels == nil {
agentNodeLabels = make(map[string]string)
}
if !reflect.DeepEqual(nodeLabels, agentNodeLabels) {
agent.Spec.NodeLabels = nodeLabels
return true
}
return false
}
// The detached annotation is added if the BMH provisioning state is provisioned
func (r *BMACReconciler) addBMHDetachedAnnotationIfBmhIsProvisioned(log logrus.FieldLogger, bmh *bmh_v1alpha1.BareMetalHost, agent *aiv1beta1.Agent) reconcileResult {
if r.ConvergedFlowEnabled && bmh.Status.Provisioning.State != bmh_v1alpha1.StateProvisioned {
log.Debugf("Skipping adding detached annotation. BMH provisioning state is: %s should be: %s", bmh.Status.Provisioning.State, bmh_v1alpha1.StateProvisioned)
return reconcileComplete{}
}
return r.ensureBMHDetached(log, bmh, agent)
}
func (r *BMACReconciler) detachedValue(bmh *bmh_v1alpha1.BareMetalHost) (string, error) {
detachValue := []byte("assisted-service-controller")
if _, has_annotation := bmh.GetAnnotations()[BMH_DELETE_ANNOTATION]; has_annotation && r.ConvergedFlowEnabled {
arg := bmh_v1alpha1.DetachedAnnotationArguments{DeleteAction: bmh_v1alpha1.DetachedDeleteActionDelay}
var err error
detachValue, err = json.Marshal(arg)
if err != nil {
return "", err
}
}
return string(detachValue), nil
}
func (r *BMACReconciler) ensureBMHDetached(log logrus.FieldLogger, bmh *bmh_v1alpha1.BareMetalHost, agent *aiv1beta1.Agent) reconcileResult {
if bmh.ObjectMeta.Annotations == nil {
bmh.ObjectMeta.Annotations = make(map[string]string)
}
// it's possible this BMH doesn't have a matching agent when this is called in some cases
if agent != nil {
//check if we are in unbinding-pending-user-action status. If yes, we should not
//re-apply the detached label because ironic need to restart the host
boundCondition := conditionsv1.FindStatusCondition(agent.Status.Conditions, aiv1beta1.BoundCondition)
if boundCondition != nil && boundCondition.Reason == aiv1beta1.UnbindingPendingUserActionReason {
log.Debugf("Skipping adding detached annotation. pending unbound condition \n %v", agent)
return reconcileComplete{}
}
}
desiredValue, err := r.detachedValue(bmh)
if err != nil {
return reconcileError{err: err}
}
currentValue, haveAnnotation := bmh.ObjectMeta.Annotations[BMH_DETACHED_ANNOTATION]
if haveAnnotation && currentValue == desiredValue {
return reconcileComplete{}
}
bmh.ObjectMeta.Annotations[BMH_DETACHED_ANNOTATION] = desiredValue
log.Info("Added detached annotation to BMH")
return reconcileComplete{dirty: true, stop: true}
}
// The detached annotation is added if the installation of the agent associated with
// the host has started.
func (r *BMACReconciler) addBMHDetachedAnnotationIfAgentHasStartedInstallation(log logrus.FieldLogger, bmh *bmh_v1alpha1.BareMetalHost, agent *aiv1beta1.Agent) reconcileResult {
c := conditionsv1.FindStatusCondition(agent.Status.Conditions, aiv1beta1.InstalledCondition)
if c == nil {
log.Debugf("Skipping adding detached annotation. missing install condition \n %v", agent)
return reconcileComplete{}
}
installConditionReason := c.Reason
// Do nothing if InstalledCondition is not in Installed, InProgress, or Failed
if installConditionReason != aiv1beta1.InstallationInProgressReason &&
installConditionReason != aiv1beta1.InstalledReason &&
installConditionReason != aiv1beta1.InstallationFailedReason {
log.Debugf("Skipping adding detached annotation. host not in proper installation condition \n %v", agent)
return reconcileComplete{}
}
return r.ensureBMHDetached(log, bmh, agent)
}
// Reconcile BMH's HardwareDetails using the agent's inventory
//
// Here we will copy as much data from the Agent's Inventory as possible
// into the `inspect.metal3.io/hardwaredetails` annotation in the BMH.
//
// This will trigger a reconcile on the BMH side, resulting in this data
// being copied from the annotation into the BMH's HardwareDetails status.
//
// Care must be taken to only update the data when really needed. Doing an update
// on every BMAC reconcile will trigger an infinite loop of reconciles between
// BMAC and the BMH reconcile as the former will update the hardwaredetails annotation
// while the latter will continue to update the status.
func (r *BMACReconciler) reconcileAgentInventory(log logrus.FieldLogger, bmh *bmh_v1alpha1.BareMetalHost, agent *aiv1beta1.Agent) reconcileResult {
log.Debugf("Started agent inventory reconcile")
// This check should be updated. We should check the agent's conditions instead
if len(agent.Status.Inventory.Interfaces) == 0 {
log.Debugf("Skipping Agent Inventory (hardwaredetails) reconcile \n %v", agent)
return reconcileComplete{}
}
bmhAnnotations := bmh.ObjectMeta.GetAnnotations()
if _, ok := bmhAnnotations[BMH_HARDWARE_DETAILS_ANNOTATION]; ok {
log.Debugf("%s annotation exists", BMH_HARDWARE_DETAILS_ANNOTATION)
return reconcileComplete{}
}
// Check whether HardwareDetails has been set already. This annotation
// status should only be set through this Reconcile in this scenario.
if bmh.Status.HardwareDetails != nil && bmh.Status.HardwareDetails.Hostname != "" {
log.Debugf("HardwareDetails or Hostname already present in the BMH")
return reconcileComplete{}
}
inventory := agent.Status.Inventory
hardwareDetails := bmh_v1alpha1.HardwareDetails{}
// Add the interfaces
for _, iface := range inventory.Interfaces {
// BMH handles dual stack in a different way, it requires adding
// multiple NICs, same mac and name, with different IPs.
// reference: https://github.com/metal3-io/baremetal-operator/pull/758
for _, ip := range append(iface.IPV6Addresses, iface.IPV4Addresses...) {
hardwareDetails.NIC = append(hardwareDetails.NIC, bmh_v1alpha1.NIC{
IP: strings.SplitN(ip, "/", 2)[0],
Name: iface.Name,
Model: iface.Vendor,
MAC: iface.MacAddress,
SpeedGbps: int(iface.SpeedMbps / 1024),
})
}
}
// Add storage
for _, d := range inventory.Disks {
device := d.Path
if d.ByPath != "" {
device = d.ByPath
}
// missing WWNVendorExtension, WWNWithExtension
disk := bmh_v1alpha1.Storage{
Name: device,
HCTL: d.Hctl,
Model: d.Model,
SizeBytes: bmh_v1alpha1.Capacity(d.SizeBytes),
SerialNumber: d.Serial,
WWN: d.Wwn,
Vendor: d.Vendor,
Rotational: strings.EqualFold(d.DriveType, string(models.DriveTypeHDD)),
}
hardwareDetails.Storage = append(hardwareDetails.Storage, disk)
}
// Add the memory information in MebiByte
if agent.Status.Inventory.Memory.PhysicalBytes > 0 {
hardwareDetails.RAMMebibytes = int(conversions.BytesToMib(inventory.Memory.PhysicalBytes))
}
// Add CPU information
hardwareDetails.CPU = bmh_v1alpha1.CPU{
Flags: inventory.Cpu.Flags,
Count: int(inventory.Cpu.Count),
Model: inventory.Cpu.ModelName,
Arch: inventory.Cpu.Architecture,
ClockMegahertz: bmh_v1alpha1.ClockSpeed(inventory.Cpu.ClockMegahertz),
}
// BMH has a `virtual` field that the Agent does not have
hardwareDetails.SystemVendor = bmh_v1alpha1.HardwareSystemVendor{
Manufacturer: inventory.SystemVendor.Manufacturer,
ProductName: inventory.SystemVendor.ProductName,
SerialNumber: inventory.SystemVendor.SerialNumber,
}
// Add hostname
if agent.Spec.Hostname != "" {
hardwareDetails.Hostname = agent.Spec.Hostname
} else {
hardwareDetails.Hostname = inventory.Hostname
}
bytes, err := json.Marshal(hardwareDetails)
if err != nil {
return reconcileError{err: err}
}
setAnnotation(&bmh.ObjectMeta, BMH_HARDWARE_DETAILS_ANNOTATION, string(bytes))
log.Debugf("Agent Inventory reconciled to BMH \n %v \n %v", agent, bmh)
return reconcileComplete{dirty: true, stop: true}
}
func agentIsUnbindingPendingUserAction(agent *aiv1beta1.Agent) bool {
boundCondition := conditionsv1.FindStatusCondition(agent.Status.Conditions, aiv1beta1.BoundCondition)
return boundCondition != nil && boundCondition.Reason == aiv1beta1.UnbindingPendingUserActionReason
}
// Ask BMH to reboot the host if the agent is unbound after installation
//
// By re-attaching the BMH and clearing the Image field on it, BMAC will clear
// the Image data to force the boot from ISO
func reconcileUnboundAgent(log logrus.FieldLogger, bmh *bmh_v1alpha1.BareMetalHost, converged bool) reconcileResult {
log.Debugf("Started unbound agent reconcile")
if !converged {
// proceed with BMH unbind only when the detached annotation is in place (which means that we have not dealt with this case before)
if _, isDetached := bmh.ObjectMeta.Annotations[BMH_DETACHED_ANNOTATION]; !isDetached {
log.Debugf("Skipping Unbound Agent reconcile for bmh %v", bmh)
return reconcileComplete{}
}
// re-attach the bmh and clear the ISO url to force ironic image refresh
// and re-conciliation of BMH and agent. Also, clear the hw details just
// in case. They will be regenerated in the reconciles following the agent's
// reboot
delete(bmh.ObjectMeta.Annotations, BMH_DETACHED_ANNOTATION)
delete(bmh.ObjectMeta.Annotations, BMH_HARDWARE_DETAILS_ANNOTATION)
bmh.Spec.Image = nil
log.Infof("Unbound agent reconciled to BMH")
return reconcileComplete{dirty: true, stop: true}
}
// for converged flow we need to orchestrate deprovisioning the host
var dirty, stop bool
switch bmh.Status.Provisioning.State {
case bmh_v1alpha1.StateProvisioned:
// unset customDeploy to initiate deprovisioning
if bmh.Spec.CustomDeploy != nil {
log.Info("deprovisioning BMH")
bmh.Spec.CustomDeploy = nil
dirty = true
}
stop = true
case bmh_v1alpha1.StateDeprovisioning:
// wait for deprovision to finish before resetting customDeploy
stop = true
}
// always want the host attached if it's still unbinding pending user action
if _, ok := bmh.GetAnnotations()[BMH_DETACHED_ANNOTATION]; ok {
log.Info("removing BMH detached annotation")
delete(bmh.Annotations, BMH_DETACHED_ANNOTATION)
dirty = true
}
if _, ok := bmh.GetAnnotations()[BMH_HARDWARE_DETAILS_ANNOTATION]; ok {
log.Info("removing BMH hardware details annotation")
delete(bmh.Annotations, BMH_HARDWARE_DETAILS_ANNOTATION)
dirty = true
}
return reconcileComplete{dirty: dirty, stop: stop}
}
// Utility to verify whether a BMH should be reconciled based on the InfraEnv
//
// This function verifies the following things:
//
// 1. InfraEnv exists
// 2. InfraEnv's ISODownloadURL exists
// 3. The BMH.Spec.URL is the same to the InfraEnv's ISODownload URL
// 4. The InfraEnv's ISO is at least 60 seconds old
//
// If all the checks above are true, then the reconcile won't happen
// and the reconcileBMH function will return.
//
// Note that this function is also used to decide whether a BMH reconcile should be queued
// or not. This will help queuing fewer reconciles when we know the BMH is not ready.
//
// The function returns 2 booleans, time.Duration and a string:
//
// 1. Should we proceed with the BMH's reconcile
// 2. Should the full `Reconcile` stop as well
// 3. If requeueing is needed, for how long should we back off
// 4. If reconciling should not continue, a reason that will be printed in the log
//
// TODO: This function should return `reconcileResult` or some other interface suitable
//
// to contain multiple informations instead of a bunch of variables that are later on
// separately interpreted.
func shouldReconcileBMH(bmh *bmh_v1alpha1.BareMetalHost, infraEnv *aiv1beta1.InfraEnv) (bool, bool, time.Duration, string) {
// This is a separate check because an existing
// InfraEnv with an empty ISODownloadURL means the
// global `Reconcile` function should also return
// as there is nothing left to do for it. Note that we
// do not have to explicitly requeue here. As soon as
// the InfraEnv gets its ISO, reconciliation will be
// triggered because of the watcher on the InfraEnv CR.
if infraEnv.Status.ISODownloadURL == "" {
return false, true, 0, "InfraEnv corresponding to the BMH has no image URL available."
}
// The Image URL exists and InfraEnv's URL has not changed
// nothing else to do.
if bmh.Spec.Image != nil && bmh.Spec.Image.URL == infraEnv.Status.ISODownloadURL {
return false, false, 0, "BMH and InfraEnv images are in sync. Nothing to update."
}
// The image has been created sooner than the specified cooldown period
imageTime := infraEnv.Status.CreatedTime.Time.Add(InfraEnvImageCooldownPeriod)
if imageTime.After(time.Now()) {
return false, false, time.Until(imageTime), "InfraEnv image is too recent. Requeuing and retrying again soon."
}
return true, false, 0, ""
}
func (r *BMACReconciler) findInfraEnvForBMH(ctx context.Context, log logrus.FieldLogger, bmh *bmh_v1alpha1.BareMetalHost) (*aiv1beta1.InfraEnv, error) {
for ann, value := range bmh.Labels {
log.Debugf("BMH label %s value %s", ann, value)
// Find the `BMH_INFRA_ENV_LABEL`, get the infraEnv configured in it
// and copy the ISO Url from the InfraEnv to the BMH resource.
if ann == BMH_INFRA_ENV_LABEL {
infraEnv := &aiv1beta1.InfraEnv{}
log.Debugf("Loading InfraEnv %s", value)
if err := r.Get(ctx, types.NamespacedName{Name: value, Namespace: bmh.Namespace}, infraEnv); err != nil {
log.WithError(err).Errorf("failed to get infraEnv resource %s/%s", bmh.Namespace, value)
return nil, client.IgnoreNotFound(err)
}
return infraEnv, nil
}
}
return nil, nil
}
// Reconcile the `BareMetalHost` resource
//
// This reconcile step sets the Image.URL value in the `BareMetalHost`
// spec by copying it from the `InfraEnv` referenced in the resource's
// labels. If the previous action succeeds, this step will also set the
// BMH_INSPECT_ANNOTATION to disabled on the BareMetalHost.
//
// The above changes will be done only if the ISODownloadURL value has already
// been set in the `InfraEnv` resource and the Image.URL value has not been
// set in the `BareMetalHost`
func (r *BMACReconciler) reconcileBMH(ctx context.Context, log logrus.FieldLogger, bmh *bmh_v1alpha1.BareMetalHost, agent *aiv1beta1.Agent) reconcileResult {
log.Debugf("Started BMH reconcile")
log.Debugf("BMH value %v", bmh)
// A detached BMH is considered to be unmanaged by the hub
// cluster and, therefore, BMAC reconciles on this BMH should
// not happen.
//
// User is expected to remove the `detached` annotation manually
// to bring this BMH back into the pool of reconciled BMH resources.
bmhAnnotations := bmh.ObjectMeta.GetAnnotations()
if _, ok := bmhAnnotations[BMH_DETACHED_ANNOTATION]; ok {
result := r.ensureBMHDetached(log, bmh, agent)
if !result.Stop(ctx) {
// only create a new result here if ensureBMHDetected had no changes and no errors
// this ensures that the reconcile call will still exit
result = reconcileComplete{stop: true}
}
log.Debugf("Stopped BMH reconcile because it has been detached")
return result
}
infraEnv, err := r.findInfraEnvForBMH(ctx, log, bmh)
if err != nil {
return reconcileError{err: err}
}
// Stop `Reconcile` if BMH does not have an InfraEnv.
if infraEnv == nil {
return reconcileComplete{stop: true}
}
dirty := false
// in case of converged flow set the custom deploy instead of the annotations
if r.ConvergedFlowEnabled {
if bmh.Spec.CustomDeploy == nil || bmh.Spec.CustomDeploy.Method != ASSISTED_DEPLOY_METHOD {
log.Infof("Updating BMH CustomDeploy to %s", ASSISTED_DEPLOY_METHOD)
bmh.Spec.CustomDeploy = &bmh_v1alpha1.CustomDeploy{Method: ASSISTED_DEPLOY_METHOD}
dirty = true
}
return reconcileComplete{dirty: dirty, stop: false}
}
annotations := bmh.ObjectMeta.GetAnnotations()
// Set the following parameters regardless of the state
// of the InfraEnv and the BMH. There is no need for
// inspection to happen out of assisted service's loop.
if _, ok := annotations[BMH_INSPECT_ANNOTATION]; !ok {
// Let's make sure inspection is disabled for BMH resources
// that are associated with an agent-based deployment.
//
// Ideally, the user would do this while creating the BMH
// we are just taking extra care that this is the case.
setAnnotation(&bmh.ObjectMeta, BMH_INSPECT_ANNOTATION, "disabled")
dirty = true
}
proceed, stopReconcileLoop, requeuePeriod, reason := shouldReconcileBMH(bmh, infraEnv)
if !proceed {
if requeuePeriod != 0 {
log.Infof("Requeuing reconcileBMH: %s", reason)
return reconcileRequeue{requeueAfter: requeuePeriod}
}
log.Infof("Stopping reconcileBMH: %s", reason)
return reconcileComplete{dirty: dirty, stop: stopReconcileLoop}
}
// Set the bmh.Spec.Image field to nil if the BMH is in a non-ready state.
// This will make sure that any existing image will be de-provisioned first
// and, therefore, removed from Ironic's cache. The deprovision step is critical
// to guarantee that Ironic will fetch the latest version of the image.
if bmh.Status.Provisioning.State != bmh_v1alpha1.StateReady && bmh.Status.Provisioning.State != bmh_v1alpha1.StateAvailable {
log.Infof("Removing BMH image field to trigger Ironic image refresh")
bmh.Spec.Image = nil
return reconcileComplete{stop: true, dirty: true}
}
log.Debugf("Setting attributes in BMH")
// We'll just overwrite this at this point
// since the nullness and emptyness checks
// are done at the beginning of this function.
bmh.Spec.Image = &bmh_v1alpha1.Image{}
liveIso := "live-iso"
bmh.Spec.Online = true
bmh.Spec.Image.URL = infraEnv.Status.ISODownloadURL
bmh.Spec.Image.DiskFormat = &liveIso
log.Infof("Image URL has been set in the BMH")
return reconcileComplete{dirty: true, stop: true}
}
// Reconcile the `BareMetalHost` resource on the spoke cluster
//
// Baremetal-operator in the hub cluster creates a host using the live-iso feature. To add this host as a worker node
// to an existing spoke cluster, the following things need to be done:
// - Check agent to see if day2 flow needs to be triggered.
// - Get the kubeconfig client from secret data
// - Creates a new Machine
// - Create BMH with externallyProvisioned set to true and set the newly created machine as ConsumerRef
// BMH_HARDWARE_DETAILS_ANNOTATION is needed for auto approval of the CSR.
func (r *BMACReconciler) reconcileSpokeBMH(ctx context.Context, log logrus.FieldLogger, bmh *bmh_v1alpha1.BareMetalHost, agent *aiv1beta1.Agent) reconcileResult {
if !r.validateWorkerForDay2(log, agent) {
return reconcileComplete{}
}
cd, installed, err := r.getClusterDeploymentAndCheckIfInstalled(ctx, log, agent)
if err != nil {
return reconcileError{err: err}
}
if !installed {
return reconcileComplete{}
}
key := types.NamespacedName{
Namespace: agent.Spec.ClusterDeploymentName.Namespace,
Name: getClusterDeploymentAdminKubeConfigSecretName(cd),
}
isNonePlatform, propagateError, err := isNonePlatformCluster(ctx, r.Client, cd)
if err != nil {
log.WithError(err).Errorf("Failed to determine if platform is none for cluster deployment %s/%s", cd.Namespace, cd.Name)
// In case ACI reference doesn't exist or ACI not found do not reconcile again since such a change in these will trigger BMH reconciliation
// In all other cases propagate the error
if propagateError {
return reconcileError{err: err}
}
return reconcileComplete{}
}
if isNonePlatform {
// If none platform do not attempt to create spoke BMH
return reconcileComplete{}
}
if !funk.ContainsString([]string{models.HostStatusInstalling, models.HostStatusInstallingInProgress}, agent.Status.DebugInfo.State) {
// If agent hasn't started installing, do not create the spoke BMH yet
log.Debugf("Agent has not started installing, not creating the spoke BMH for %s on cluster %s", bmh.Name, agent.Spec.ClusterDeploymentName.Name)
return reconcileComplete{stop: false}
}
secret, err := getSecret(ctx, r.Client, r.APIReader, key)
if err != nil {
return reconcileError{err: err}
}
if err = ensureSecretIsLabelled(ctx, r.Client, secret, key); err != nil {
return reconcileError{err: err}
}
spokeClient, err := r.getSpokeClient(secret)
if err != nil {
log.WithError(err).Errorf("failed to create spoke kubeclient")
return reconcileError{err: err}
}
checksum, url, err, stopReconcileLoop := r.getChecksumAndURL(ctx, spokeClient)
if err != nil {
log.WithError(err).Errorf("failed to get checksum and url value from master spoke machine")
if stopReconcileLoop {
log.Info("Stopping reconcileSpokeBMH")
return reconcileComplete{dirty: false, stop: stopReconcileLoop}
}
return reconcileError{err: err}
}