-
Notifications
You must be signed in to change notification settings - Fork 192
/
agent_controller.go
1687 lines (1535 loc) · 61.8 KB
/
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 2020.
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"
"fmt"
"net/http"
"reflect"
"regexp"
"strconv"
"strings"
"time"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
bmh_v1alpha1 "github.com/metal3-io/baremetal-operator/apis/metal3.io/v1alpha1"
. "github.com/openshift/assisted-service/api/common"
aiv1beta1 "github.com/openshift/assisted-service/api/v1beta1"
"github.com/openshift/assisted-service/internal/bminventory"
"github.com/openshift/assisted-service/internal/common"
"github.com/openshift/assisted-service/internal/common/events"
eventsapi "github.com/openshift/assisted-service/internal/events/api"
"github.com/openshift/assisted-service/internal/gencrypto"
"github.com/openshift/assisted-service/internal/host"
"github.com/openshift/assisted-service/internal/oc"
"github.com/openshift/assisted-service/internal/spoke_k8s_client"
"github.com/openshift/assisted-service/models"
"github.com/openshift/assisted-service/pkg/auth"
logutil "github.com/openshift/assisted-service/pkg/log"
"github.com/openshift/assisted-service/restapi/operations/installer"
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"
"gorm.io/gorm"
certificatesv1 "k8s.io/api/certificates/v1"
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"
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"
"sigs.k8s.io/controller-runtime/pkg/source"
)
const (
AgentFinalizerName = "agent." + aiv1beta1.Group + "/ai-deprovision"
BaseLabelPrefix = aiv1beta1.Group + "/"
InventoryLabelPrefix = "inventory." + BaseLabelPrefix
AgentLabelHasNonrotationalDisk = InventoryLabelPrefix + "storage-hasnonrotationaldisk"
AgentLabelCpuArchitecture = InventoryLabelPrefix + "cpu-architecture"
AgentLabelCpuVirtEnabled = InventoryLabelPrefix + "cpu-virtenabled"
AgentLabelHostManufacturer = InventoryLabelPrefix + "host-manufacturer"
AgentLabelHostProductName = InventoryLabelPrefix + "host-productname"
AgentLabelHostIsVirtual = InventoryLabelPrefix + "host-isvirtual"
AgentLabelClusterDeploymentNamespace = BaseLabelPrefix + "clusterdeployment-namespace"
)
// AgentReconciler reconciles a Agent object
type AgentReconciler struct {
client.Client
APIReader client.Reader
Log logrus.FieldLogger
Scheme *runtime.Scheme
Installer bminventory.InstallerInternals
CRDEventsHandler CRDEventsHandler
ServiceBaseURL string
AuthType auth.AuthType
SpokeK8sClientFactory spoke_k8s_client.SpokeK8sClientFactory
ApproveCsrsRequeueDuration time.Duration
AgentContainerImage string
HostFSMountDir string
reclaimer *agentReclaimer
EventSender eventsapi.Sender
}
// +kubebuilder:rbac:groups=agent-install.openshift.io,resources=agents,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=agent-install.openshift.io,resources=agents/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=agent-install.openshift.io,resources=agents/ai-deprovision,verbs=update
// +kubebuilder:rbac:groups="",resources=secrets,verbs=get;list;watch
func (r *AgentReconciler) Reconcile(origCtx context.Context, req ctrl.Request) (ctrl.Result, error) {
ctx := addRequestIdIfNeeded(origCtx)
log := logutil.FromContext(ctx, r.Log).WithFields(
logrus.Fields{
"agent": req.Name,
"agent_namespace": req.Namespace,
})
defer func() {
log.Info("Agent Reconcile ended")
}()
log.Info("Agent Reconcile started")
agent := &aiv1beta1.Agent{}
if err := r.Get(ctx, req.NamespacedName, agent); err != nil {
log.WithError(err).Errorf("Failed to get resource %s", req.NamespacedName)
return ctrl.Result{}, client.IgnoreNotFound(err)
}
log = log.WithFields(logrus.Fields{"hostname": getAgentHostname(agent)})
origAgent := agent.DeepCopy()
if agent.ObjectMeta.Labels == nil {
agent.ObjectMeta.Labels = make(map[string]string)
}
res, err := r.handleAgentFinalizer(ctx, log, agent)
if res != nil {
if err != nil {
conditionsv1.SetStatusConditionNoHeartbeat(&agent.Status.Conditions, conditionsv1.Condition{
Type: aiv1beta1.CleanupCondition,
Status: corev1.ConditionFalse,
Reason: aiv1beta1.CleanupFailedReason,
Message: err.Error(),
})
if updateErr := r.Status().Update(ctx, agent); updateErr != nil {
log.WithError(updateErr).Error("failed to update agent status")
}
}
return *res, err
}
h, err := r.Installer.GetHostByKubeKey(req.NamespacedName)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return r.deleteAgent(ctx, log, req.NamespacedName)
} else {
log.WithError(err).Errorf("failed to retrieve Host %s from backend", agent.Name)
return ctrl.Result{RequeueAfter: defaultRequeueAfterOnError}, err
}
}
if err = r.setInfraEnvNameLabel(ctx, log, h, agent); err != nil {
log.WithError(err).Warnf("failed to set infraEnv name label on agent %s/%s", agent.Namespace, agent.Name)
}
if agent.Spec.ClusterDeploymentName == nil && h.ClusterID != nil {
log.Debugf("ClusterDeploymentName is unset in Agent %s. unbind", agent.Name)
return r.unbindHost(ctx, log, agent, origAgent, h)
}
if agent.Spec.ClusterDeploymentName != nil {
kubeKey := types.NamespacedName{
Namespace: agent.Spec.ClusterDeploymentName.Namespace,
Name: agent.Spec.ClusterDeploymentName.Name,
}
clusterDeployment := &hivev1.ClusterDeployment{}
// Retrieve clusterDeployment
if err = r.Get(ctx, kubeKey, clusterDeployment); err != nil {
errMsg := fmt.Sprintf("failed to get clusterDeployment with name %s in namespace %s",
agent.Spec.ClusterDeploymentName.Name, agent.Spec.ClusterDeploymentName.Namespace)
log.WithError(err).Error(errMsg)
// Update that we failed to retrieve the clusterDeployment
//TODO MGMT-7844 add mapping CD-ACI to rnot requeue always
return r.updateStatus(ctx, log, agent, origAgent, &h.Host, nil, errors.Wrapf(err, errMsg), true)
}
// Retrieve cluster by ClusterDeploymentName from the database
cluster, err2 := r.Installer.GetClusterByKubeKey(kubeKey)
if err2 != nil {
log.WithError(err2).Errorf("Fail to get cluster name: %s namespace: %s in backend",
agent.Spec.ClusterDeploymentName.Name, agent.Spec.ClusterDeploymentName.Namespace)
// Update that we failed to retrieve the cluster from the database
return r.updateStatus(ctx, log, agent, origAgent, &h.Host, nil, err2, true)
}
if h.ClusterID == nil {
log.Infof("ClusterDeploymentName is set in Agent %s. bind", agent.Name)
host, err2 := r.Installer.BindHostInternal(ctx, installer.BindHostParams{
HostID: *h.ID,
InfraEnvID: h.InfraEnvID,
BindHostParams: &models.BindHostParams{
ClusterID: cluster.ID,
},
})
if err2 != nil {
return r.updateStatus(ctx, log, agent, origAgent, &h.Host, nil, err2, !IsUserError(err2))
}
return r.updateStatus(ctx, log, agent, origAgent, &host.Host, cluster.ID, nil, true)
} else if *h.ClusterID != *cluster.ID {
log.Infof("ClusterDeploymentName is changed in Agent %s. unbind first", agent.Name)
return r.unbindHost(ctx, log, agent, origAgent, h)
}
}
// check for updates from user, compare spec and update if needed
h, err = r.updateIfNeeded(ctx, log, agent, h)
if err != nil {
return r.updateStatus(ctx, log, agent, origAgent, &h.Host, h.ClusterID, err, !IsUserError(err))
}
err = r.updateInventoryAndLabels(log, ctx, &h.Host, agent)
if err != nil {
return r.updateStatus(ctx, log, agent, origAgent, &h.Host, h.ClusterID, err, true)
}
err = r.updateNtpSources(log, &h.Host, agent)
if err != nil {
return r.updateStatus(ctx, log, agent, origAgent, &h.Host, h.ClusterID, err, true)
}
return r.updateStatus(ctx, log, agent, origAgent, &h.Host, h.ClusterID, nil, false)
}
func splitNamespacedName(nsName string) (string, string, error) {
parts := strings.Split(nsName, "/")
if len(parts) != 2 {
return "", "", fmt.Errorf("unable to parse namespaced name %s", nsName)
}
return parts[0], parts[1], nil
}
func deleteBMHForMachine(ctx context.Context, spokeClient client.Client, machine *machinev1beta1.Machine) error {
bmhNSName, haveBMH := machine.GetAnnotations()["metal3.io/BareMetalHost"]
if !haveBMH {
return nil
}
bmhNamespace, bmhName, err := splitNamespacedName(bmhNSName)
if err != nil {
return errors.Wrap(err, "failed to parse BMH name")
}
bmh := &bmh_v1alpha1.BareMetalHost{}
bmhKey := client.ObjectKey{Namespace: bmhNamespace, Name: bmhName}
if err = spokeClient.Get(ctx, bmhKey, bmh); err != nil {
return errors.Wrapf(err, "failed to get BMH %s", bmhNSName)
}
if err = spokeClient.Delete(ctx, bmh); err != nil {
return errors.Wrapf(err, "failed to delete BMH %s", bmhNSName)
}
// TODO: remove this once OCPBUGS-7581 is fixed
patch := client.MergeFrom(bmh.DeepCopy())
bmh.ObjectMeta.Finalizers = nil
if err = client.IgnoreNotFound(spokeClient.Patch(ctx, bmh, patch)); err != nil {
return errors.Wrapf(err, "failed to remove BMH %s finalizers", bmhNSName)
}
return nil
}
// removeSpokeResources removes all relevant resources from the agent's spoke cluster
// This includes all or some of the node, machine, BMH, and scaling the machineset depending on what is present
func (r *AgentReconciler) removeSpokeResources(ctx context.Context, log logrus.FieldLogger, agent *aiv1beta1.Agent) error {
spokeClient, err := r.spokeKubeClient(ctx, agent.Spec.ClusterDeploymentName)
if err != nil {
log.WithError(err).Error("failed to create spoke client")
return err
}
nodeName := getAgentHostname(agent)
log = log.WithField("node", nodeName)
nodeKey := client.ObjectKey{Name: nodeName}
node := &corev1.Node{}
if err = spokeClient.Get(ctx, nodeKey, node); err != nil {
if k8serrors.IsNotFound(err) {
log.Warn("node not found")
return nil
}
log.WithError(err).Error("failed to get node from spoke cluster")
return err
}
deleteNode := func() error {
nodeErr := client.IgnoreNotFound(spokeClient.Delete(ctx, node))
if nodeErr != nil {
log.WithError(nodeErr).Error("failed to delete node")
return nodeErr
}
log.Info("spoke node deleted")
return nil
}
machineNSName, haveMachine := node.GetAnnotations()["machine.openshift.io/machine"]
if !haveMachine {
return deleteNode()
}
machineNamespace, machineName, err := splitNamespacedName(machineNSName)
if err != nil {
log.WithError(err).Error("failed to parse machine name from node annotation")
return deleteNode()
}
log = log.WithFields(logrus.Fields{
"machine": machineName,
"machine_namespace": machineNamespace,
})
machine := &machinev1beta1.Machine{}
machineKey := client.ObjectKey{Namespace: machineNamespace, Name: machineName}
if err = spokeClient.Get(ctx, machineKey, machine); err != nil {
if k8serrors.IsNotFound(err) {
log.Warn("machine not found")
return deleteNode()
}
log.WithError(err).Error("failed to get machine")
return err
}
deleteMachine := func(deleteBMH bool) error {
if deleteBMH {
if bmhErr := deleteBMHForMachine(ctx, spokeClient, machine); client.IgnoreNotFound(bmhErr) != nil {
return bmhErr
}
}
if machineErr := spokeClient.Delete(ctx, machine); machineErr != nil {
log.WithError(machineErr).Error("failed to delete machine")
return machineErr
}
log.Infof("spoke machine deleted")
return nil
}
log.Infof("Annotating machine for deletion")
patch := client.MergeFrom(machine.DeepCopy())
// mark this particular machine for deletion if/when the set is scaled down
setAnnotation(&machine.ObjectMeta, "machine.openshift.io/delete-machine", "true")
// don't try to drain the node since it has already been done or timed out
setAnnotation(&machine.ObjectMeta, "machine.openshift.io/exclude-node-draining", "true")
if err = spokeClient.Patch(ctx, machine, patch); err != nil {
log.WithError(err).Error("failed to annotate machine for deletion")
return err
}
machineSetName, haveMachineSet := machine.GetLabels()["machine.openshift.io/cluster-api-machineset"]
if !haveMachineSet {
log.Info("no machineset label found")
return deleteMachine(true)
}
log = log.WithField("machine_set", machineSetName)
machineSet := &machinev1beta1.MachineSet{}
machineSetKey := client.ObjectKey{Namespace: machineNamespace, Name: machineSetName}
if err = spokeClient.Get(ctx, machineSetKey, machineSet); err != nil {
if k8serrors.IsNotFound(err) {
log.Warn("machine set not found")
return deleteMachine(true)
}
log.WithError(err).Error("failed to get machine set")
return err
}
patch = client.MergeFrom(machineSet.DeepCopy())
setAnnotation(&machineSet.ObjectMeta, "metal3.io/autoscale-to-hosts", "true")
if err = spokeClient.Patch(ctx, machineSet, patch); err != nil {
log.WithError(err).Error("failed to set machine set to autoscale")
return err
}
// Deleting the BMH while the machine set is configured for autoscaling will scale down the set
// This will delete the machine which was previously annotated which will remove the node
if err = deleteBMHForMachine(ctx, spokeClient, machine); client.IgnoreNotFound(err) != nil {
log.WithError(err).Error("failed to delete BMH")
return err
}
return nil
}
func (r *AgentReconciler) handleAgentFinalizer(ctx context.Context, log logrus.FieldLogger, agent *aiv1beta1.Agent) (*ctrl.Result, error) {
if agent.ObjectMeta.DeletionTimestamp.IsZero() { // agent not being deleted
// Register a finalizer if it is absent.
if !funk.ContainsString(agent.GetFinalizers(), AgentFinalizerName) {
controllerutil.AddFinalizer(agent, AgentFinalizerName)
if err := r.Update(ctx, agent); err != nil {
log.WithError(err).Errorf("failed to add finalizer %s to resource %s %s", AgentFinalizerName, agent.Name, agent.Namespace)
}
// After update there should not be any more changes on the object
// Update will return a new object so the creation of maps like annotations or labels is not valid anymore
return &ctrl.Result{Requeue: true}, nil
}
} else { // agent is being deleted
if funk.ContainsString(agent.GetFinalizers(), AgentFinalizerName) {
if _, has_annotation := agent.GetAnnotations()[BMH_FINALIZER_NAME]; has_annotation && agent.Spec.ClusterDeploymentName != nil {
// wait for BMH to be deleted
if foundBMH, err := r.bmhExists(ctx, agent); err != nil || foundBMH {
if err != nil {
log.WithError(err).Warnf("failed to determine if BMH exists for agent")
}
log.Info("waiting for BMH to be deleted")
return &ctrl.Result{RequeueAfter: defaultRequeueAfterOnError}, err
}
// only remove the spoke resources if the entire cluster isn't being deleted
clusterExists, err := r.clusterExists(ctx, agent)
if err != nil {
log.WithError(err).Errorf("failed to check cluster deployment presence")
return &ctrl.Result{}, err
}
if clusterExists {
if err := r.removeSpokeResources(ctx, log, agent); err != nil {
return &ctrl.Result{}, errors.Wrap(err, "failed to clean spoke cluster resources")
}
}
}
// deletion finalizer found, deregister the backend host and delete the agent
if reply, err := r.deregisterHostIfNeeded(ctx, log, types.NamespacedName{Namespace: agent.Namespace, Name: agent.Name}); err != nil {
log.WithError(err).Errorf("failed to run pre-deletion cleanup for finalizer %s on resource %s %s", AgentFinalizerName, agent.Name, agent.Namespace)
return &reply, err
}
// remove our finalizer from the list and update it.
controllerutil.RemoveFinalizer(agent, AgentFinalizerName)
if err := r.Update(ctx, agent); err != nil {
log.WithError(err).Errorf("failed to remove finalizer %s from resource %s %s", AgentFinalizerName, agent.Name, agent.Namespace)
return &ctrl.Result{Requeue: true}, err
}
}
// Stop reconciliation as the item is being deleted
return &ctrl.Result{}, nil
}
return nil, nil
}
// Validate that the CSR can be approved
func (r *AgentReconciler) shouldApproveCSR(csr *certificatesv1.CertificateSigningRequest, agent *aiv1beta1.Agent, validateNodeCsr nodeCsrValidator) (bool, error) {
x509CSR, err := getX509ParsedRequest(csr)
if err != nil {
return false, err
}
if !isCsrAssociatedWithAgent(x509CSR, agent) {
return false, nil
}
return validateNodeCsr(agent, csr, x509CSR)
}
func (r *AgentReconciler) approveAIHostsCSRs(ctx context.Context, clients spoke_k8s_client.SpokeK8sClient, agent *aiv1beta1.Agent, validateNodeCsr nodeCsrValidator) {
csrList, err := clients.ListCsrs(ctx)
if err != nil {
r.Log.WithError(err).Errorf("Failed to get CSRs for agent %s/%s", agent.Namespace, agent.Name)
return
}
for i := range csrList.Items {
csr := &csrList.Items[i]
if !isCsrApproved(csr) {
shouldApprove, err := r.shouldApproveCSR(csr, agent, validateNodeCsr)
if err != nil || !shouldApprove {
if err != nil {
r.Log.WithError(err).Errorf("Failed checking if CSR %s should be approved for agent %s/%s",
csr.Name, agent.Namespace, agent.Name)
}
continue
}
if err = clients.ApproveCsr(ctx, csr); err != nil {
r.Log.WithError(err).Errorf("Failed to approve CSR %s for agent %s/%s", csr.Name, agent.Namespace, agent.Name)
continue
}
}
}
}
func (r *AgentReconciler) spokeKubeClient(ctx context.Context, clusterRef *aiv1beta1.ClusterReference) (spoke_k8s_client.SpokeK8sClient, error) {
secret, err := spokeKubeconfigSecret(ctx, r.Log, r.Client, r.APIReader, clusterRef)
if err != nil {
r.Log.WithError(err).Errorf("failed to get spoke secret for cluster %s/%s", clusterRef.Namespace, clusterRef.Name)
return nil, err
}
return r.SpokeK8sClientFactory.CreateFromSecret(secret)
}
func (r *AgentReconciler) notifyNumberOfReboots(ctx context.Context, h *models.Host, node *corev1.Node, clusterRef *aiv1beta1.ClusterReference) error {
if !isNodeReady(node) {
return nil
}
secret, err := spokeKubeconfigSecret(ctx, r.Log, r.Client, r.APIReader, clusterRef)
if err != nil {
r.Log.WithError(err).Errorf("failed to get spoke secret for cluster %s/%s", clusterRef.Namespace, clusterRef.Name)
return err
}
kubeconfig, err := spoke_k8s_client.KubeconfigFromSecret(secret)
if err != nil {
r.Log.WithError(err).Errorf("failed to get kubeconfig from secret for cluster %s/%s", clusterRef.Namespace, clusterRef.Name)
return err
}
dbg := oc.NewDebug(kubeconfig)
reboots, err := dbg.RebootsForNode(node.Name)
if err != nil {
r.Log.WithError(err).Errorf("failed to get number of reboots for node %s, cluster %s/%s", node.Name,
clusterRef.Namespace, clusterRef.Name)
return err
}
events.SendRebootsForNodeEvent(ctx, r.EventSender, *h.ID, node.Name, h.InfraEnvID, h.ClusterID, int64(reboots))
return nil
}
// Attempt to approve CSRs for agent. If already approved then the node will be marked as done
// requeue means that approval will be attempted again
func (r *AgentReconciler) tryApproveDay2CSRs(ctx context.Context, agent *aiv1beta1.Agent, node *corev1.Node, client spoke_k8s_client.SpokeK8sClient) {
r.Log.Infof("Approving CSRs for agent %s/%s", agent.Namespace, agent.Name)
var validateNodeCsr nodeCsrValidator
if node == nil {
validateNodeCsr = validateNodeClientCSR
} else {
validateNodeCsr = createNodeServerCsrValidator(node)
}
// Even if node is already ready, we try approving last time
r.approveAIHostsCSRs(ctx, client, agent, validateNodeCsr)
}
func (r *AgentReconciler) bmhExists(ctx context.Context, agent *aiv1beta1.Agent) (bool, error) {
bmhName, ok := agent.ObjectMeta.Labels[AGENT_BMH_LABEL]
if !ok {
return false, nil
}
bmhKey := types.NamespacedName{
Name: bmhName,
Namespace: agent.Namespace,
}
if err := r.Client.Get(ctx, bmhKey, &bmh_v1alpha1.BareMetalHost{}); err != nil {
return false, client.IgnoreNotFound(err)
}
return true, nil
}
func (r *AgentReconciler) clusterExists(ctx context.Context, agent *aiv1beta1.Agent) (bool, error) {
if agent.Spec.ClusterDeploymentName == nil {
return false, nil
}
cdKey := types.NamespacedName{
Name: agent.Spec.ClusterDeploymentName.Name,
Namespace: agent.Spec.ClusterDeploymentName.Namespace,
}
cd := &hivev1.ClusterDeployment{}
if err := r.Client.Get(ctx, cdKey, cd); err != nil {
return false, client.IgnoreNotFound(err)
}
return cd.DeletionTimestamp.IsZero(), nil
}
func (r *AgentReconciler) shouldReclaimOnUnbind(ctx context.Context, agent *aiv1beta1.Agent, clusterRef *aiv1beta1.ClusterReference) bool {
// default to not attempting to reclaim as that's the safer route
if foundBMH, err := r.bmhExists(ctx, agent); err != nil || foundBMH {
if err != nil {
r.Log.WithError(err).Warnf("failed to determine if BMH exists for agent")
}
return false
}
return true
}
func (r *AgentReconciler) runReclaimAgent(ctx context.Context, log logrus.FieldLogger, agent *aiv1beta1.Agent, clusterRef *aiv1beta1.ClusterReference, host *common.Host) error {
client, err := r.spokeKubeClient(ctx, clusterRef)
if err != nil {
r.Log.WithError(err).Warnf("failed to create spoke kube client")
return err
}
hostname := getAgentHostname(agent)
r.Log.Infof("Starting agent pod for reclaim on node %s", hostname)
if err := ensureSpokeNamespace(ctx, client, log); err != nil {
return err
}
if err := ensureSpokeServiceAccount(ctx, client, log); err != nil {
return err
}
if err := ensureSpokeRole(ctx, client, log); err != nil {
return err
}
if err := ensureSpokeRoleBinding(ctx, client, log); err != nil {
return err
}
if err := r.reclaimer.ensureSpokeAgentSecret(ctx, client, log, host.InfraEnvID.String()); err != nil {
return err
}
if err := r.reclaimer.ensureSpokeAgentCertCM(ctx, client, log); err != nil {
return err
}
return r.reclaimer.createNextStepRunnerDaemonSet(ctx, client, log, hostname, host.InfraEnvID.String(), host.ID.String())
}
func (r *AgentReconciler) unbindHost(ctx context.Context, log logrus.FieldLogger, agent, origAgent *aiv1beta1.Agent, h *common.Host) (ctrl.Result, error) {
var reclaim bool
// log and don't reclaim if anything fails here
cluster, err := r.Installer.GetClusterInternal(ctx, installer.V2GetClusterParams{ClusterID: *h.ClusterID})
if err != nil || cluster.KubeKeyName == "" || cluster.KubeKeyNamespace == "" {
if err != nil {
log.WithError(err).Warnf("failed to get cluster %s, not attempting reclaim", h.ClusterID)
} else {
log.Warnf("cluster %s missing kube key (%s/%s), not attempting reclaim", h.ClusterID, cluster.KubeKeyNamespace, cluster.KubeKeyName)
}
} else {
clusterRef := &aiv1beta1.ClusterReference{Namespace: cluster.KubeKeyNamespace, Name: cluster.KubeKeyName}
reclaim = r.shouldReclaimOnUnbind(ctx, origAgent, clusterRef)
if reclaim {
if err = r.runReclaimAgent(ctx, log, agent, clusterRef, h); err != nil {
log.WithError(err).Warn("failed to start agent on spoke cluster to reclaim")
reclaim = false
}
}
}
params := installer.UnbindHostParams{
HostID: *h.ID,
InfraEnvID: h.InfraEnvID,
}
host, err := r.Installer.UnbindHostInternal(ctx, params, reclaim, bminventory.NonInteractive)
if err != nil {
return r.updateStatus(ctx, log, agent, origAgent, &h.Host, nil, err, !IsUserError(err))
}
return r.updateStatus(ctx, log, agent, origAgent, &host.Host, h.ClusterID, nil, true)
}
func (r *AgentReconciler) deleteAgent(ctx context.Context, log logrus.FieldLogger, agent types.NamespacedName) (ctrl.Result, error) {
agentToDelete := &aiv1beta1.Agent{
ObjectMeta: metav1.ObjectMeta{
Name: agent.Name,
Namespace: agent.Namespace,
},
}
if delErr := r.Client.Delete(ctx, agentToDelete); delErr != nil {
log.WithError(delErr).Errorf("Failed to delete resource %s %s", agent.Name, agent.Namespace)
return ctrl.Result{Requeue: true}, delErr
}
return ctrl.Result{}, nil
}
func (r *AgentReconciler) deregisterHostIfNeeded(ctx context.Context, log logrus.FieldLogger, key types.NamespacedName) (ctrl.Result, error) {
buildReply := func(err error) (ctrl.Result, error) {
reply := ctrl.Result{}
if err == nil {
return reply, nil
}
reply.RequeueAfter = defaultRequeueAfterOnError
err = errors.Wrapf(err, "failed to deregister host: %s", key.Name)
log.Error(err)
return reply, err
}
h, err := r.Installer.GetHostByKubeKey(key)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
// return if from any reason host is already deleted from db (or never existed)
return buildReply(nil)
} else {
return buildReply(err)
}
}
err = r.Installer.V2DeregisterHostInternal(
ctx, installer.V2DeregisterHostParams{
InfraEnvID: h.InfraEnvID,
HostID: *h.ID,
}, bminventory.NonInteractive)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
// return if from any reason host is already deleted from db
return buildReply(nil)
} else {
return buildReply(err)
}
}
log.Infof("Host resource deleted, Unregistered host: %s", h.ID.String())
return buildReply(nil)
}
// CSRs should be approved in the following cases:
// * Agent belongs to a none platform cluster
// * No BMH exists for agent
func (r *AgentReconciler) shouldApproveCSRsForAgent(ctx context.Context, agent *aiv1beta1.Agent, h *models.Host) (bool, error) {
if funk.Contains([]models.HostStage{models.HostStageRebooting, models.HostStageJoined}, h.Progress.CurrentStage) {
isNone, err := isAgentInNonePlatformCluster(ctx, r.Client, agent)
if err != nil {
return false, err
}
if isNone {
return true, nil
}
bmhExists, err := r.bmhExists(ctx, agent)
if err != nil {
return false, err
}
return !bmhExists, nil
}
return false, nil
}
func marshalNodeLabels(nodeLabels map[string]string) (string, error) {
b, err := json.Marshal(&nodeLabels)
if err != nil {
return "", err
}
return string(b), err
}
func (r *AgentReconciler) applyDay2NodeLabels(ctx context.Context, log logrus.FieldLogger, agent *aiv1beta1.Agent, node *corev1.Node, client spoke_k8s_client.SpokeK8sClient) error {
if funk.IsEmpty(agent.Spec.NodeLabels) || !isNodeReady(node) {
return nil
}
labels := node.GetLabels()
if labels == nil {
labels = make(map[string]string)
}
updateNeeded := false
for key, value := range agent.Spec.NodeLabels {
if existingValue, ok := labels[key]; !ok || existingValue != value {
updateNeeded = true
break
}
}
if updateNeeded {
log.Infof("Setting node labels %+v on node %s/%s", agent.Spec.NodeLabels, node.Namespace, node.Name)
marshalledLabels, err := marshalNodeLabels(agent.Spec.NodeLabels)
if err != nil {
return err
}
return client.PatchNodeLabels(ctx, node.Name, marshalledLabels)
}
return nil
}
// updateStatus is updating all the Agent Conditions.
// In case that an error has ocurred when trying to sync the Spec, the error (syncErr) is presented in SpecSyncedCondition.
// Internal bool differentiate between backend server error (internal HTTP 5XX) and user input error (HTTP 4XXX)
func (r *AgentReconciler) updateStatus(ctx context.Context, log logrus.FieldLogger, agent, origAgent *aiv1beta1.Agent, h *models.Host, clusterId *strfmt.UUID, syncErr error, internal bool) (ctrl.Result, error) {
var (
err error
shouldAutoApproveCSRs bool
spokeClient spoke_k8s_client.SpokeK8sClient
node *corev1.Node
)
ret := ctrl.Result{}
specSynced(agent, syncErr, internal)
if h != nil && h.Status != nil {
agent.Status.Bootstrap = h.Bootstrap
agent.Status.Role = h.Role
if h.SuggestedRole != "" && h.Role == models.HostRoleAutoAssign {
agent.Status.Role = h.SuggestedRole
}
agent.Status.DebugInfo.State = swag.StringValue(h.Status)
agent.Status.DebugInfo.StateInfo = swag.StringValue(h.StatusInfo)
agent.Status.InstallationDiskID = h.InstallationDiskID
if h.ValidationsInfo != "" {
newValidationsInfo := ValidationsStatus{}
err = json.Unmarshal([]byte(h.ValidationsInfo), &newValidationsInfo)
if err != nil {
log.WithError(err).Error("failed to umarshed ValidationsInfo")
return ctrl.Result{}, err
}
agent.Status.ValidationsInfo = newValidationsInfo
}
if h.Progress != nil && h.Progress.CurrentStage != "" {
// In case the node didn't reboot yet, we get the stage from the host (else)
if swag.StringValue(h.Kind) == models.HostKindAddToExistingClusterHost &&
funk.Contains([]models.HostStage{models.HostStageRebooting, models.HostStageJoined, models.HostStageConfiguring}, h.Progress.CurrentStage) &&
agent.Spec.ClusterDeploymentName != nil {
spokeClient, err = r.spokeKubeClient(ctx, agent.Spec.ClusterDeploymentName)
if err != nil {
r.Log.WithError(err).Errorf("Agent %s/%s: Failed to create spoke client", agent.Namespace, agent.Name)
return ctrl.Result{}, err
}
if shouldAutoApproveCSRs, err = r.shouldApproveCSRsForAgent(ctx, agent, h); err != nil {
log.WithError(err).Errorf("Failed to determine if agent %s/%s is rebooting and belongs to none platform cluster or has an associated BMH", agent.Namespace, agent.Name)
return ctrl.Result{RequeueAfter: defaultRequeueAfterOnError}, nil
}
// TODO: Node name might be FQDN and not just host name if cluster is IPv6
node, err = spokeClient.GetNode(ctx, getAgentHostname(agent))
if err != nil {
if !k8serrors.IsNotFound(err) {
r.Log.WithError(err).Errorf("agent %s/%s: failed to get node", agent.Namespace, agent.Name)
return ctrl.Result{RequeueAfter: defaultRequeueAfterOnError}, err
}
node = nil
}
if shouldAutoApproveCSRs {
r.tryApproveDay2CSRs(ctx, agent, node, spokeClient)
}
if err = r.applyDay2NodeLabels(ctx, log, agent, node, spokeClient); err != nil {
log.WithError(err).Errorf("Failed to apply labels for day2 node %s/%s", agent.Namespace, agent.Name)
return ctrl.Result{RequeueAfter: defaultRequeueAfterOnError}, err
}
if err = r.notifyNumberOfReboots(ctx, h, node, agent.Spec.ClusterDeploymentName); err != nil {
log.WithError(err).Errorf("Failed to notify number of reboots for day2 node %s/%s", agent.Namespace, agent.Name)
}
if err = r.UpdateDay2InstallPogress(ctx, h, agent, node); err != nil {
return ctrl.Result{RequeueAfter: defaultRequeueAfterOnError}, err
}
if agent.Status.Progress.CurrentStage != models.HostStageDone {
ret = ctrl.Result{RequeueAfter: r.ApproveCsrsRequeueDuration}
}
} else {
// sync day1 progress stage
agent.Status.Progress.CurrentStage = h.Progress.CurrentStage
}
agent.Status.Progress.ProgressInfo = h.Progress.ProgressInfo
agent.Status.Progress.InstallationPercentage = h.Progress.InstallationPercentage
stageStartTime := metav1.NewTime(time.Time(h.Progress.StageStartedAt))
agent.Status.Progress.StageStartTime = &stageStartTime
stageUpdateTime := metav1.NewTime(time.Time(h.Progress.StageUpdatedAt))
agent.Status.Progress.StageUpdateTime = &stageUpdateTime
agent.Status.Progress.ProgressStages = h.ProgressStages
} else {
agent.Status.Progress = aiv1beta1.HostProgressInfo{}
}
status := *h.Status
if clusterId != nil {
err = r.populateEventsURL(log, agent, h.InfraEnvID.String())
if err != nil {
return ctrl.Result{Requeue: true}, nil
}
if agent.Status.DebugInfo.LogsURL == "" && !time.Time(h.LogsCollectedAt).Equal(time.Time{}) { // logs collection time is updated means logs are available
var logsURL string
logsURL, err = generateControllerLogsDownloadURL(r.ServiceBaseURL, clusterId.String(), r.AuthType, agent.Name, "host")
if err != nil {
log.WithError(err).Error("failed to generate controller logs URL")
return ctrl.Result{}, err
}
agent.Status.DebugInfo.LogsURL = logsURL
}
}
connected(agent, status)
requirementsMet(agent, status)
validated(agent, status, h)
installed(agent, status, swag.StringValue(h.StatusInfo))
bound(agent, status, h)
} else {
setConditionsUnknown(agent)
}
if !reflect.DeepEqual(agent, origAgent) {
if updateErr := r.Status().Update(ctx, agent); updateErr != nil {
log.WithError(updateErr).Error("failed to update agent Status")
return ctrl.Result{Requeue: true}, nil
}
} else {
log.Debugf("Agent %s/%s: update skipped", agent.Namespace, agent.Name)
}
if syncErr != nil && internal {
return ctrl.Result{RequeueAfter: defaultRequeueAfterOnError}, nil
}
return ret, nil
}
func (r *AgentReconciler) UpdateDay2InstallPogress(ctx context.Context, h *models.Host, agent *aiv1beta1.Agent, node *corev1.Node) error {
if node == nil {
// In case the node not found we get the stage from the host
agent.Status.Progress.CurrentStage = h.Progress.CurrentStage
// requeue in order to keep reconciling until the node show up
return nil
}
var err error
if isNodeReady(node) {
err = r.updateHostInstallProgress(ctx, h, models.HostStageDone)
agent.Status.Progress.CurrentStage = models.HostStageDone
// now that the node is done there is no need to requeue
} else {
err = r.updateHostInstallProgress(ctx, h, models.HostStageJoined)
agent.Status.Progress.CurrentStage = models.HostStageJoined
}
if err != nil {
r.Log.WithError(err).Errorf("Failed updating host %s install progress", h.ID)
return err
}
return nil
}
func (r *AgentReconciler) populateEventsURL(log logrus.FieldLogger, agent *aiv1beta1.Agent, infraEnvId string) error {
if agent.Status.DebugInfo.EventsURL == "" {
tokenGen := gencrypto.CryptoPair{JWTKeyType: gencrypto.InfraEnvKey, JWTKeyValue: infraEnvId}
eventUrl, err := generateEventsURL(r.ServiceBaseURL, r.AuthType, tokenGen, "host_id", agent.Name)
if err != nil {
log.WithError(err).Error("failed to generate Events URL")
return err
}
agent.Status.DebugInfo.EventsURL = eventUrl
}
return nil
}
func generateControllerLogsDownloadURL(baseURL string, clusterID string, authType auth.AuthType, host string, logsType string) (string, error) {
hostID := strfmt.UUID(host)
builder := &installer.V2DownloadClusterLogsURL{
ClusterID: strfmt.UUID(clusterID),
HostID: &hostID,
LogsType: &logsType,
}
u, err := builder.Build()
if err != nil {
return "", err
}
downloadURL := fmt.Sprintf("%s%s", baseURL, u.RequestURI())
if authType != auth.TypeLocal {
return downloadURL, nil
}
downloadURL, err = gencrypto.SignURL(downloadURL, clusterID, gencrypto.ClusterKey)
if err != nil {
return "", errors.Wrapf(err, "failed to sign %s controller logs URL for host %s", logsType, host)
}
return downloadURL, nil
}
func setConditionsUnknown(agent *aiv1beta1.Agent) {
agent.Status.DebugInfo.State = ""
agent.Status.DebugInfo.StateInfo = ""
conditionsv1.SetStatusConditionNoHeartbeat(&agent.Status.Conditions, conditionsv1.Condition{
Type: aiv1beta1.InstalledCondition,
Status: corev1.ConditionUnknown,
Reason: aiv1beta1.NotAvailableReason,
Message: aiv1beta1.NotAvailableMsg,
})
conditionsv1.SetStatusConditionNoHeartbeat(&agent.Status.Conditions, conditionsv1.Condition{
Type: aiv1beta1.ConnectedCondition,
Status: corev1.ConditionUnknown,
Reason: aiv1beta1.NotAvailableReason,
Message: aiv1beta1.NotAvailableMsg,
})
conditionsv1.SetStatusConditionNoHeartbeat(&agent.Status.Conditions, conditionsv1.Condition{
Type: aiv1beta1.RequirementsMetCondition,
Status: corev1.ConditionUnknown,
Reason: aiv1beta1.NotAvailableReason,
Message: aiv1beta1.NotAvailableMsg,
})
conditionsv1.SetStatusConditionNoHeartbeat(&agent.Status.Conditions, conditionsv1.Condition{
Type: aiv1beta1.ValidatedCondition,
Status: corev1.ConditionUnknown,
Reason: aiv1beta1.NotAvailableReason,
Message: aiv1beta1.NotAvailableMsg,
})
conditionsv1.SetStatusConditionNoHeartbeat(&agent.Status.Conditions, conditionsv1.Condition{
Type: aiv1beta1.BoundCondition,
Status: corev1.ConditionUnknown,
Reason: aiv1beta1.NotAvailableReason,
Message: aiv1beta1.NotAvailableMsg,
})
}
// specSynced is updating the Agent SpecSynced Condition.
// Internal bool differentiate between the reason BackendErrorReason/InputErrorReason.
// if true then it is a backend server error (internal HTTP 5XX) otherwise an user input error (HTTP 4XXX)
func specSynced(agent *aiv1beta1.Agent, syncErr error, internal bool) {
var condStatus corev1.ConditionStatus
var reason string
var msg string
if syncErr == nil {
condStatus = corev1.ConditionTrue
reason = aiv1beta1.SyncedOkReason
msg = aiv1beta1.SyncedOkMsg
} else {
condStatus = corev1.ConditionFalse
if internal {
reason = aiv1beta1.BackendErrorReason
msg = aiv1beta1.BackendErrorMsg + " " + syncErr.Error()
} else {
reason = aiv1beta1.InputErrorReason
msg = aiv1beta1.InputErrorMsg + " " + syncErr.Error()
}
}
conditionsv1.SetStatusConditionNoHeartbeat(&agent.Status.Conditions, conditionsv1.Condition{
Type: aiv1beta1.SpecSyncedCondition,
Status: condStatus,