From 5c13dd396afb46acece71ae2493670a06fe93496 Mon Sep 17 00:00:00 2001 From: Jack Francis Date: Fri, 31 Oct 2025 15:25:03 -0700 Subject: [PATCH] Replace autorest/to with k8s.io/utils/ptr --- .../cloudprovider/azure/azure_agent_pool.go | 4 +- .../azure/azure_agent_pool_test.go | 48 +++---- .../cloudprovider/azure/azure_cache.go | 7 +- .../cloudprovider/azure/azure_cache_test.go | 6 +- .../azure/azure_cloud_provider_test.go | 8 +- .../cloudprovider/azure/azure_manager_test.go | 6 +- .../cloudprovider/azure/azure_scale_set.go | 10 +- .../azure/azure_scale_set_instance_cache.go | 8 +- .../azure/azure_scale_set_test.go | 118 +++++++++--------- .../cloudprovider/azure/azure_template.go | 18 +-- .../azure/azure_template_test.go | 26 ++-- .../cloudprovider/azure/azure_util.go | 4 +- .../cloudprovider/azure/azure_vms_pool.go | 20 +-- .../azure/azure_vms_pool_test.go | 28 ++--- cluster-autoscaler/go.mod | 2 +- 15 files changed, 155 insertions(+), 158 deletions(-) diff --git a/cluster-autoscaler/cloudprovider/azure/azure_agent_pool.go b/cluster-autoscaler/cloudprovider/azure/azure_agent_pool.go index 15655e387009..fc4da2a67c79 100644 --- a/cluster-autoscaler/cloudprovider/azure/azure_agent_pool.go +++ b/cluster-autoscaler/cloudprovider/azure/azure_agent_pool.go @@ -27,7 +27,7 @@ import ( "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2017-05-10/resources" azStorage "github.com/Azure/azure-sdk-for-go/storage" - "github.com/Azure/go-autorest/autorest/to" + "k8s.io/utils/ptr" apiv1 "k8s.io/api/core/v1" utilerrors "k8s.io/apimachinery/pkg/util/errors" @@ -521,7 +521,7 @@ func (as *AgentPool) deleteBlob(accountName, vhdContainer, vhdBlob string) error } keys := *storageKeysResult.Keys - client, err := azStorage.NewBasicClientOnSovereignCloud(accountName, to.String(keys[0].Value), as.manager.env) + client, err := azStorage.NewBasicClientOnSovereignCloud(accountName, ptr.Deref(keys[0].Value, ""), as.manager.env) if err != nil { return err } diff --git a/cluster-autoscaler/cloudprovider/azure/azure_agent_pool_test.go b/cluster-autoscaler/cloudprovider/azure/azure_agent_pool_test.go index 1f3b8872c2c4..9eb1b195defa 100644 --- a/cluster-autoscaler/cloudprovider/azure/azure_agent_pool_test.go +++ b/cluster-autoscaler/cloudprovider/azure/azure_agent_pool_test.go @@ -25,6 +25,7 @@ import ( apiv1 "k8s.io/api/core/v1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/storageaccountclient/mockstorageaccountclient" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmclient/mockvmclient" providerazureconsts "sigs.k8s.io/cloud-provider-azure/pkg/consts" @@ -33,7 +34,6 @@ import ( "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2017-05-10/resources" "github.com/Azure/go-autorest/autorest/date" - "github.com/Azure/go-autorest/autorest/to" "github.com/stretchr/testify/assert" "go.uber.org/mock/gomock" ) @@ -62,14 +62,14 @@ func newTestAgentPool(manager *AzureManager, name string) *AgentPool { func getExpectedVMs() []compute.VirtualMachine { expectedVMs := []compute.VirtualMachine{ { - Name: to.StringPtr("000-0-00000000-0"), - ID: to.StringPtr("/subscriptions/sub/resourceGroups/rg/providers/provider/0"), - Tags: map[string]*string{"poolName": to.StringPtr("as")}, + Name: ptr.To("000-0-00000000-0"), + ID: ptr.To("/subscriptions/sub/resourceGroups/rg/providers/provider/0"), + Tags: map[string]*string{"poolName": ptr.To("as")}, VirtualMachineProperties: &compute.VirtualMachineProperties{ StorageProfile: &compute.StorageProfile{ OsDisk: &compute.OSDisk{ OsType: compute.OperatingSystemTypesLinux, - Vhd: &compute.VirtualHardDisk{URI: to.StringPtr("https://foo.blob/vhds/bar.vhd")}, + Vhd: &compute.VirtualHardDisk{URI: ptr.To("https://foo.blob/vhds/bar.vhd")}, }, }, NetworkProfile: &compute.NetworkProfile{ @@ -80,9 +80,9 @@ func getExpectedVMs() []compute.VirtualMachine { }, }, { - Name: to.StringPtr("00000000001"), - ID: to.StringPtr("/subscriptions/sub/resourceGroups/rg/providers/provider/0"), - Tags: map[string]*string{"poolName": to.StringPtr("as")}, + Name: ptr.To("00000000001"), + ID: ptr.To("/subscriptions/sub/resourceGroups/rg/providers/provider/0"), + Tags: map[string]*string{"poolName": ptr.To("as")}, VirtualMachineProperties: &compute.VirtualMachineProperties{ StorageProfile: &compute.StorageProfile{ OsDisk: &compute.OSDisk{OsType: compute.OperatingSystemTypesWindows}, @@ -115,30 +115,30 @@ func TestDeleteOutdatedDeployments(t *testing.T) { { deployments: map[string]resources.DeploymentExtended{ "non-cluster-autoscaler-0000": { - Name: to.StringPtr("non-cluster-autoscaler-0000"), + Name: ptr.To("non-cluster-autoscaler-0000"), Properties: &resources.DeploymentPropertiesExtended{ - ProvisioningState: to.StringPtr("Succeeded"), + ProvisioningState: ptr.To("Succeeded"), Timestamp: &date.Time{Time: timeBenchMark.Add(2 * time.Minute)}, }, }, "cluster-autoscaler-0000": { - Name: to.StringPtr("cluster-autoscaler-0000"), + Name: ptr.To("cluster-autoscaler-0000"), Properties: &resources.DeploymentPropertiesExtended{ - ProvisioningState: to.StringPtr("Succeeded"), + ProvisioningState: ptr.To("Succeeded"), Timestamp: &date.Time{Time: timeBenchMark}, }, }, "cluster-autoscaler-0001": { - Name: to.StringPtr("cluster-autoscaler-0001"), + Name: ptr.To("cluster-autoscaler-0001"), Properties: &resources.DeploymentPropertiesExtended{ - ProvisioningState: to.StringPtr("Succeeded"), + ProvisioningState: ptr.To("Succeeded"), Timestamp: &date.Time{Time: timeBenchMark.Add(time.Minute)}, }, }, "cluster-autoscaler-0002": { - Name: to.StringPtr("cluster-autoscaler-0002"), + Name: ptr.To("cluster-autoscaler-0002"), Properties: &resources.DeploymentPropertiesExtended{ - ProvisioningState: to.StringPtr("Succeeded"), + ProvisioningState: ptr.To("Succeeded"), Timestamp: &date.Time{Time: timeBenchMark.Add(2 * time.Minute)}, }, }, @@ -177,7 +177,7 @@ func TestAgentPoolGetVMsFromCache(t *testing.T) { testAS := newTestAgentPool(newTestAzureManager(t), "testAS") expectedVMs := []compute.VirtualMachine{ { - Tags: map[string]*string{"poolName": to.StringPtr("testAS")}, + Tags: map[string]*string{"poolName": ptr.To("testAS")}, }, } @@ -213,7 +213,7 @@ func TestGetVMIndexes(t *testing.T) { assert.Equal(t, 2, len(sortedIndexes)) assert.Equal(t, 2, len(indexToVM)) - expectedVMs[0].ID = to.StringPtr("foo") + expectedVMs[0].ID = ptr.To("foo") mockVMClient.EXPECT().List(gomock.Any(), as.manager.config.ResourceGroup).Return(expectedVMs, nil) err = as.manager.forceRefresh() assert.NoError(t, err) @@ -223,7 +223,7 @@ func TestGetVMIndexes(t *testing.T) { assert.Nil(t, sortedIndexes) assert.Nil(t, indexToVM) - expectedVMs[0].Name = to.StringPtr("foo") + expectedVMs[0].Name = ptr.To("foo") mockVMClient.EXPECT().List(gomock.Any(), as.manager.config.ResourceGroup).Return(expectedVMs, nil) err = as.manager.forceRefresh() sortedIndexes, indexToVM, err = as.GetVMIndexes() @@ -501,11 +501,11 @@ func TestAgentPoolNodes(t *testing.T) { as := newTestAgentPool(newTestAzureManager(t), "as") expectedVMs := []compute.VirtualMachine{ { - Tags: map[string]*string{"poolName": to.StringPtr("as")}, - ID: to.StringPtr(""), + Tags: map[string]*string{"poolName": ptr.To("as")}, + ID: ptr.To(""), }, { - Tags: map[string]*string{"poolName": to.StringPtr("as")}, + Tags: map[string]*string{"poolName": ptr.To("as")}, ID: &testValidProviderID0, }, } @@ -524,8 +524,8 @@ func TestAgentPoolNodes(t *testing.T) { expectedVMs = []compute.VirtualMachine{ { - Tags: map[string]*string{"poolName": to.StringPtr("as")}, - ID: to.StringPtr("foo"), + Tags: map[string]*string{"poolName": ptr.To("as")}, + ID: ptr.To("foo"), }, } mockVMClient.EXPECT().List(gomock.Any(), as.manager.config.ResourceGroup).Return(expectedVMs, nil) diff --git a/cluster-autoscaler/cloudprovider/azure/azure_cache.go b/cluster-autoscaler/cloudprovider/azure/azure_cache.go index 08c7cfea28ed..29d2d63eb752 100644 --- a/cluster-autoscaler/cloudprovider/azure/azure_cache.go +++ b/cluster-autoscaler/cloudprovider/azure/azure_cache.go @@ -27,7 +27,6 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v5" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/go-autorest/autorest/to" "github.com/Azure/skewer" "k8s.io/autoscaler/cluster-autoscaler/cloudprovider" providerazureconsts "sigs.k8s.io/cloud-provider-azure/pkg/consts" @@ -295,11 +294,9 @@ func (m *azureCache) fetchVirtualMachines() (map[string][]compute.VirtualMachine if vmPoolName == nil { vmPoolName = tags[legacyAgentpoolNameTag] } - if vmPoolName == nil { - continue + if vmPoolName != nil { + instances[*vmPoolName] = append(instances[*vmPoolName], instance) } - - instances[to.String(vmPoolName)] = append(instances[to.String(vmPoolName)], instance) } return instances, nil } diff --git a/cluster-autoscaler/cloudprovider/azure/azure_cache_test.go b/cluster-autoscaler/cloudprovider/azure/azure_cache_test.go index 843b54e1cf28..aff2d26d17ff 100644 --- a/cluster-autoscaler/cloudprovider/azure/azure_cache_test.go +++ b/cluster-autoscaler/cloudprovider/azure/azure_cache_test.go @@ -23,9 +23,9 @@ import ( providerazureconsts "sigs.k8s.io/cloud-provider-azure/pkg/consts" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v5" - "github.com/Azure/go-autorest/autorest/to" "github.com/stretchr/testify/assert" "go.uber.org/mock/gomock" + "k8s.io/utils/ptr" ) func TestFetchVMsPools(t *testing.T) { @@ -40,7 +40,7 @@ func TestFetchVMsPools(t *testing.T) { vmsPool := getTestVMsAgentPool(false) vmssPoolType := armcontainerservice.AgentPoolTypeVirtualMachineScaleSets vmssPool := armcontainerservice.AgentPool{ - Name: to.StringPtr("vmsspool1"), + Name: ptr.To("vmsspool1"), Properties: &armcontainerservice.ManagedClusterAgentPoolProfileProperties{ Type: &vmssPoolType, }, @@ -54,7 +54,7 @@ func TestFetchVMsPools(t *testing.T) { assert.NoError(t, err) assert.Equal(t, 1, len(vmsPoolMap)) - _, ok := vmsPoolMap[to.String(vmsPool.Name)] + _, ok := vmsPoolMap[ptr.Deref(vmsPool.Name, "")] assert.True(t, ok) } diff --git a/cluster-autoscaler/cloudprovider/azure/azure_cloud_provider_test.go b/cluster-autoscaler/cloudprovider/azure/azure_cloud_provider_test.go index 342f4988e8cf..d15e7984ae40 100644 --- a/cluster-autoscaler/cloudprovider/azure/azure_cloud_provider_test.go +++ b/cluster-autoscaler/cloudprovider/azure/azure_cloud_provider_test.go @@ -23,10 +23,10 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v5" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2017-05-10/resources" - "github.com/Azure/go-autorest/autorest/to" apiv1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/utils/ptr" "k8s.io/autoscaler/cluster-autoscaler/cloudprovider" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmclient/mockvmclient" @@ -74,7 +74,7 @@ func newTestAzureManager(t *testing.T) *AzureManager { deploymentClient: &DeploymentClientMock{ FakeStore: map[string]resources.DeploymentExtended{ "deployment": { - Name: to.StringPtr("deployment"), + Name: ptr.To("deployment"), Properties: &resources.DeploymentPropertiesExtended{Template: map[string]interface{}{ resourcesFieldName: []interface{}{ map[string]interface{}{ @@ -166,7 +166,7 @@ func TestHasInstance(t *testing.T) { mockVMSSVMClient.EXPECT().List(gomock.Any(), provider.azureManager.config.ResourceGroup, "test-asg", gomock.Any()).Return(expectedVMSSVMs, nil).AnyTimes() vmssType := armcontainerservice.AgentPoolTypeVirtualMachineScaleSets vmssPool := armcontainerservice.AgentPool{ - Name: to.StringPtr("test-asg"), + Name: ptr.To("test-asg"), Properties: &armcontainerservice.ManagedClusterAgentPoolProfileProperties{ Type: &vmssType, }, @@ -303,7 +303,7 @@ func TestMixedNodeGroups(t *testing.T) { vmssType := armcontainerservice.AgentPoolTypeVirtualMachineScaleSets vmssPool := armcontainerservice.AgentPool{ - Name: to.StringPtr("test-asg"), + Name: ptr.To("test-asg"), Properties: &armcontainerservice.ManagedClusterAgentPoolProfileProperties{ Type: &vmssType, }, diff --git a/cluster-autoscaler/cloudprovider/azure/azure_manager_test.go b/cluster-autoscaler/cloudprovider/azure/azure_manager_test.go index 6efd60756a4c..4fe5273f0cda 100644 --- a/cluster-autoscaler/cloudprovider/azure/azure_manager_test.go +++ b/cluster-autoscaler/cloudprovider/azure/azure_manager_test.go @@ -30,11 +30,11 @@ import ( "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2017-05-10/resources" "github.com/Azure/go-autorest/autorest/date" - "github.com/Azure/go-autorest/autorest/to" "github.com/stretchr/testify/assert" "go.uber.org/mock/gomock" "k8s.io/autoscaler/cluster-autoscaler/cloudprovider" "k8s.io/autoscaler/cluster-autoscaler/config" + "k8s.io/utils/ptr" azclient "sigs.k8s.io/cloud-provider-azure/pkg/azclient" azclients "sigs.k8s.io/cloud-provider-azure/pkg/azureclients" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssclient/mockvmssclient" @@ -1069,9 +1069,9 @@ func TestFetchExplicitNodeGroups(t *testing.T) { testAS.manager.azClient.deploymentClient = &DeploymentClientMock{ FakeStore: map[string]resources.DeploymentExtended{ "cluster-autoscaler-0001": { - Name: to.StringPtr("cluster-autoscaler-0001"), + Name: ptr.To("cluster-autoscaler-0001"), Properties: &resources.DeploymentPropertiesExtended{ - ProvisioningState: to.StringPtr("Succeeded"), + ProvisioningState: ptr.To("Succeeded"), Timestamp: &date.Time{Time: timeBenchMark.Add(2 * time.Minute)}, }, }, diff --git a/cluster-autoscaler/cloudprovider/azure/azure_scale_set.go b/cluster-autoscaler/cloudprovider/azure/azure_scale_set.go index c6fecb67b005..9faaf5818873 100644 --- a/cluster-autoscaler/cloudprovider/azure/azure_scale_set.go +++ b/cluster-autoscaler/cloudprovider/azure/azure_scale_set.go @@ -29,11 +29,11 @@ import ( "k8s.io/autoscaler/cluster-autoscaler/config/dynamic" klog "k8s.io/klog/v2" schedulerframework "k8s.io/kubernetes/pkg/scheduler/framework" + "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/retry" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/to" ) var ( @@ -209,7 +209,7 @@ func (scaleSet *ScaleSet) getCurSize() (int64, *GetVMSSFailedError) { // // If VMSS state is updating, return the currentSize which would've been proactively incremented or decremented by CA // // unless it's -1. In that case, its better to initialize it. // if scaleSet.curSize != -1 && set.VirtualMachineScaleSetProperties != nil && - // strings.EqualFold(to.String(set.VirtualMachineScaleSetProperties.ProvisioningState), string(compute.GalleryProvisioningStateUpdating)) { + // strings.EqualFold(ptr.Deref(set.VirtualMachineScaleSetProperties.ProvisioningState, ""), string(compute.GalleryProvisioningStateUpdating)) { // klog.V(3).Infof("VMSS %q is in updating state, returning cached size: %d", scaleSet.Name, scaleSet.curSize) // return scaleSet.curSize, nil // } @@ -870,10 +870,10 @@ func (scaleSet *ScaleSet) cseErrors(extensions *[]compute.VirtualMachineExtensio failed := false if extensions != nil { for _, extension := range *extensions { - if strings.EqualFold(to.String(extension.Name), vmssCSEExtensionName) && extension.Statuses != nil { + if strings.EqualFold(ptr.Deref(extension.Name, ""), vmssCSEExtensionName) && extension.Statuses != nil { for _, status := range *extension.Statuses { if status.Level == "Error" { - errs = append(errs, to.String(status.Message)) + errs = append(errs, ptr.Deref(status.Message, "")) failed = true } } @@ -889,7 +889,7 @@ func (scaleSet *ScaleSet) getSKU() string { klog.Errorf("Failed to get information for VMSS (%q): %v", scaleSet.Name, err) return "" } - return to.String(vmssInfo.Sku.Name) + return ptr.Deref(vmssInfo.Sku.Name, "") } func (scaleSet *ScaleSet) verifyNodeGroup(instance *azureRef, commonNgID string) error { diff --git a/cluster-autoscaler/cloudprovider/azure/azure_scale_set_instance_cache.go b/cluster-autoscaler/cloudprovider/azure/azure_scale_set_instance_cache.go index 0c21bdc12e57..5f003905e9e6 100644 --- a/cluster-autoscaler/cloudprovider/azure/azure_scale_set_instance_cache.go +++ b/cluster-autoscaler/cloudprovider/azure/azure_scale_set_instance_cache.go @@ -23,10 +23,10 @@ import ( "time" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/go-autorest/autorest/to" "k8s.io/autoscaler/cluster-autoscaler/cloudprovider" "k8s.io/klog/v2" + "k8s.io/utils/ptr" ) /* @@ -227,7 +227,7 @@ func (scaleSet *ScaleSet) instanceStatusFromVM(vm *compute.VirtualMachineScaleSe case string(compute.GalleryProvisioningStateFailed): status.State = cloudprovider.InstanceRunning - klog.V(3).Infof("VM %s reports failed provisioning state with power state: %s, eligible for fast delete: %s", to.String(vm.ID), powerState, strconv.FormatBool(scaleSet.enableFastDeleteOnFailedProvisioning)) + klog.V(3).Infof("VM %s reports failed provisioning state with power state: %s, eligible for fast delete: %s", ptr.Deref(vm.ID, ""), powerState, strconv.FormatBool(scaleSet.enableFastDeleteOnFailedProvisioning)) if scaleSet.enableFastDeleteOnFailedProvisioning { // Provisioning can fail both during instance creation or after the instance is running. // Per https://learn.microsoft.com/en-us/azure/virtual-machines/states-billing#provisioning-states, @@ -253,12 +253,12 @@ func (scaleSet *ScaleSet) instanceStatusFromVM(vm *compute.VirtualMachineScaleSe // Add vmssCSE Provisioning Failed Message in error info body for vmssCSE Extensions if enableDetailedCSEMessage is true if scaleSet.enableDetailedCSEMessage && vm.InstanceView != nil { if err, failed := scaleSet.cseErrors(vm.InstanceView.Extensions); failed { - klog.V(3).Infof("VM %s reports CSE failure: %v, with provisioning state %s, power state %s", to.String(vm.ID), err, to.String(vm.ProvisioningState), powerState) + klog.V(3).Infof("VM %s reports CSE failure: %v, with provisioning state %s, power state %s", ptr.Deref(vm.ID, ""), err, ptr.Deref(vm.ProvisioningState, ""), powerState) status.State = cloudprovider.InstanceCreating errorInfo := &cloudprovider.InstanceErrorInfo{ ErrorClass: cloudprovider.OtherErrorClass, ErrorCode: vmssExtensionProvisioningFailed, - ErrorMessage: fmt.Sprintf("%s: %v", to.String(vm.Name), err), + ErrorMessage: fmt.Sprintf("%s: %v", ptr.Deref(vm.Name, ""), err), } status.ErrorInfo = errorInfo } diff --git a/cluster-autoscaler/cloudprovider/azure/azure_scale_set_test.go b/cluster-autoscaler/cloudprovider/azure/azure_scale_set_test.go index 7615b8e7e621..93a9ffc8a510 100644 --- a/cluster-autoscaler/cloudprovider/azure/azure_scale_set_test.go +++ b/cluster-autoscaler/cloudprovider/azure/azure_scale_set_test.go @@ -23,12 +23,12 @@ import ( "time" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/go-autorest/autorest/to" "github.com/stretchr/testify/assert" "go.uber.org/mock/gomock" apiv1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" "k8s.io/autoscaler/cluster-autoscaler/cloudprovider" + "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmclient/mockvmclient" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssclient/mockvmssclient" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssvmclient/mockvmssvmclient" @@ -78,31 +78,31 @@ func newTestScaleSetWithFastDelete(manager *AzureManager, name string) *ScaleSet func newTestVMSSList(cap int64, name, loc string, orchmode compute.OrchestrationMode) []compute.VirtualMachineScaleSet { return []compute.VirtualMachineScaleSet{ { - Name: to.StringPtr(name), + Name: ptr.To(name), Sku: &compute.Sku{ - Capacity: to.Int64Ptr(cap), - Name: to.StringPtr("Standard_D4_v2"), + Capacity: ptr.To(cap), + Name: ptr.To("Standard_D4_v2"), }, VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{ OrchestrationMode: orchmode, }, - Location: to.StringPtr(loc), - ID: to.StringPtr(name), + Location: ptr.To(loc), + ID: ptr.To(name), }, } } func newTestVMSSListForEdgeZones(capacity int64, name string) *compute.VirtualMachineScaleSet { return &compute.VirtualMachineScaleSet{ - Name: to.StringPtr(name), + Name: ptr.To(name), Sku: &compute.Sku{ - Capacity: to.Int64Ptr(capacity), - Name: to.StringPtr("Standard_D4_v2"), + Capacity: ptr.To(capacity), + Name: ptr.To("Standard_D4_v2"), }, VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{}, - Location: to.StringPtr(testLocation), + Location: ptr.To(testLocation), ExtendedLocation: &compute.ExtendedLocation{ - Name: to.StringPtr("losangeles"), + Name: ptr.To("losangeles"), Type: compute.ExtendedLocationTypes("EdgeZone"), }, } @@ -112,10 +112,10 @@ func newTestVMSSVMList(count int) []compute.VirtualMachineScaleSetVM { var vmssVMList []compute.VirtualMachineScaleSetVM for i := 0; i < count; i++ { vmssVM := compute.VirtualMachineScaleSetVM{ - ID: to.StringPtr(fmt.Sprintf(fakeVirtualMachineScaleSetVMID, i)), - InstanceID: to.StringPtr(fmt.Sprintf("%d", i)), + ID: ptr.To(fmt.Sprintf(fakeVirtualMachineScaleSetVMID, i)), + InstanceID: ptr.To(fmt.Sprintf("%d", i)), VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ - VMID: to.StringPtr(fmt.Sprintf("123E4567-E89B-12D3-A456-426655440000-%d", i)), + VMID: ptr.To(fmt.Sprintf("123E4567-E89B-12D3-A456-426655440000-%d", i)), }, } vmssVMList = append(vmssVMList, vmssVM) @@ -127,9 +127,9 @@ func newTestVMList(count int) []compute.VirtualMachine { var vmssVMList []compute.VirtualMachine for i := 0; i < count; i++ { vmssVM := compute.VirtualMachine{ - ID: to.StringPtr(fmt.Sprintf(fakeVirtualMachineVMID, i)), + ID: ptr.To(fmt.Sprintf(fakeVirtualMachineVMID, i)), VirtualMachineProperties: &compute.VirtualMachineProperties{ - VMID: to.StringPtr(fmt.Sprintf("123E4567-E89B-12D3-A456-426655440000-%d", i)), + VMID: ptr.To(fmt.Sprintf("123E4567-E89B-12D3-A456-426655440000-%d", i)), }, } vmssVMList = append(vmssVMList, vmssVM) @@ -201,7 +201,7 @@ func TestScaleSetTargetSize(t *testing.T) { provider.azureManager.azClient.virtualMachinesClient = mockVMClient // return a different capacity from GET API - spotScaleSet.Sku.Capacity = to.Int64Ptr(1) + spotScaleSet.Sku.Capacity = ptr.To[int64](1) mockVMSSClient.EXPECT().Get(gomock.Any(), provider.azureManager.config.ResourceGroup, "spot-vmss").Return(spotScaleSet, nil).Times(1) provider.azureManager.azClient.virtualMachineScaleSetsClient = mockVMSSClient mockVMSSVMClient := mockvmssvmclient.NewMockInterface(ctrl) @@ -376,16 +376,16 @@ func TestScaleSetIncreaseSizeOnVMProvisioningFailed(t *testing.T) { expectErrorInfoPopulated: false, }, "out of resources when VM is stopped": { - statuses: []compute.InstanceViewStatus{{Code: to.StringPtr(vmPowerStateStopped)}}, + statuses: []compute.InstanceViewStatus{{Code: ptr.To(vmPowerStateStopped)}}, expectErrorInfoPopulated: false, }, "out of resources when VM reports invalid power state": { - statuses: []compute.InstanceViewStatus{{Code: to.StringPtr("PowerState/invalid")}}, + statuses: []compute.InstanceViewStatus{{Code: ptr.To("PowerState/invalid")}}, expectErrorInfoPopulated: false, }, "instance running when power state is running": { expectInstanceRunning: true, - statuses: []compute.InstanceViewStatus{{Code: to.StringPtr(vmPowerStateRunning)}}, + statuses: []compute.InstanceViewStatus{{Code: ptr.To(vmPowerStateRunning)}}, expectErrorInfoPopulated: false, }, "instance running if instance view cannot be retrieved": { @@ -406,7 +406,7 @@ func TestScaleSetIncreaseSizeOnVMProvisioningFailed(t *testing.T) { expectedVMSSVMs := newTestVMSSVMList(3) // The failed state is important line of code here expectedVMs := newTestVMList(3) - expectedVMSSVMs[2].ProvisioningState = to.StringPtr(provisioningStateFailed) + expectedVMSSVMs[2].ProvisioningState = ptr.To(provisioningStateFailed) if !testCase.isMissingInstanceView { expectedVMSSVMs[2].InstanceView = &compute.VirtualMachineScaleSetVMInstanceView{Statuses: &testCase.statuses} } @@ -465,16 +465,16 @@ func TestIncreaseSizeOnVMProvisioningFailedWithFastDelete(t *testing.T) { expectErrorInfoPopulated: true, }, "out of resources when VM is stopped": { - statuses: []compute.InstanceViewStatus{{Code: to.StringPtr(vmPowerStateStopped)}}, + statuses: []compute.InstanceViewStatus{{Code: ptr.To(vmPowerStateStopped)}}, expectErrorInfoPopulated: true, }, "out of resources when VM reports invalid power state": { - statuses: []compute.InstanceViewStatus{{Code: to.StringPtr("PowerState/invalid")}}, + statuses: []compute.InstanceViewStatus{{Code: ptr.To("PowerState/invalid")}}, expectErrorInfoPopulated: true, }, "instance running when power state is running": { expectInstanceRunning: true, - statuses: []compute.InstanceViewStatus{{Code: to.StringPtr(vmPowerStateRunning)}}, + statuses: []compute.InstanceViewStatus{{Code: ptr.To(vmPowerStateRunning)}}, expectErrorInfoPopulated: false, }, "instance running if instance view cannot be retrieved": { @@ -495,7 +495,7 @@ func TestIncreaseSizeOnVMProvisioningFailedWithFastDelete(t *testing.T) { expectedVMSSVMs := newTestVMSSVMList(3) // The failed state is important line of code here expectedVMs := newTestVMList(3) - expectedVMSSVMs[2].ProvisioningState = to.StringPtr(provisioningStateFailed) + expectedVMSSVMs[2].ProvisioningState = ptr.To(provisioningStateFailed) if !testCase.isMissingInstanceView { expectedVMSSVMs[2].InstanceView = &compute.VirtualMachineScaleSetVMInstanceView{Statuses: &testCase.statuses} } @@ -558,7 +558,7 @@ func TestScaleSetIncreaseSizeOnVMSSUpdating(t *testing.T) { Capacity: &vmssCapacity, }, VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{ - ProvisioningState: to.StringPtr(string(compute.GalleryProvisioningStateUpdating)), + ProvisioningState: ptr.To(string(compute.GalleryProvisioningStateUpdating)), OrchestrationMode: compute.Uniform, }, }, @@ -749,12 +749,12 @@ func TestScaleSetDeleteNodes(t *testing.T) { mockVMSSClient.EXPECT().List(gomock.Any(), manager.config.ResourceGroup).Return(expectedScaleSets, nil).AnyTimes() if orchMode == compute.Uniform { - expectedVMSSVMs[0].ProvisioningState = to.StringPtr(provisioningStateDeleting) - expectedVMSSVMs[2].ProvisioningState = to.StringPtr(provisioningStateDeleting) + expectedVMSSVMs[0].ProvisioningState = ptr.To(provisioningStateDeleting) + expectedVMSSVMs[2].ProvisioningState = ptr.To(provisioningStateDeleting) mockVMSSVMClient.EXPECT().List(gomock.Any(), manager.config.ResourceGroup, "test-asg", gomock.Any()).Return(expectedVMSSVMs, nil).AnyTimes() } else { - expectedVMs[0].ProvisioningState = to.StringPtr(provisioningStateDeleting) - expectedVMs[2].ProvisioningState = to.StringPtr(provisioningStateDeleting) + expectedVMs[0].ProvisioningState = ptr.To(provisioningStateDeleting) + expectedVMs[2].ProvisioningState = ptr.To(provisioningStateDeleting) mockVMClient.EXPECT().ListVmssFlexVMsWithoutInstanceView(gomock.Any(), "test-asg").Return(expectedVMs, nil).AnyTimes() } @@ -982,8 +982,8 @@ func TestScaleSetDeleteInstancesWithForceDeleteEnabled(t *testing.T) { }, } mockVMSSClient.EXPECT().List(gomock.Any(), manager.config.ResourceGroup).Return(expectedScaleSets, nil).AnyTimes() - expectedVMSSVMs[0].ProvisioningState = to.StringPtr(string(compute.GalleryProvisioningStateDeleting)) - expectedVMSSVMs[2].ProvisioningState = to.StringPtr(string(compute.GalleryProvisioningStateDeleting)) + expectedVMSSVMs[0].ProvisioningState = ptr.To(string(compute.GalleryProvisioningStateDeleting)) + expectedVMSSVMs[2].ProvisioningState = ptr.To(string(compute.GalleryProvisioningStateDeleting)) mockVMSSVMClient.EXPECT().List(gomock.Any(), manager.config.ResourceGroup, "test-asg", gomock.Any()).Return(expectedVMSSVMs, nil).AnyTimes() err = manager.forceRefresh() assert.NoError(t, err) @@ -1021,11 +1021,11 @@ func TestScaleSetDeleteNoConflictRequest(t *testing.T) { expectedVMSSVMs := []compute.VirtualMachineScaleSetVM{ { - ID: to.StringPtr(fakeVirtualMachineScaleSetVMID), - InstanceID: to.StringPtr("0"), + ID: ptr.To(fakeVirtualMachineScaleSetVMID), + InstanceID: ptr.To("0"), VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ - VMID: to.StringPtr("123E4567-E89B-12D3-A456-426655440000"), - ProvisioningState: to.StringPtr("Deleting"), + VMID: ptr.To("123E4567-E89B-12D3-A456-426655440000"), + ProvisioningState: ptr.To("Deleting"), }, }, } @@ -1318,14 +1318,14 @@ func TestScaleSetTemplateNodeInfo(t *testing.T) { } func TestScaleSetCseErrors(t *testing.T) { - errorMessage := to.StringPtr("Error Message Test") + errorMessage := ptr.To("Error Message Test") vmssVMs := compute.VirtualMachineScaleSetVM{ - Name: to.StringPtr("vmTest"), - ID: to.StringPtr(fakeVirtualMachineScaleSetVMID), - InstanceID: to.StringPtr("0"), + Name: ptr.To("vmTest"), + ID: ptr.To(fakeVirtualMachineScaleSetVMID), + InstanceID: ptr.To("0"), VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ - VMID: to.StringPtr("123E4567-E89B-12D3-A456-426655440000"), - ProvisioningState: to.StringPtr("Succeeded"), + VMID: ptr.To("123E4567-E89B-12D3-A456-426655440000"), + ProvisioningState: ptr.To("Succeeded"), InstanceView: &compute.VirtualMachineScaleSetVMInstanceView{ Extensions: &[]compute.VirtualMachineExtensionInstanceView{ { @@ -1353,13 +1353,13 @@ func TestScaleSetCseErrors(t *testing.T) { t.Run("getCSEErrorMessages test with CSE error in VM extensions", func(t *testing.T) { expectedCSEWErrorMessage := "Error Message Test" - (*vmssVMs.InstanceView.Extensions)[0].Name = to.StringPtr(vmssCSEExtensionName) + (*vmssVMs.InstanceView.Extensions)[0].Name = ptr.To(vmssCSEExtensionName) actualCSEErrorMessage, actualCSEFailureBool := scaleSet.cseErrors(vmssVMs.InstanceView.Extensions) assert.True(t, actualCSEFailureBool) assert.Equal(t, []string{expectedCSEWErrorMessage}, actualCSEErrorMessage) }) t.Run("getCSEErrorMessages test with no CSE error in VM extensions", func(t *testing.T) { - (*vmssVMs.InstanceView.Extensions)[0].Name = to.StringPtr("notCSEExtension") + (*vmssVMs.InstanceView.Extensions)[0].Name = ptr.To("notCSEExtension") actualCSEErrorMessage, actualCSEFailureBool := scaleSet.cseErrors(vmssVMs.InstanceView.Extensions) assert.False(t, actualCSEFailureBool) assert.Equal(t, []string(nil), actualCSEErrorMessage) @@ -1368,12 +1368,12 @@ func TestScaleSetCseErrors(t *testing.T) { func newVMObjectWithState(provisioningState string, powerState string) *compute.VirtualMachineScaleSetVM { return &compute.VirtualMachineScaleSetVM{ - ID: to.StringPtr("1"), // Beware; refactor if needed + ID: ptr.To("1"), // Beware; refactor if needed VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ - ProvisioningState: to.StringPtr(provisioningState), + ProvisioningState: ptr.To(provisioningState), InstanceView: &compute.VirtualMachineScaleSetVMInstanceView{ Statuses: &[]compute.InstanceViewStatus{ - {Code: to.StringPtr(powerState)}, + {Code: ptr.To(powerState)}, }, }, }, @@ -1384,21 +1384,21 @@ func newVMObjectWithState(provisioningState string, powerState string) *compute. func TestInstanceStatusFromProvisioningStateAndPowerState(t *testing.T) { t.Run("fast delete enablement = false", func(t *testing.T) { t.Run("provisioning state = failed, power state = starting", func(t *testing.T) { - status := instanceStatusFromProvisioningStateAndPowerState("1", to.StringPtr(string(compute.GalleryProvisioningStateFailed)), vmPowerStateStarting, false) + status := instanceStatusFromProvisioningStateAndPowerState("1", ptr.To(string(compute.GalleryProvisioningStateFailed)), vmPowerStateStarting, false) assert.NotNil(t, status) assert.Equal(t, cloudprovider.InstanceRunning, status.State) }) t.Run("provisioning state = failed, power state = running", func(t *testing.T) { - status := instanceStatusFromProvisioningStateAndPowerState("1", to.StringPtr(string(compute.GalleryProvisioningStateFailed)), vmPowerStateRunning, false) + status := instanceStatusFromProvisioningStateAndPowerState("1", ptr.To(string(compute.GalleryProvisioningStateFailed)), vmPowerStateRunning, false) assert.NotNil(t, status) assert.Equal(t, cloudprovider.InstanceRunning, status.State) }) t.Run("provisioning state = failed, power state = stopping", func(t *testing.T) { - status := instanceStatusFromProvisioningStateAndPowerState("1", to.StringPtr(string(compute.GalleryProvisioningStateFailed)), vmPowerStateStopping, false) + status := instanceStatusFromProvisioningStateAndPowerState("1", ptr.To(string(compute.GalleryProvisioningStateFailed)), vmPowerStateStopping, false) assert.NotNil(t, status) assert.Equal(t, cloudprovider.InstanceRunning, status.State) @@ -1406,21 +1406,21 @@ func TestInstanceStatusFromProvisioningStateAndPowerState(t *testing.T) { t.Run("provisioning state = failed, power state = stopped", func(t *testing.T) { - status := instanceStatusFromProvisioningStateAndPowerState("1", to.StringPtr(string(compute.GalleryProvisioningStateFailed)), vmPowerStateStopped, false) + status := instanceStatusFromProvisioningStateAndPowerState("1", ptr.To(string(compute.GalleryProvisioningStateFailed)), vmPowerStateStopped, false) assert.NotNil(t, status) assert.Equal(t, cloudprovider.InstanceRunning, status.State) }) t.Run("provisioning state = failed, power state = deallocated", func(t *testing.T) { - status := instanceStatusFromProvisioningStateAndPowerState("1", to.StringPtr(string(compute.GalleryProvisioningStateFailed)), vmPowerStateDeallocated, false) + status := instanceStatusFromProvisioningStateAndPowerState("1", ptr.To(string(compute.GalleryProvisioningStateFailed)), vmPowerStateDeallocated, false) assert.NotNil(t, status) assert.Equal(t, cloudprovider.InstanceRunning, status.State) }) t.Run("provisioning state = failed, power state = unknown", func(t *testing.T) { - status := instanceStatusFromProvisioningStateAndPowerState("1", to.StringPtr(string(compute.GalleryProvisioningStateFailed)), vmPowerStateUnknown, false) + status := instanceStatusFromProvisioningStateAndPowerState("1", ptr.To(string(compute.GalleryProvisioningStateFailed)), vmPowerStateUnknown, false) assert.NotNil(t, status) assert.Equal(t, cloudprovider.InstanceRunning, status.State) @@ -1429,21 +1429,21 @@ func TestInstanceStatusFromProvisioningStateAndPowerState(t *testing.T) { t.Run("fast delete enablement = true", func(t *testing.T) { t.Run("provisioning state = failed, power state = starting", func(t *testing.T) { - status := instanceStatusFromProvisioningStateAndPowerState("1", to.StringPtr(string(compute.GalleryProvisioningStateFailed)), vmPowerStateStarting, true) + status := instanceStatusFromProvisioningStateAndPowerState("1", ptr.To(string(compute.GalleryProvisioningStateFailed)), vmPowerStateStarting, true) assert.NotNil(t, status) assert.Equal(t, cloudprovider.InstanceRunning, status.State) }) t.Run("provisioning state = failed, power state = running", func(t *testing.T) { - status := instanceStatusFromProvisioningStateAndPowerState("1", to.StringPtr(string(compute.GalleryProvisioningStateFailed)), vmPowerStateRunning, true) + status := instanceStatusFromProvisioningStateAndPowerState("1", ptr.To(string(compute.GalleryProvisioningStateFailed)), vmPowerStateRunning, true) assert.NotNil(t, status) assert.Equal(t, cloudprovider.InstanceRunning, status.State) }) t.Run("provisioning state = failed, power state = stopping", func(t *testing.T) { - status := instanceStatusFromProvisioningStateAndPowerState("1", to.StringPtr(string(compute.GalleryProvisioningStateFailed)), vmPowerStateStopping, true) + status := instanceStatusFromProvisioningStateAndPowerState("1", ptr.To(string(compute.GalleryProvisioningStateFailed)), vmPowerStateStopping, true) assert.NotNil(t, status) assert.Equal(t, cloudprovider.InstanceCreating, status.State) @@ -1451,7 +1451,7 @@ func TestInstanceStatusFromProvisioningStateAndPowerState(t *testing.T) { }) t.Run("provisioning state = failed, power state = stopped", func(t *testing.T) { - status := instanceStatusFromProvisioningStateAndPowerState("1", to.StringPtr(string(compute.GalleryProvisioningStateFailed)), vmPowerStateStopped, true) + status := instanceStatusFromProvisioningStateAndPowerState("1", ptr.To(string(compute.GalleryProvisioningStateFailed)), vmPowerStateStopped, true) assert.NotNil(t, status) assert.Equal(t, cloudprovider.InstanceCreating, status.State) @@ -1459,7 +1459,7 @@ func TestInstanceStatusFromProvisioningStateAndPowerState(t *testing.T) { }) t.Run("provisioning state = failed, power state = deallocated", func(t *testing.T) { - status := instanceStatusFromProvisioningStateAndPowerState("1", to.StringPtr(string(compute.GalleryProvisioningStateFailed)), vmPowerStateDeallocated, true) + status := instanceStatusFromProvisioningStateAndPowerState("1", ptr.To(string(compute.GalleryProvisioningStateFailed)), vmPowerStateDeallocated, true) assert.NotNil(t, status) assert.Equal(t, cloudprovider.InstanceCreating, status.State) @@ -1467,7 +1467,7 @@ func TestInstanceStatusFromProvisioningStateAndPowerState(t *testing.T) { }) t.Run("provisioning state = failed, power state = unknown", func(t *testing.T) { - status := instanceStatusFromProvisioningStateAndPowerState("1", to.StringPtr(string(compute.GalleryProvisioningStateFailed)), vmPowerStateUnknown, true) + status := instanceStatusFromProvisioningStateAndPowerState("1", ptr.To(string(compute.GalleryProvisioningStateFailed)), vmPowerStateUnknown, true) assert.NotNil(t, status) assert.Equal(t, cloudprovider.InstanceCreating, status.State) diff --git a/cluster-autoscaler/cloudprovider/azure/azure_template.go b/cluster-autoscaler/cloudprovider/azure/azure_template.go index 86c8370efe67..bba2641a60cb 100644 --- a/cluster-autoscaler/cloudprovider/azure/azure_template.go +++ b/cluster-autoscaler/cloudprovider/azure/azure_template.go @@ -26,7 +26,6 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v5" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/go-autorest/autorest/to" apiv1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -34,6 +33,7 @@ import ( "k8s.io/autoscaler/cluster-autoscaler/utils/gpu" "k8s.io/klog/v2" kubeletapis "k8s.io/kubelet/pkg/apis" + "k8s.io/utils/ptr" ) const ( @@ -128,11 +128,11 @@ func buildNodeTemplateFromVMSS(vmss compute.VirtualMachineScaleSet, inputLabels } if vmss.Sku == nil || vmss.Sku.Name == nil { - return NodeTemplate{}, fmt.Errorf("VMSS %s has no SKU", to.String(vmss.Name)) + return NodeTemplate{}, fmt.Errorf("VMSS %s has no SKU", ptr.Deref(vmss.Name, "")) } if vmss.Location == nil { - return NodeTemplate{}, fmt.Errorf("VMSS %s has no location", to.String(vmss.Name)) + return NodeTemplate{}, fmt.Errorf("VMSS %s has no location", ptr.Deref(vmss.Name, "")) } zones := []string{} @@ -157,7 +157,7 @@ func buildNodeTemplateFromVMSS(vmss compute.VirtualMachineScaleSet, inputLabels func buildNodeTemplateFromVMPool(vmsPool armcontainerservice.AgentPool, location string, skuName string, labelsFromSpec map[string]string, taintsFromSpec string) (NodeTemplate, error) { if vmsPool.Properties == nil { - return NodeTemplate{}, fmt.Errorf("vmsPool %s has nil properties", to.String(vmsPool.Name)) + return NodeTemplate{}, fmt.Errorf("vmsPool %s has nil properties", ptr.Deref(vmsPool.Name, "")) } // labels from the agentpool labels := vmsPool.Properties.NodeLabels @@ -166,14 +166,14 @@ func buildNodeTemplateFromVMPool(vmsPool armcontainerservice.AgentPool, location if labels == nil { labels = make(map[string]*string) } - labels[k] = to.StringPtr(v) + labels[k] = ptr.To(v) } // taints from the agentpool taintsList := []string{} for _, taint := range vmsPool.Properties.NodeTaints { - if to.String(taint) != "" { - taintsList = append(taintsList, to.String(taint)) + if ptr.Deref(taint, "") != "" { + taintsList = append(taintsList, ptr.Deref(taint, "")) } } // taints from spec @@ -203,7 +203,7 @@ func buildNodeTemplateFromVMPool(vmsPool armcontainerservice.AgentPool, location InstanceOS: instanceOS, Location: location, VMPoolNodeTemplate: &VMPoolNodeTemplate{ - AgentPoolName: to.String(vmsPool.Name), + AgentPoolName: ptr.Deref(vmsPool.Name, ""), OSDiskType: vmsPool.Properties.OSDiskType, Taints: taints, Labels: labels, @@ -290,7 +290,7 @@ func processVMPoolTemplate(template NodeTemplate, nodeName string, node apiv1.No labels[agentPoolNodeLabelKey] = template.VMPoolNodeTemplate.AgentPoolName if template.VMPoolNodeTemplate.Labels != nil { for k, v := range template.VMPoolNodeTemplate.Labels { - labels[k] = to.String(v) + labels[k] = ptr.Deref(v, "") } } node.Labels = cloudprovider.JoinStringMaps(node.Labels, labels) diff --git a/cluster-autoscaler/cloudprovider/azure/azure_template_test.go b/cluster-autoscaler/cloudprovider/azure/azure_template_test.go index f6fe6a006819..99fc79e730a1 100644 --- a/cluster-autoscaler/cloudprovider/azure/azure_template_test.go +++ b/cluster-autoscaler/cloudprovider/azure/azure_template_test.go @@ -24,11 +24,11 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v5" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/to" "github.com/stretchr/testify/assert" apiv1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" + "k8s.io/utils/ptr" ) func TestExtractLabelsFromTags(t *testing.T) { @@ -152,10 +152,10 @@ func TestExtractTaintsFromSpecString(t *testing.T) { func TestExtractAllocatableResourcesFromScaleSet(t *testing.T) { tags := map[string]*string{ - fmt.Sprintf("%s%s", nodeResourcesTagName, "cpu"): to.StringPtr("100m"), - fmt.Sprintf("%s%s", nodeResourcesTagName, "memory"): to.StringPtr("100M"), - fmt.Sprintf("%s%s", nodeResourcesTagName, "ephemeral-storage"): to.StringPtr("20G"), - fmt.Sprintf("%s%s", nodeResourcesTagName, "nvidia.com_Tesla-P100-PCIE"): to.StringPtr("4"), + fmt.Sprintf("%s%s", nodeResourcesTagName, "cpu"): ptr.To("100m"), + fmt.Sprintf("%s%s", nodeResourcesTagName, "memory"): ptr.To("100M"), + fmt.Sprintf("%s%s", nodeResourcesTagName, "ephemeral-storage"): ptr.To("20G"), + fmt.Sprintf("%s%s", nodeResourcesTagName, "nvidia.com_Tesla-P100-PCIE"): ptr.To("4"), } labels := extractAllocatableResourcesFromScaleSet(tags) @@ -179,7 +179,7 @@ func TestTopologyFromScaleSet(t *testing.T) { VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{ VirtualMachineProfile: &compute.VirtualMachineScaleSetVMProfile{OsProfile: nil}}, Zones: &[]string{"1", "2", "3"}, - Location: to.StringPtr("westus"), + Location: ptr.To("westus"), } expectedZoneValues := []string{"westus-1", "westus-2", "westus-3"} template, err := buildNodeTemplateFromVMSS(testVmss, map[string]string{}, "") @@ -206,7 +206,7 @@ func TestEmptyTopologyFromScaleSet(t *testing.T) { Plan: nil, VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{ VirtualMachineProfile: &compute.VirtualMachineScaleSetVMProfile{OsProfile: nil}}, - Location: to.StringPtr("westus"), + Location: ptr.To("westus"), } expectedFailureDomain := "0" @@ -242,13 +242,13 @@ func TestBuildNodeTemplateFromVMPool(t *testing.T) { zone2 := "2" vmpool := armcontainerservice.AgentPool{ - Name: to.StringPtr(agentPoolName), + Name: ptr.To(agentPoolName), Properties: &armcontainerservice.ManagedClusterAgentPoolProfileProperties{ NodeLabels: map[string]*string{ - "existing": to.StringPtr("label"), - "department": to.StringPtr("engineering"), + "existing": ptr.To("label"), + "department": ptr.To("engineering"), }, - NodeTaints: []*string{to.StringPtr("group=bar:NoExecute")}, + NodeTaints: []*string{ptr.To("group=bar:NoExecute")}, OSType: &osType, OSDiskType: &osDiskType, AvailabilityZones: []*string{&zone1, &zone2}, @@ -317,7 +317,7 @@ func TestBuildNodeFromTemplateWithLabelPrediction(t *testing.T) { "poolName": &poolName, }, Zones: &[]string{"1", "2"}, - Location: to.StringPtr("westus"), + Location: ptr.To("westus"), } template, err := buildNodeTemplateFromVMSS(vmss, map[string]string{}, "") @@ -362,7 +362,7 @@ func TestBuildNodeFromTemplateWithEphemeralStorage(t *testing.T) { "poolName": &poolName, }, Zones: &[]string{"1", "2"}, - Location: to.StringPtr("westus"), + Location: ptr.To("westus"), } template, err := buildNodeTemplateFromVMSS(vmss, map[string]string{}, "") diff --git a/cluster-autoscaler/cloudprovider/azure/azure_util.go b/cluster-autoscaler/cloudprovider/azure/azure_util.go index 44a87980571c..8e90464de6b0 100644 --- a/cluster-autoscaler/cloudprovider/azure/azure_util.go +++ b/cluster-autoscaler/cloudprovider/azure/azure_util.go @@ -33,11 +33,11 @@ import ( "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" azStorage "github.com/Azure/azure-sdk-for-go/storage" "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/to" "k8s.io/autoscaler/cluster-autoscaler/cloudprovider" "k8s.io/autoscaler/cluster-autoscaler/version" klog "k8s.io/klog/v2" + "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/retry" ) @@ -123,7 +123,7 @@ func (util *AzUtil) DeleteBlob(accountName, vhdContainer, vhdBlob string) error } keys := *storageKeysResult.Keys - client, err := azStorage.NewBasicClientOnSovereignCloud(accountName, to.String(keys[0].Value), util.manager.env) + client, err := azStorage.NewBasicClientOnSovereignCloud(accountName, ptr.Deref(keys[0].Value, ""), util.manager.env) if err != nil { return err } diff --git a/cluster-autoscaler/cloudprovider/azure/azure_vms_pool.go b/cluster-autoscaler/cloudprovider/azure/azure_vms_pool.go index b667c41a7dc0..3edc43bfe5d7 100644 --- a/cluster-autoscaler/cloudprovider/azure/azure_vms_pool.go +++ b/cluster-autoscaler/cloudprovider/azure/azure_vms_pool.go @@ -24,7 +24,6 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v5" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/go-autorest/autorest/to" apiv1 "k8s.io/api/core/v1" "k8s.io/autoscaler/cluster-autoscaler/cloudprovider" @@ -32,6 +31,7 @@ import ( "k8s.io/autoscaler/cluster-autoscaler/config/dynamic" klog "k8s.io/klog/v2" schedulerframework "k8s.io/kubernetes/pkg/scheduler/framework" + "k8s.io/utils/ptr" ) // VMPool represents a group of standalone virtual machines (VMs) with a single SKU. @@ -206,9 +206,9 @@ func buildRequestBodyForScaleUp(agentpool armcontainerservice.AgentPool, count i // set the count of the matching manual scale profile to the new target value for _, manualProfile := range agentpool.Properties.VirtualMachinesProfile.Scale.Manual { if manualProfile != nil && len(manualProfile.Sizes) == 1 && - strings.EqualFold(to.String(manualProfile.Sizes[0]), vmSku) { + strings.EqualFold(ptr.Deref(manualProfile.Sizes[0], ""), vmSku) { klog.V(5).Infof("Found matching manual profile for VM SKU: %s, updating count to: %d", vmSku, count) - manualProfile.Count = to.Int32Ptr(count) + manualProfile.Count = ptr.To(count) requestBody.Properties.VirtualMachinesProfile = agentpool.Properties.VirtualMachinesProfile break } @@ -404,8 +404,8 @@ func (vmPool *VMPool) getSpotPoolSize() (int32, error) { // it only contains VMs in the running state. for _, status := range ap.Properties.VirtualMachineNodesStatus { if status != nil { - if strings.EqualFold(to.String(status.Size), vmPool.sku) { - return to.Int32(status.Count), nil + if strings.EqualFold(ptr.Deref(status.Size, ""), vmPool.sku) { + return ptr.Deref(status.Count, 0), nil } } } @@ -427,13 +427,13 @@ func (vmPool *VMPool) getVMsFromCache(op skipOption) ([]compute.VirtualMachine, continue } - if op.skipDeleting && strings.Contains(to.String(vm.VirtualMachineProperties.ProvisioningState), "Deleting") { - klog.V(4).Infof("Skipping VM %s in deleting state", to.String(vm.ID)) + if op.skipDeleting && strings.Contains(ptr.Deref(vm.VirtualMachineProperties.ProvisioningState, ""), "Deleting") { + klog.V(4).Infof("Skipping VM %s in deleting state", ptr.Deref(vm.ID, "")) continue } - if op.skipFailed && strings.Contains(to.String(vm.VirtualMachineProperties.ProvisioningState), "Failed") { - klog.V(4).Infof("Skipping VM %s in failed state", to.String(vm.ID)) + if op.skipFailed && strings.Contains(ptr.Deref(vm.VirtualMachineProperties.ProvisioningState, ""), "Failed") { + klog.V(4).Infof("Skipping VM %s in failed state", ptr.Deref(vm.ID, "")) continue } @@ -455,7 +455,7 @@ func (vmPool *VMPool) Nodes() ([]cloudprovider.Instance, error) { if vm.ID == nil || len(*vm.ID) == 0 { continue } - resourceID, err := convertResourceGroupNameToLower("azure://" + to.String(vm.ID)) + resourceID, err := convertResourceGroupNameToLower("azure://" + ptr.Deref(vm.ID, "")) if err != nil { return nil, err } diff --git a/cluster-autoscaler/cloudprovider/azure/azure_vms_pool_test.go b/cluster-autoscaler/cloudprovider/azure/azure_vms_pool_test.go index dd04875fce8f..37e99e3b17dc 100644 --- a/cluster-autoscaler/cloudprovider/azure/azure_vms_pool_test.go +++ b/cluster-autoscaler/cloudprovider/azure/azure_vms_pool_test.go @@ -25,7 +25,6 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v5" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - "github.com/Azure/go-autorest/autorest/to" "go.uber.org/mock/gomock" "github.com/stretchr/testify/assert" @@ -33,6 +32,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/autoscaler/cluster-autoscaler/cloudprovider" "k8s.io/autoscaler/cluster-autoscaler/config" + "k8s.io/utils/ptr" "k8s.io/autoscaler/cluster-autoscaler/config/dynamic" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmclient/mockvmclient" @@ -64,17 +64,17 @@ func newTestVMsPoolVMList(count int) []compute.VirtualMachine { for i := 0; i < count; i++ { vm := compute.VirtualMachine{ - ID: to.StringPtr(fmt.Sprintf(fakeVMsPoolVMID, i)), + ID: ptr.To(fmt.Sprintf(fakeVMsPoolVMID, i)), VirtualMachineProperties: &compute.VirtualMachineProperties{ - VMID: to.StringPtr(fmt.Sprintf("123E4567-E89B-12D3-A456-426655440000-%d", i)), + VMID: ptr.To(fmt.Sprintf("123E4567-E89B-12D3-A456-426655440000-%d", i)), HardwareProfile: &compute.HardwareProfile{ VMSize: compute.VirtualMachineSizeTypes(vmSku), }, - ProvisioningState: to.StringPtr("Succeeded"), + ProvisioningState: ptr.To("Succeeded"), }, Tags: map[string]*string{ - agentpoolTypeTag: to.StringPtr("VirtualMachines"), - agentpoolNameTag: to.StringPtr(vmsAgentPoolName), + agentpoolTypeTag: ptr.To("VirtualMachines"), + agentpoolNameTag: ptr.To(vmsAgentPoolName), }, } vmList = append(vmList, vm) @@ -100,7 +100,7 @@ func getTestVMsAgentPool(isSystemPool bool) armcontainerservice.AgentPool { } vmsPoolType := armcontainerservice.AgentPoolTypeVirtualMachines return armcontainerservice.AgentPool{ - Name: to.StringPtr(vmsAgentPoolName), + Name: ptr.To(vmsAgentPoolName), Properties: &armcontainerservice.ManagedClusterAgentPoolProfileProperties{ Type: &vmsPoolType, Mode: &mode, @@ -108,16 +108,16 @@ func getTestVMsAgentPool(isSystemPool bool) armcontainerservice.AgentPool { Scale: &armcontainerservice.ScaleProfile{ Manual: []*armcontainerservice.ManualScaleProfile{ { - Count: to.Int32Ptr(3), - Sizes: []*string{to.StringPtr(vmSku)}, + Count: ptr.To[int32](3), + Sizes: []*string{ptr.To(vmSku)}, }, }, }, }, VirtualMachineNodesStatus: []*armcontainerservice.VirtualMachineNodes{ { - Count: to.Int32Ptr(3), - Size: to.StringPtr(vmSku), + Count: ptr.To[int32](3), + Size: ptr.To(vmSku), }, }, }, @@ -287,7 +287,7 @@ func TestGetVMsFromCache(t *testing.T) { // Test case 4 - should skip failed VMs vmList := newTestVMsPoolVMList(3) - vmList[0].VirtualMachineProperties.ProvisioningState = to.StringPtr("Failed") + vmList[0].VirtualMachineProperties.ProvisioningState = ptr.To("Failed") manager.azureCache.virtualMachines[vmsAgentPoolName] = vmList vms, err = agentPool.getVMsFromCache(skipOption{skipFailed: true}) assert.NoError(t, err) @@ -295,7 +295,7 @@ func TestGetVMsFromCache(t *testing.T) { // Test case 5 - should skip deleting VMs vmList = newTestVMsPoolVMList(3) - vmList[0].VirtualMachineProperties.ProvisioningState = to.StringPtr("Deleting") + vmList[0].VirtualMachineProperties.ProvisioningState = ptr.To("Deleting") manager.azureCache.virtualMachines[vmsAgentPoolName] = vmList vms, err = agentPool.getVMsFromCache(skipOption{skipDeleting: true}) assert.NoError(t, err) @@ -303,7 +303,7 @@ func TestGetVMsFromCache(t *testing.T) { // Test case 6 - should not skip deleting VMs vmList = newTestVMsPoolVMList(3) - vmList[0].VirtualMachineProperties.ProvisioningState = to.StringPtr("Deleting") + vmList[0].VirtualMachineProperties.ProvisioningState = ptr.To("Deleting") manager.azureCache.virtualMachines[vmsAgentPoolName] = vmList vms, err = agentPool.getVMsFromCache(skipOption{skipFailed: true}) assert.NoError(t, err) diff --git a/cluster-autoscaler/go.mod b/cluster-autoscaler/go.mod index 541dae796a20..b0a3fbf74cc0 100644 --- a/cluster-autoscaler/go.mod +++ b/cluster-autoscaler/go.mod @@ -13,7 +13,6 @@ require ( github.com/Azure/go-autorest/autorest/adal v0.9.24 github.com/Azure/go-autorest/autorest/azure/auth v0.5.13 github.com/Azure/go-autorest/autorest/date v0.3.0 - github.com/Azure/go-autorest/autorest/to v0.4.0 github.com/Azure/skewer v0.0.19 github.com/aws/aws-sdk-go v1.44.241 github.com/cenkalti/backoff/v4 v4.3.0 @@ -74,6 +73,7 @@ require ( github.com/Azure/go-autorest v14.2.0+incompatible // indirect github.com/Azure/go-autorest/autorest/azure/cli v0.4.6 // indirect github.com/Azure/go-autorest/autorest/mocks v0.4.2 // indirect + github.com/Azure/go-autorest/autorest/to v0.4.0 // indirect github.com/Azure/go-autorest/autorest/validation v0.3.1 // indirect github.com/Azure/go-autorest/logger v0.2.1 // indirect github.com/Azure/go-autorest/tracing v0.6.0 // indirect