Skip to content

Commit 5c2d9ae

Browse files
committed
Move AWSMachinePool AWSMachine functions to shared file, fix labels
1 parent 8547215 commit 5c2d9ae

File tree

3 files changed

+193
-173
lines changed

3 files changed

+193
-173
lines changed

exp/controllers/awsmachinepool_controller.go

-171
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,6 @@ import (
2222
"fmt"
2323
"time"
2424

25-
"github.com/aws/aws-sdk-go/aws"
26-
"github.com/go-logr/logr"
2725
"github.com/google/go-cmp/cmp"
2826
"github.com/google/go-cmp/cmp/cmpopts"
2927
"github.com/pkg/errors"
@@ -33,7 +31,6 @@ import (
3331
"k8s.io/apimachinery/pkg/runtime/schema"
3432
"k8s.io/client-go/tools/record"
3533
"k8s.io/klog/v2"
36-
"k8s.io/utils/ptr"
3734
ctrl "sigs.k8s.io/controller-runtime"
3835
"sigs.k8s.io/controller-runtime/pkg/client"
3936
"sigs.k8s.io/controller-runtime/pkg/controller"
@@ -56,7 +53,6 @@ import (
5653
"sigs.k8s.io/cluster-api/util"
5754
"sigs.k8s.io/cluster-api/util/annotations"
5855
"sigs.k8s.io/cluster-api/util/conditions"
59-
"sigs.k8s.io/cluster-api/util/labels/format"
6056
"sigs.k8s.io/cluster-api/util/predicates"
6157
)
6258

@@ -453,173 +449,6 @@ func (r *AWSMachinePoolReconciler) reconcileDelete(ctx context.Context, machineP
453449
return nil
454450
}
455451

456-
func reconcileDeleteAWSMachines(ctx context.Context, mp *expclusterv1.MachinePool, client client.Client, l logr.Logger) error {
457-
awsMachineList, err := getAWSMachines(ctx, mp, client)
458-
if err != nil {
459-
return err
460-
}
461-
for i := range awsMachineList.Items {
462-
awsMachine := awsMachineList.Items[i]
463-
if awsMachine.DeletionTimestamp.IsZero() {
464-
continue
465-
}
466-
logger := l.WithValues("awsmachine", klog.KObj(&awsMachine))
467-
// delete the owner Machine resource for the AWSMachine so that CAPI can clean up gracefully
468-
machine, err := util.GetOwnerMachine(ctx, client, awsMachine.ObjectMeta)
469-
if err != nil {
470-
logger.V(2).Info("Failed to get owner Machine", "err", err.Error())
471-
continue
472-
}
473-
474-
if err := client.Delete(ctx, machine); err != nil {
475-
logger.V(2).Info("Failed to delete owner Machine", "err", err.Error())
476-
}
477-
}
478-
return nil
479-
}
480-
481-
func getAWSMachines(ctx context.Context, mp *expclusterv1.MachinePool, kubeClient client.Client) (*infrav1.AWSMachineList, error) {
482-
awsMachineList := &infrav1.AWSMachineList{}
483-
labels := map[string]string{
484-
clusterv1.MachinePoolNameLabel: mp.Name,
485-
clusterv1.ClusterNameLabel: mp.Spec.ClusterName,
486-
}
487-
if err := kubeClient.List(ctx, awsMachineList, client.InNamespace(mp.Namespace), client.MatchingLabels(labels)); err != nil {
488-
return nil, err
489-
}
490-
return awsMachineList, nil
491-
}
492-
493-
func createAWSMachinesIfNotExists(ctx context.Context, awsMachineList *infrav1.AWSMachineList, mp *expclusterv1.MachinePool, infraMachinePoolMeta *metav1.ObjectMeta, infraMachinePoolType *metav1.TypeMeta, existingASG *expinfrav1.AutoScalingGroup, l logr.Logger, client client.Client, ec2Svc services.EC2Interface) error {
494-
l.V(4).Info("Creating missing AWSMachines")
495-
496-
providerIDToAWSMachine := make(map[string]infrav1.AWSMachine, len(awsMachineList.Items))
497-
for i := range awsMachineList.Items {
498-
awsMachine := awsMachineList.Items[i]
499-
if awsMachine.Spec.ProviderID == nil || *awsMachine.Spec.ProviderID == "" {
500-
continue
501-
}
502-
providerID := *awsMachine.Spec.ProviderID
503-
providerIDToAWSMachine[providerID] = awsMachine
504-
}
505-
506-
for i := range existingASG.Instances {
507-
instanceID := existingASG.Instances[i].ID
508-
providerID := fmt.Sprintf("aws:///%s/%s", existingASG.Instances[i].AvailabilityZone, instanceID)
509-
510-
instanceLogger := l.WithValues("providerID", providerID, "instanceID", instanceID, "asg", existingASG.Name)
511-
instanceLogger.V(4).Info("Checking if machine pool AWSMachine is up to date")
512-
if _, exists := providerIDToAWSMachine[providerID]; exists {
513-
continue
514-
}
515-
516-
instance, err := ec2Svc.InstanceIfExists(&instanceID)
517-
if errors.Is(err, ec2.ErrInstanceNotFoundByID) {
518-
instanceLogger.V(4).Info("Instance not found, it may have already been deleted")
519-
continue
520-
}
521-
if err != nil {
522-
return fmt.Errorf("failed to look up EC2 instance %q: %w", instanceID, err)
523-
}
524-
525-
securityGroups := make([]infrav1.AWSResourceReference, 0, len(instance.SecurityGroupIDs))
526-
for j := range instance.SecurityGroupIDs {
527-
securityGroups = append(securityGroups, infrav1.AWSResourceReference{
528-
ID: aws.String(instance.SecurityGroupIDs[j]),
529-
})
530-
}
531-
532-
awsMachine := &infrav1.AWSMachine{
533-
ObjectMeta: metav1.ObjectMeta{
534-
Namespace: mp.Namespace,
535-
GenerateName: fmt.Sprintf("%s-", existingASG.Name),
536-
Labels: map[string]string{
537-
clusterv1.MachinePoolNameLabel: format.MustFormatValue(mp.Name),
538-
clusterv1.ClusterNameLabel: mp.Spec.ClusterName,
539-
},
540-
OwnerReferences: []metav1.OwnerReference{
541-
{
542-
APIVersion: infraMachinePoolType.APIVersion,
543-
Kind: infraMachinePoolType.Kind,
544-
Name: infraMachinePoolMeta.Name,
545-
BlockOwnerDeletion: ptr.To(true),
546-
UID: infraMachinePoolMeta.UID,
547-
},
548-
},
549-
},
550-
Spec: infrav1.AWSMachineSpec{
551-
ProviderID: aws.String(providerID),
552-
InstanceID: aws.String(instanceID),
553-
554-
// Store some extra fields for informational purposes (not needed by CAPA)
555-
AMI: infrav1.AMIReference{
556-
ID: aws.String(instance.ImageID),
557-
},
558-
InstanceType: instance.Type,
559-
PublicIP: aws.Bool(instance.PublicIP != nil),
560-
SSHKeyName: instance.SSHKeyName,
561-
InstanceMetadataOptions: instance.InstanceMetadataOptions,
562-
IAMInstanceProfile: instance.IAMProfile,
563-
AdditionalSecurityGroups: securityGroups,
564-
Subnet: &infrav1.AWSResourceReference{ID: aws.String(instance.SubnetID)},
565-
RootVolume: instance.RootVolume,
566-
NonRootVolumes: instance.NonRootVolumes,
567-
NetworkInterfaces: instance.NetworkInterfaces,
568-
CloudInit: infrav1.CloudInit{},
569-
SpotMarketOptions: instance.SpotMarketOptions,
570-
Tenancy: instance.Tenancy,
571-
},
572-
}
573-
instanceLogger.V(4).Info("Creating AWSMachine")
574-
if err := client.Create(ctx, awsMachine); err != nil {
575-
return fmt.Errorf("failed to create AWSMachine: %w", err)
576-
}
577-
}
578-
return nil
579-
}
580-
581-
func deleteOrphanedAWSMachines(ctx context.Context, awsMachineList *infrav1.AWSMachineList, existingASG *expinfrav1.AutoScalingGroup, l logr.Logger, client client.Client) error {
582-
l.V(4).Info("Deleting orphaned AWSMachines")
583-
providerIDToInstance := make(map[string]infrav1.Instance, len(existingASG.Instances))
584-
for i := range existingASG.Instances {
585-
providerID := fmt.Sprintf("aws:///%s/%s", existingASG.Instances[i].AvailabilityZone, existingASG.Instances[i].ID)
586-
providerIDToInstance[providerID] = existingASG.Instances[i]
587-
}
588-
589-
for i := range awsMachineList.Items {
590-
awsMachine := awsMachineList.Items[i]
591-
if awsMachine.Spec.ProviderID == nil || *awsMachine.Spec.ProviderID == "" {
592-
continue
593-
}
594-
595-
providerID := *awsMachine.Spec.ProviderID
596-
if _, exists := providerIDToInstance[providerID]; exists {
597-
continue
598-
}
599-
600-
machine, err := util.GetOwnerMachine(ctx, client, awsMachine.ObjectMeta)
601-
if err != nil {
602-
return fmt.Errorf("failed to get owner Machine for %s/%s: %w", awsMachine.Namespace, awsMachine.Name, err)
603-
}
604-
machineLogger := l.WithValues("machine", klog.KObj(machine), "awsmachine", klog.KObj(&awsMachine), "ProviderID", providerID)
605-
machineLogger.V(4).Info("Deleting orphaned Machine")
606-
if machine == nil {
607-
machineLogger.Info("No machine owner found for AWSMachine, deleting AWSMachine anyway.")
608-
if err := client.Delete(ctx, &awsMachine); err != nil {
609-
return fmt.Errorf("failed to delete orphan AWSMachine %s/%s: %w", awsMachine.Namespace, awsMachine.Name, err)
610-
}
611-
machineLogger.V(4).Info("Deleted AWSMachine")
612-
continue
613-
}
614-
615-
if err := client.Delete(ctx, machine); err != nil {
616-
return fmt.Errorf("failed to delete orphan Machine %s/%s: %w", machine.Namespace, machine.Name, err)
617-
}
618-
machineLogger.V(4).Info("Deleted Machine")
619-
}
620-
return nil
621-
}
622-
623452
func (r *AWSMachinePoolReconciler) updatePool(machinePoolScope *scope.MachinePoolScope, clusterScope cloud.ClusterScoper, existingASG *expinfrav1.AutoScalingGroup) error {
624453
asgSvc := r.getASGService(clusterScope)
625454

exp/controllers/awsmachinepool_controller_test.go

+3-2
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ import (
5050
capierrors "sigs.k8s.io/cluster-api/errors"
5151
expclusterv1 "sigs.k8s.io/cluster-api/exp/api/v1beta1"
5252
"sigs.k8s.io/cluster-api/util/conditions"
53+
"sigs.k8s.io/cluster-api/util/labels/format"
5354
"sigs.k8s.io/cluster-api/util/patch"
5455
)
5556

@@ -357,7 +358,7 @@ func TestAWSMachinePoolReconciler(t *testing.T) {
357358
Namespace: ms.AWSMachinePool.Namespace,
358359
Name: "name-1",
359360
Labels: map[string]string{
360-
clusterv1.MachinePoolNameLabel: ms.MachinePool.Name,
361+
clusterv1.MachinePoolNameLabel: format.MustFormatValue(ms.MachinePool.Name),
361362
clusterv1.ClusterNameLabel: ms.MachinePool.Spec.ClusterName,
362363
},
363364
OwnerReferences: []metav1.OwnerReference{
@@ -389,7 +390,7 @@ func TestAWSMachinePoolReconciler(t *testing.T) {
389390
Namespace: ms.AWSMachinePool.Namespace,
390391
Name: "name-2",
391392
Labels: map[string]string{
392-
clusterv1.MachinePoolNameLabel: ms.MachinePool.Name,
393+
clusterv1.MachinePoolNameLabel: format.MustFormatValue(ms.MachinePool.Name),
393394
clusterv1.ClusterNameLabel: ms.MachinePool.Spec.ClusterName,
394395
},
395396
OwnerReferences: []metav1.OwnerReference{

0 commit comments

Comments
 (0)