Use k8s utils pointer instead of Azure autorest/to

Since k/u includes pointer functions which are equivalent to the
autorest/to pointer functions, and the latter are deprecated, it seems
useful to switch to the former:
* to.FooPtr becomes pointer.Foo
* to.Foo becomes pointer.FooDeref with an appropriate default
* to.StringSlicePtr becomes &

This doesn't remove anything from vendor, but it does turn the
dependency into an indirect one, ready to be removed when the rest of
the Azure migration happens.

Signed-off-by: Stephen Kitt <skitt@redhat.com>
This commit is contained in:
Stephen Kitt 2022-12-07 18:16:16 +01:00
parent 09d7286eb5
commit 56d8302bc8
No known key found for this signature in database
GPG Key ID: 1CC5FA453662A71D
61 changed files with 1476 additions and 1478 deletions

2
go.mod
View File

@ -13,7 +13,6 @@ require (
github.com/Azure/azure-sdk-for-go v55.0.0+incompatible github.com/Azure/azure-sdk-for-go v55.0.0+incompatible
github.com/Azure/go-autorest/autorest v0.11.27 github.com/Azure/go-autorest/autorest v0.11.27
github.com/Azure/go-autorest/autorest/adal v0.9.20 github.com/Azure/go-autorest/autorest/adal v0.9.20
github.com/Azure/go-autorest/autorest/to v0.4.0
github.com/GoogleCloudPlatform/k8s-cloud-provider v1.18.1-0.20220218231025-f11817397a1b github.com/GoogleCloudPlatform/k8s-cloud-provider v1.18.1-0.20220218231025-f11817397a1b
github.com/JeffAshton/win_pdh v0.0.0-20161109143554-76bb4ee9f0ab github.com/JeffAshton/win_pdh v0.0.0-20161109143554-76bb4ee9f0ab
github.com/Microsoft/go-winio v0.4.17 github.com/Microsoft/go-winio v0.4.17
@ -135,6 +134,7 @@ require (
github.com/Azure/go-autorest v14.2.0+incompatible // indirect github.com/Azure/go-autorest v14.2.0+incompatible // indirect
github.com/Azure/go-autorest/autorest/date v0.3.0 // indirect github.com/Azure/go-autorest/autorest/date v0.3.0 // indirect
github.com/Azure/go-autorest/autorest/mocks v0.4.2 // 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.1.0 // indirect github.com/Azure/go-autorest/autorest/validation v0.1.0 // indirect
github.com/Azure/go-autorest/logger v0.2.1 // indirect github.com/Azure/go-autorest/logger v0.2.1 // indirect
github.com/Azure/go-autorest/tracing v0.6.0 // indirect github.com/Azure/go-autorest/tracing v0.6.0 // indirect

View File

@ -25,8 +25,8 @@ import (
"github.com/Azure/azure-sdk-for-go/services/containerregistry/mgmt/2019-05-01/containerregistry" "github.com/Azure/azure-sdk-for-go/services/containerregistry/mgmt/2019-05-01/containerregistry"
"github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/to"
"k8s.io/client-go/tools/cache" "k8s.io/client-go/tools/cache"
"k8s.io/utils/pointer"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -39,27 +39,27 @@ func Test(t *testing.T) {
}` }`
result := []containerregistry.Registry{ result := []containerregistry.Registry{
{ {
Name: to.StringPtr("foo"), Name: pointer.String("foo"),
RegistryProperties: &containerregistry.RegistryProperties{ RegistryProperties: &containerregistry.RegistryProperties{
LoginServer: to.StringPtr("*.azurecr.io"), LoginServer: pointer.String("*.azurecr.io"),
}, },
}, },
{ {
Name: to.StringPtr("bar"), Name: pointer.String("bar"),
RegistryProperties: &containerregistry.RegistryProperties{ RegistryProperties: &containerregistry.RegistryProperties{
LoginServer: to.StringPtr("*.azurecr.cn"), LoginServer: pointer.String("*.azurecr.cn"),
}, },
}, },
{ {
Name: to.StringPtr("baz"), Name: pointer.String("baz"),
RegistryProperties: &containerregistry.RegistryProperties{ RegistryProperties: &containerregistry.RegistryProperties{
LoginServer: to.StringPtr("*.azurecr.de"), LoginServer: pointer.String("*.azurecr.de"),
}, },
}, },
{ {
Name: to.StringPtr("bus"), Name: pointer.String("bus"),
RegistryProperties: &containerregistry.RegistryProperties{ RegistryProperties: &containerregistry.RegistryProperties{
LoginServer: to.StringPtr("*.azurecr.us"), LoginServer: pointer.String("*.azurecr.us"),
}, },
}, },
} }

View File

@ -29,13 +29,13 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/Azure/go-autorest/autorest/to"
v1 "k8s.io/api/core/v1" v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes/fake" "k8s.io/client-go/kubernetes/fake"
fakecloud "k8s.io/cloud-provider/fake" fakecloud "k8s.io/cloud-provider/fake"
"k8s.io/mount-utils" "k8s.io/mount-utils"
"k8s.io/utils/pointer"
"k8s.io/kubernetes/pkg/volume" "k8s.io/kubernetes/pkg/volume"
volumetest "k8s.io/kubernetes/pkg/volume/testing" volumetest "k8s.io/kubernetes/pkg/volume/testing"
@ -384,7 +384,7 @@ func TestAppendDefaultMountOptions(t *testing.T) {
}, },
{ {
options: []string{"file_mode=0777"}, options: []string{"file_mode=0777"},
fsGroup: to.Int64Ptr(0), fsGroup: pointer.Int64(0),
expected: []string{"file_mode=0777", expected: []string{"file_mode=0777",
fmt.Sprintf("%s=%s", dirMode, defaultDirMode), fmt.Sprintf("%s=%s", dirMode, defaultDirMode),
fmt.Sprintf("%s=%s", vers, defaultVers), fmt.Sprintf("%s=%s", vers, defaultVers),
@ -395,7 +395,7 @@ func TestAppendDefaultMountOptions(t *testing.T) {
}, },
{ {
options: []string{"vers=2.1"}, options: []string{"vers=2.1"},
fsGroup: to.Int64Ptr(1000), fsGroup: pointer.Int64(1000),
expected: []string{"vers=2.1", expected: []string{"vers=2.1",
fmt.Sprintf("%s=%s", fileMode, defaultFileMode), fmt.Sprintf("%s=%s", fileMode, defaultFileMode),
fmt.Sprintf("%s=%s", dirMode, defaultDirMode), fmt.Sprintf("%s=%s", dirMode, defaultDirMode),
@ -424,7 +424,7 @@ func TestAppendDefaultMountOptions(t *testing.T) {
}, },
{ {
options: []string{"gid=2000"}, options: []string{"gid=2000"},
fsGroup: to.Int64Ptr(1000), fsGroup: pointer.Int64(1000),
expected: []string{"gid=2000", expected: []string{"gid=2000",
fmt.Sprintf("%s=%s", fileMode, defaultFileMode), fmt.Sprintf("%s=%s", fileMode, defaultFileMode),
fmt.Sprintf("%s=%s", dirMode, defaultDirMode), fmt.Sprintf("%s=%s", dirMode, defaultDirMode),

View File

@ -26,7 +26,6 @@ import (
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute"
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network"
"github.com/Azure/go-autorest/autorest/to"
v1 "k8s.io/api/core/v1" v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime"
@ -36,6 +35,7 @@ import (
"k8s.io/klog/v2" "k8s.io/klog/v2"
azcache "k8s.io/legacy-cloud-providers/azure/cache" azcache "k8s.io/legacy-cloud-providers/azure/cache"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
) )
const ( const (
@ -161,7 +161,7 @@ func (az *Cloud) CreateOrUpdateSecurityGroup(sg network.SecurityGroup) error {
ctx, cancel := getContextWithCancel() ctx, cancel := getContextWithCancel()
defer cancel() defer cancel()
rerr := az.SecurityGroupsClient.CreateOrUpdate(ctx, az.SecurityGroupResourceGroup, *sg.Name, sg, to.String(sg.Etag)) rerr := az.SecurityGroupsClient.CreateOrUpdate(ctx, az.SecurityGroupResourceGroup, *sg.Name, sg, pointer.StringDeref(sg.Etag, ""))
klog.V(10).Infof("SecurityGroupsClient.CreateOrUpdate(%s): end", *sg.Name) klog.V(10).Infof("SecurityGroupsClient.CreateOrUpdate(%s): end", *sg.Name)
if rerr == nil { if rerr == nil {
// Invalidate the cache right after updating // Invalidate the cache right after updating
@ -219,7 +219,7 @@ func (az *Cloud) CreateOrUpdateLB(service *v1.Service, lb network.LoadBalancer)
lb = cleanupSubnetInFrontendIPConfigurations(&lb) lb = cleanupSubnetInFrontendIPConfigurations(&lb)
rgName := az.getLoadBalancerResourceGroup() rgName := az.getLoadBalancerResourceGroup()
rerr := az.LoadBalancerClient.CreateOrUpdate(ctx, rgName, to.String(lb.Name), lb, to.String(lb.Etag)) rerr := az.LoadBalancerClient.CreateOrUpdate(ctx, rgName, pointer.StringDeref(lb.Name, ""), lb, pointer.StringDeref(lb.Etag, ""))
klog.V(10).Infof("LoadBalancerClient.CreateOrUpdate(%s): end", *lb.Name) klog.V(10).Infof("LoadBalancerClient.CreateOrUpdate(%s): end", *lb.Name)
if rerr == nil { if rerr == nil {
// Invalidate the cache right after updating // Invalidate the cache right after updating
@ -229,14 +229,14 @@ func (az *Cloud) CreateOrUpdateLB(service *v1.Service, lb network.LoadBalancer)
// Invalidate the cache because ETAG precondition mismatch. // Invalidate the cache because ETAG precondition mismatch.
if rerr.HTTPStatusCode == http.StatusPreconditionFailed { if rerr.HTTPStatusCode == http.StatusPreconditionFailed {
klog.V(3).Infof("LoadBalancer cache for %s is cleanup because of http.StatusPreconditionFailed", to.String(lb.Name)) klog.V(3).Infof("LoadBalancer cache for %s is cleanup because of http.StatusPreconditionFailed", pointer.StringDeref(lb.Name, ""))
az.lbCache.Delete(*lb.Name) az.lbCache.Delete(*lb.Name)
} }
retryErrorMessage := rerr.Error().Error() retryErrorMessage := rerr.Error().Error()
// Invalidate the cache because another new operation has canceled the current request. // Invalidate the cache because another new operation has canceled the current request.
if strings.Contains(strings.ToLower(retryErrorMessage), operationCanceledErrorMessage) { if strings.Contains(strings.ToLower(retryErrorMessage), operationCanceledErrorMessage) {
klog.V(3).Infof("LoadBalancer cache for %s is cleanup because CreateOrUpdate is canceled by another operation", to.String(lb.Name)) klog.V(3).Infof("LoadBalancer cache for %s is cleanup because CreateOrUpdate is canceled by another operation", pointer.StringDeref(lb.Name, ""))
az.lbCache.Delete(*lb.Name) az.lbCache.Delete(*lb.Name)
} }
@ -248,7 +248,7 @@ func (az *Cloud) CreateOrUpdateLB(service *v1.Service, lb network.LoadBalancer)
return rerr.Error() return rerr.Error()
} }
pipRG, pipName := matches[1], matches[2] pipRG, pipName := matches[1], matches[2]
klog.V(3).Infof("The public IP %s referenced by load balancer %s is not in Succeeded provisioning state, will try to update it", pipName, to.String(lb.Name)) klog.V(3).Infof("The public IP %s referenced by load balancer %s is not in Succeeded provisioning state, will try to update it", pipName, pointer.StringDeref(lb.Name, ""))
pip, _, err := az.getPublicIPAddress(pipRG, pipName) pip, _, err := az.getPublicIPAddress(pipRG, pipName)
if err != nil { if err != nil {
klog.Warningf("Failed to get the public IP %s in resource group %s: %v", pipName, pipRG, err) klog.Warningf("Failed to get the public IP %s in resource group %s: %v", pipName, pipRG, err)
@ -311,10 +311,10 @@ func (az *Cloud) CreateOrUpdatePIP(service *v1.Service, pipResourceGroup string,
ctx, cancel := getContextWithCancel() ctx, cancel := getContextWithCancel()
defer cancel() defer cancel()
rerr := az.PublicIPAddressesClient.CreateOrUpdate(ctx, pipResourceGroup, to.String(pip.Name), pip) rerr := az.PublicIPAddressesClient.CreateOrUpdate(ctx, pipResourceGroup, pointer.StringDeref(pip.Name, ""), pip)
klog.V(10).Infof("PublicIPAddressesClient.CreateOrUpdate(%s, %s): end", pipResourceGroup, to.String(pip.Name)) klog.V(10).Infof("PublicIPAddressesClient.CreateOrUpdate(%s, %s): end", pipResourceGroup, pointer.StringDeref(pip.Name, ""))
if rerr != nil { if rerr != nil {
klog.Errorf("PublicIPAddressesClient.CreateOrUpdate(%s, %s) failed: %s", pipResourceGroup, to.String(pip.Name), rerr.Error().Error()) klog.Errorf("PublicIPAddressesClient.CreateOrUpdate(%s, %s) failed: %s", pipResourceGroup, pointer.StringDeref(pip.Name, ""), rerr.Error().Error())
az.Event(service, v1.EventTypeWarning, "CreateOrUpdatePublicIPAddress", rerr.Error().Error()) az.Event(service, v1.EventTypeWarning, "CreateOrUpdatePublicIPAddress", rerr.Error().Error())
return rerr.Error() return rerr.Error()
} }
@ -381,7 +381,7 @@ func (az *Cloud) CreateOrUpdateRouteTable(routeTable network.RouteTable) error {
ctx, cancel := getContextWithCancel() ctx, cancel := getContextWithCancel()
defer cancel() defer cancel()
rerr := az.RouteTablesClient.CreateOrUpdate(ctx, az.RouteTableResourceGroup, az.RouteTableName, routeTable, to.String(routeTable.Etag)) rerr := az.RouteTablesClient.CreateOrUpdate(ctx, az.RouteTableResourceGroup, az.RouteTableName, routeTable, pointer.StringDeref(routeTable.Etag, ""))
if rerr == nil { if rerr == nil {
// Invalidate the cache right after updating // Invalidate the cache right after updating
az.rtCache.Delete(*routeTable.Name) az.rtCache.Delete(*routeTable.Name)
@ -407,7 +407,7 @@ func (az *Cloud) CreateOrUpdateRoute(route network.Route) error {
ctx, cancel := getContextWithCancel() ctx, cancel := getContextWithCancel()
defer cancel() defer cancel()
rerr := az.RoutesClient.CreateOrUpdate(ctx, az.RouteTableResourceGroup, az.RouteTableName, *route.Name, route, to.String(route.Etag)) rerr := az.RoutesClient.CreateOrUpdate(ctx, az.RouteTableResourceGroup, az.RouteTableName, *route.Name, route, pointer.StringDeref(route.Etag, ""))
klog.V(10).Infof("RoutesClient.CreateOrUpdate(%s): end", *route.Name) klog.V(10).Infof("RoutesClient.CreateOrUpdate(%s): end", *route.Name)
if rerr == nil { if rerr == nil {
az.rtCache.Delete(az.RouteTableName) az.rtCache.Delete(az.RouteTableName)

View File

@ -37,10 +37,10 @@ import (
"k8s.io/legacy-cloud-providers/azure/clients/vmclient/mockvmclient" "k8s.io/legacy-cloud-providers/azure/clients/vmclient/mockvmclient"
"k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient" "k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute"
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network"
"github.com/Azure/go-autorest/autorest/to"
"github.com/golang/mock/gomock" "github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -100,14 +100,14 @@ func TestGetPrivateIPsForMachine(t *testing.T) {
expectedVM := compute.VirtualMachine{ expectedVM := compute.VirtualMachine{
VirtualMachineProperties: &compute.VirtualMachineProperties{ VirtualMachineProperties: &compute.VirtualMachineProperties{
AvailabilitySet: &compute.SubResource{ID: to.StringPtr("availability-set")}, AvailabilitySet: &compute.SubResource{ID: pointer.String("availability-set")},
NetworkProfile: &compute.NetworkProfile{ NetworkProfile: &compute.NetworkProfile{
NetworkInterfaces: &[]compute.NetworkInterfaceReference{ NetworkInterfaces: &[]compute.NetworkInterfaceReference{
{ {
NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{ NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{
Primary: to.BoolPtr(true), Primary: pointer.Bool(true),
}, },
ID: to.StringPtr("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic"), ID: pointer.String("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic"),
}, },
}, },
}, },
@ -119,7 +119,7 @@ func TestGetPrivateIPsForMachine(t *testing.T) {
IPConfigurations: &[]network.InterfaceIPConfiguration{ IPConfigurations: &[]network.InterfaceIPConfiguration{
{ {
InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{
PrivateIPAddress: to.StringPtr("1.2.3.4"), PrivateIPAddress: pointer.String("1.2.3.4"),
}, },
}, },
}, },
@ -162,14 +162,14 @@ func TestGetIPForMachineWithRetry(t *testing.T) {
expectedVM := compute.VirtualMachine{ expectedVM := compute.VirtualMachine{
VirtualMachineProperties: &compute.VirtualMachineProperties{ VirtualMachineProperties: &compute.VirtualMachineProperties{
AvailabilitySet: &compute.SubResource{ID: to.StringPtr("availability-set")}, AvailabilitySet: &compute.SubResource{ID: pointer.String("availability-set")},
NetworkProfile: &compute.NetworkProfile{ NetworkProfile: &compute.NetworkProfile{
NetworkInterfaces: &[]compute.NetworkInterfaceReference{ NetworkInterfaces: &[]compute.NetworkInterfaceReference{
{ {
NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{ NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{
Primary: to.BoolPtr(true), Primary: pointer.Bool(true),
}, },
ID: to.StringPtr("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic"), ID: pointer.String("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic"),
}, },
}, },
}, },
@ -181,9 +181,9 @@ func TestGetIPForMachineWithRetry(t *testing.T) {
IPConfigurations: &[]network.InterfaceIPConfiguration{ IPConfigurations: &[]network.InterfaceIPConfiguration{
{ {
InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{
PrivateIPAddress: to.StringPtr("1.2.3.4"), PrivateIPAddress: pointer.String("1.2.3.4"),
PublicIPAddress: &network.PublicIPAddress{ PublicIPAddress: &network.PublicIPAddress{
ID: to.StringPtr("test/pip"), ID: pointer.String("test/pip"),
}, },
}, },
}, },
@ -193,7 +193,7 @@ func TestGetIPForMachineWithRetry(t *testing.T) {
expectedPIP := network.PublicIPAddress{ expectedPIP := network.PublicIPAddress{
PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{
IPAddress: to.StringPtr("5.6.7.8"), IPAddress: pointer.String("5.6.7.8"),
}, },
} }
@ -228,7 +228,7 @@ func TestCreateOrUpdateSecurityGroupCanceled(t *testing.T) {
}) })
mockSGClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, "sg", gomock.Any()).Return(network.SecurityGroup{}, nil) mockSGClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, "sg", gomock.Any()).Return(network.SecurityGroup{}, nil)
err := az.CreateOrUpdateSecurityGroup(network.SecurityGroup{Name: to.StringPtr("sg")}) err := az.CreateOrUpdateSecurityGroup(network.SecurityGroup{Name: pointer.String("sg")})
assert.EqualError(t, fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: %w", fmt.Errorf("canceledandsupersededduetoanotheroperation")), err.Error()) assert.EqualError(t, fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: %w", fmt.Errorf("canceledandsupersededduetoanotheroperation")), err.Error())
// security group should be removed from cache if the operation is canceled // security group should be removed from cache if the operation is canceled
@ -272,15 +272,15 @@ func TestCreateOrUpdateLB(t *testing.T) {
mockPIPClient := az.PublicIPAddressesClient.(*mockpublicipclient.MockInterface) mockPIPClient := az.PublicIPAddressesClient.(*mockpublicipclient.MockInterface)
mockPIPClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, "pip", gomock.Any()).Return(nil).AnyTimes() mockPIPClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, "pip", gomock.Any()).Return(nil).AnyTimes()
mockPIPClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, "pip", gomock.Any()).Return(network.PublicIPAddress{ mockPIPClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, "pip", gomock.Any()).Return(network.PublicIPAddress{
Name: to.StringPtr("pip"), Name: pointer.String("pip"),
PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{
ProvisioningState: to.StringPtr("Succeeded"), ProvisioningState: pointer.String("Succeeded"),
}, },
}, nil).AnyTimes() }, nil).AnyTimes()
err := az.CreateOrUpdateLB(&v1.Service{}, network.LoadBalancer{ err := az.CreateOrUpdateLB(&v1.Service{}, network.LoadBalancer{
Name: to.StringPtr("lb"), Name: pointer.String("lb"),
Etag: to.StringPtr("etag"), Etag: pointer.String("etag"),
}) })
assert.Equal(t, test.expectedErr, err) assert.Equal(t, test.expectedErr, err)
@ -356,7 +356,7 @@ func TestCreateOrUpdatePIP(t *testing.T) {
mockPIPClient := az.PublicIPAddressesClient.(*mockpublicipclient.MockInterface) mockPIPClient := az.PublicIPAddressesClient.(*mockpublicipclient.MockInterface)
mockPIPClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, "nic", gomock.Any()).Return(&retry.Error{HTTPStatusCode: http.StatusInternalServerError}) mockPIPClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, "nic", gomock.Any()).Return(&retry.Error{HTTPStatusCode: http.StatusInternalServerError})
err := az.CreateOrUpdatePIP(&v1.Service{}, az.ResourceGroup, network.PublicIPAddress{Name: to.StringPtr("nic")}) err := az.CreateOrUpdatePIP(&v1.Service{}, az.ResourceGroup, network.PublicIPAddress{Name: pointer.String("nic")})
assert.Equal(t, fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 500, RawError: %w", error(nil)), err) assert.Equal(t, fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 500, RawError: %w", error(nil)), err)
} }
@ -368,7 +368,7 @@ func TestCreateOrUpdateInterface(t *testing.T) {
mockInterfaceClient := az.InterfacesClient.(*mockinterfaceclient.MockInterface) mockInterfaceClient := az.InterfacesClient.(*mockinterfaceclient.MockInterface)
mockInterfaceClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, "nic", gomock.Any()).Return(&retry.Error{HTTPStatusCode: http.StatusInternalServerError}) mockInterfaceClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, "nic", gomock.Any()).Return(&retry.Error{HTTPStatusCode: http.StatusInternalServerError})
err := az.CreateOrUpdateInterface(&v1.Service{}, network.Interface{Name: to.StringPtr("nic")}) err := az.CreateOrUpdateInterface(&v1.Service{}, network.Interface{Name: pointer.String("nic")})
assert.Equal(t, fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 500, RawError: %w", error(nil)), err) assert.Equal(t, fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 500, RawError: %w", error(nil)), err)
} }
@ -423,8 +423,8 @@ func TestCreateOrUpdateRouteTable(t *testing.T) {
mockRTClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, "rt", gomock.Any()).Return(network.RouteTable{}, nil) mockRTClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, "rt", gomock.Any()).Return(network.RouteTable{}, nil)
err := az.CreateOrUpdateRouteTable(network.RouteTable{ err := az.CreateOrUpdateRouteTable(network.RouteTable{
Name: to.StringPtr("rt"), Name: pointer.String("rt"),
Etag: to.StringPtr("etag"), Etag: pointer.String("etag"),
}) })
assert.Equal(t, test.expectedErr, err) assert.Equal(t, test.expectedErr, err)
@ -468,8 +468,8 @@ func TestCreateOrUpdateRoute(t *testing.T) {
mockRTableClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, "rt", gomock.Any()).Return(network.RouteTable{}, nil) mockRTableClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, "rt", gomock.Any()).Return(network.RouteTable{}, nil)
err := az.CreateOrUpdateRoute(network.Route{ err := az.CreateOrUpdateRoute(network.Route{
Name: to.StringPtr("rt"), Name: pointer.String("rt"),
Etag: to.StringPtr("etag"), Etag: pointer.String("etag"),
}) })
assert.Equal(t, test.expectedErr, err) assert.Equal(t, test.expectedErr, err)

View File

@ -33,12 +33,12 @@ import (
"github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2019-06-01/storage" "github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2019-06-01/storage"
azstorage "github.com/Azure/azure-sdk-for-go/storage" azstorage "github.com/Azure/azure-sdk-for-go/storage"
"github.com/Azure/go-autorest/autorest/to"
"github.com/rubiojr/go-vhd/vhd" "github.com/rubiojr/go-vhd/vhd"
kwait "k8s.io/apimachinery/pkg/util/wait" kwait "k8s.io/apimachinery/pkg/util/wait"
volerr "k8s.io/cloud-provider/volume/errors" volerr "k8s.io/cloud-provider/volume/errors"
"k8s.io/klog/v2" "k8s.io/klog/v2"
"k8s.io/utils/pointer"
) )
// Attention: blob disk feature is deprecated // Attention: blob disk feature is deprecated
@ -504,7 +504,7 @@ func (c *BlobDiskController) createStorageAccount(storageAccountName string, sto
Sku: &storage.Sku{Name: storageAccountType}, Sku: &storage.Sku{Name: storageAccountType},
// switch to use StorageV2 as it's recommended according to https://docs.microsoft.com/en-us/azure/storage/common/storage-account-options // switch to use StorageV2 as it's recommended according to https://docs.microsoft.com/en-us/azure/storage/common/storage-account-options
Kind: defaultStorageAccountKind, Kind: defaultStorageAccountKind,
Tags: map[string]*string{"created-by": to.StringPtr("azure-dd")}, Tags: map[string]*string{"created-by": pointer.String("azure-dd")},
Location: &location} Location: &location}
ctx, cancel := getContextWithCancel() ctx, cancel := getContextWithCancel()
defer cancel() defer cancel()

View File

@ -27,11 +27,11 @@ import (
"k8s.io/legacy-cloud-providers/azure/clients/storageaccountclient/mockstorageaccountclient" "k8s.io/legacy-cloud-providers/azure/clients/storageaccountclient/mockstorageaccountclient"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
"github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2019-06-01/storage" "github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2019-06-01/storage"
azstorage "github.com/Azure/azure-sdk-for-go/storage" azstorage "github.com/Azure/azure-sdk-for-go/storage"
autorestazure "github.com/Azure/go-autorest/autorest/azure" autorestazure "github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/to"
"github.com/golang/mock/gomock" "github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -66,7 +66,7 @@ func TestInitStorageAccounts(t *testing.T) {
mockSAClient.EXPECT().ListByResourceGroup(gomock.Any(), b.common.resourceGroup).Return([]storage.Account{ mockSAClient.EXPECT().ListByResourceGroup(gomock.Any(), b.common.resourceGroup).Return([]storage.Account{
{ {
Name: to.StringPtr("ds-0"), Name: pointer.String("ds-0"),
Sku: &storage.Sku{Name: "sku"}, Sku: &storage.Sku{Name: "sku"},
}, },
}, nil) }, nil)
@ -96,8 +96,8 @@ func TestCreateVolume(t *testing.T) {
mockSAClient.EXPECT().ListKeys(gomock.Any(), b.common.resourceGroup, "testsa").Return(storage.AccountListKeysResult{ mockSAClient.EXPECT().ListKeys(gomock.Any(), b.common.resourceGroup, "testsa").Return(storage.AccountListKeysResult{
Keys: &[]storage.AccountKey{ Keys: &[]storage.AccountKey{
{ {
KeyName: to.StringPtr("key1"), KeyName: pointer.String("key1"),
Value: to.StringPtr("dmFsdWUK"), Value: pointer.String("dmFsdWUK"),
}, },
}, },
}, nil) }, nil)
@ -132,8 +132,8 @@ func TestDeleteVolume(t *testing.T) {
mockSAClient.EXPECT().ListKeys(gomock.Any(), b.common.resourceGroup, "foo").Return(storage.AccountListKeysResult{ mockSAClient.EXPECT().ListKeys(gomock.Any(), b.common.resourceGroup, "foo").Return(storage.AccountListKeysResult{
Keys: &[]storage.AccountKey{ Keys: &[]storage.AccountKey{
{ {
KeyName: to.StringPtr("key1"), KeyName: pointer.String("key1"),
Value: to.StringPtr("dmFsdWUK"), Value: pointer.String("dmFsdWUK"),
}, },
}, },
}, nil) }, nil)
@ -172,14 +172,14 @@ func TestGetAllStorageAccounts(t *testing.T) {
expectedStorageAccounts := []storage.Account{ expectedStorageAccounts := []storage.Account{
{ {
Name: to.StringPtr("this-should-be-skipped"), Name: pointer.String("this-should-be-skipped"),
}, },
{ {
Name: to.StringPtr("this-should-be-skipped"), Name: pointer.String("this-should-be-skipped"),
Sku: &storage.Sku{Name: "sku"}, Sku: &storage.Sku{Name: "sku"},
}, },
{ {
Name: to.StringPtr("ds-0"), Name: pointer.String("ds-0"),
Sku: &storage.Sku{Name: "sku"}, Sku: &storage.Sku{Name: "sku"},
}, },
} }
@ -221,8 +221,8 @@ func TestEnsureDefaultContainer(t *testing.T) {
mockSAClient.EXPECT().ListKeys(gomock.Any(), b.common.resourceGroup, "testsa").Return(storage.AccountListKeysResult{ mockSAClient.EXPECT().ListKeys(gomock.Any(), b.common.resourceGroup, "testsa").Return(storage.AccountListKeysResult{
Keys: &[]storage.AccountKey{ Keys: &[]storage.AccountKey{
{ {
KeyName: to.StringPtr("key1"), KeyName: pointer.String("key1"),
Value: to.StringPtr("key1"), Value: pointer.String("key1"),
}, },
}, },
}, nil) }, nil)
@ -256,8 +256,8 @@ func TestGetDiskCount(t *testing.T) {
mockSAClient.EXPECT().ListKeys(gomock.Any(), b.common.resourceGroup, "testsa").Return(storage.AccountListKeysResult{ mockSAClient.EXPECT().ListKeys(gomock.Any(), b.common.resourceGroup, "testsa").Return(storage.AccountListKeysResult{
Keys: &[]storage.AccountKey{ Keys: &[]storage.AccountKey{
{ {
KeyName: to.StringPtr("key1"), KeyName: pointer.String("key1"),
Value: to.StringPtr("key1"), Value: pointer.String("key1"),
}, },
}, },
}, nil) }, nil)
@ -291,8 +291,8 @@ func TestFindSANameForDisk(t *testing.T) {
mockSAClient.EXPECT().ListKeys(gomock.Any(), b.common.resourceGroup, gomock.Any()).Return(storage.AccountListKeysResult{ mockSAClient.EXPECT().ListKeys(gomock.Any(), b.common.resourceGroup, gomock.Any()).Return(storage.AccountListKeysResult{
Keys: &[]storage.AccountKey{ Keys: &[]storage.AccountKey{
{ {
KeyName: to.StringPtr("key1"), KeyName: pointer.String("key1"),
Value: to.StringPtr("key1"), Value: pointer.String("key1"),
}, },
}, },
}, nil) }, nil)
@ -348,8 +348,8 @@ func TestCreateBlobDisk(t *testing.T) {
mockSAClient.EXPECT().ListKeys(gomock.Any(), b.common.resourceGroup, gomock.Any()).Return(storage.AccountListKeysResult{ mockSAClient.EXPECT().ListKeys(gomock.Any(), b.common.resourceGroup, gomock.Any()).Return(storage.AccountListKeysResult{
Keys: &[]storage.AccountKey{ Keys: &[]storage.AccountKey{
{ {
KeyName: to.StringPtr("key1"), KeyName: pointer.String("key1"),
Value: to.StringPtr("key1"), Value: pointer.String("key1"),
}, },
}, },
}, nil) }, nil)

View File

@ -23,13 +23,13 @@ import (
"context" "context"
"testing" "testing"
"github.com/Azure/go-autorest/autorest/to"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
v1 "k8s.io/api/core/v1" v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
fakeclient "k8s.io/client-go/kubernetes/fake" fakeclient "k8s.io/client-go/kubernetes/fake"
"k8s.io/legacy-cloud-providers/azure/auth" "k8s.io/legacy-cloud-providers/azure/auth"
"k8s.io/utils/pointer"
"sigs.k8s.io/yaml" "sigs.k8s.io/yaml"
) )
@ -50,7 +50,7 @@ func getTestConfig() *Config {
PrimaryAvailabilitySetName: "PrimaryAvailabilitySetName", PrimaryAvailabilitySetName: "PrimaryAvailabilitySetName",
PrimaryScaleSetName: "PrimaryScaleSetName", PrimaryScaleSetName: "PrimaryScaleSetName",
LoadBalancerSku: "LoadBalancerSku", LoadBalancerSku: "LoadBalancerSku",
ExcludeMasterFromStandardLB: to.BoolPtr(true), ExcludeMasterFromStandardLB: pointer.Bool(true),
} }
} }

View File

@ -26,7 +26,6 @@ import (
"testing" "testing"
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute"
"github.com/Azure/go-autorest/autorest/to"
"github.com/golang/mock/gomock" "github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -49,7 +48,7 @@ func TestCommonAttachDisk(t *testing.T) {
goodInstanceID := fmt.Sprintf("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/%s", "vm1") goodInstanceID := fmt.Sprintf("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/%s", "vm1")
diskEncryptionSetID := fmt.Sprintf("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Compute/diskEncryptionSets/%s", "diskEncryptionSet-name") diskEncryptionSetID := fmt.Sprintf("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Compute/diskEncryptionSets/%s", "diskEncryptionSet-name")
testTags := make(map[string]*string) testTags := make(map[string]*string)
testTags[WriteAcceleratorEnabled] = to.StringPtr("true") testTags[WriteAcceleratorEnabled] = pointer.String("true")
testCases := []struct { testCases := []struct {
desc string desc string
vmList map[string]string vmList map[string]string
@ -64,7 +63,7 @@ func TestCommonAttachDisk(t *testing.T) {
{ {
desc: "LUN -1 and error shall be returned if there's no such instance corresponding to given nodeName", desc: "LUN -1 and error shall be returned if there's no such instance corresponding to given nodeName",
nodeName: "vm1", nodeName: "vm1",
existedDisk: compute.Disk{Name: to.StringPtr("disk-name")}, existedDisk: compute.Disk{Name: pointer.String("disk-name")},
expectedLun: -1, expectedLun: -1,
expectedErr: true, expectedErr: true,
}, },
@ -73,7 +72,7 @@ func TestCommonAttachDisk(t *testing.T) {
vmList: map[string]string{"vm1": "PowerState/Running"}, vmList: map[string]string{"vm1": "PowerState/Running"},
nodeName: "vm1", nodeName: "vm1",
isDataDisksFull: true, isDataDisksFull: true,
existedDisk: compute.Disk{Name: to.StringPtr("disk-name")}, existedDisk: compute.Disk{Name: pointer.String("disk-name")},
expectedLun: -1, expectedLun: -1,
expectedErr: true, expectedErr: true,
}, },
@ -81,10 +80,10 @@ func TestCommonAttachDisk(t *testing.T) {
desc: "correct LUN and no error shall be returned if everything is good", desc: "correct LUN and no error shall be returned if everything is good",
vmList: map[string]string{"vm1": "PowerState/Running"}, vmList: map[string]string{"vm1": "PowerState/Running"},
nodeName: "vm1", nodeName: "vm1",
existedDisk: compute.Disk{Name: to.StringPtr("disk-name"), existedDisk: compute.Disk{Name: pointer.String("disk-name"),
DiskProperties: &compute.DiskProperties{ DiskProperties: &compute.DiskProperties{
Encryption: &compute.Encryption{DiskEncryptionSetID: &diskEncryptionSetID, Type: compute.EncryptionAtRestWithCustomerKey}, Encryption: &compute.Encryption{DiskEncryptionSetID: &diskEncryptionSetID, Type: compute.EncryptionAtRestWithCustomerKey},
DiskSizeGB: to.Int32Ptr(4096), DiskSizeGB: pointer.Int32(4096),
}, },
Tags: testTags}, Tags: testTags},
expectedLun: 1, expectedLun: 1,
@ -95,7 +94,7 @@ func TestCommonAttachDisk(t *testing.T) {
vmList: map[string]string{"vm1": "PowerState/Running"}, vmList: map[string]string{"vm1": "PowerState/Running"},
nodeName: "vm1", nodeName: "vm1",
isBadDiskURI: true, isBadDiskURI: true,
existedDisk: compute.Disk{Name: to.StringPtr("disk-name")}, existedDisk: compute.Disk{Name: pointer.String("disk-name")},
expectedLun: -1, expectedLun: -1,
expectedErr: true, expectedErr: true,
}, },
@ -103,7 +102,7 @@ func TestCommonAttachDisk(t *testing.T) {
desc: "an error shall be returned if attach an already attached disk with good ManagedBy instance id", desc: "an error shall be returned if attach an already attached disk with good ManagedBy instance id",
vmList: map[string]string{"vm1": "PowerState/Running"}, vmList: map[string]string{"vm1": "PowerState/Running"},
nodeName: "vm1", nodeName: "vm1",
existedDisk: compute.Disk{Name: to.StringPtr("disk-name"), ManagedBy: to.StringPtr(goodInstanceID), DiskProperties: &compute.DiskProperties{MaxShares: &maxShare}}, existedDisk: compute.Disk{Name: pointer.String("disk-name"), ManagedBy: pointer.String(goodInstanceID), DiskProperties: &compute.DiskProperties{MaxShares: &maxShare}},
expectedLun: -1, expectedLun: -1,
expectedErr: true, expectedErr: true,
}, },
@ -111,7 +110,7 @@ func TestCommonAttachDisk(t *testing.T) {
desc: "an error shall be returned if attach an already attached disk with bad ManagedBy instance id", desc: "an error shall be returned if attach an already attached disk with bad ManagedBy instance id",
vmList: map[string]string{"vm1": "PowerState/Running"}, vmList: map[string]string{"vm1": "PowerState/Running"},
nodeName: "vm1", nodeName: "vm1",
existedDisk: compute.Disk{Name: to.StringPtr("disk-name"), ManagedBy: to.StringPtr("test"), DiskProperties: &compute.DiskProperties{MaxShares: &maxShare}}, existedDisk: compute.Disk{Name: pointer.String("disk-name"), ManagedBy: pointer.String("test"), DiskProperties: &compute.DiskProperties{MaxShares: &maxShare}},
expectedLun: -1, expectedLun: -1,
expectedErr: true, expectedErr: true,
}, },
@ -119,7 +118,7 @@ func TestCommonAttachDisk(t *testing.T) {
desc: "an error shall be returned if there's no matching disk", desc: "an error shall be returned if there's no matching disk",
vmList: map[string]string{"vm1": "PowerState/Running"}, vmList: map[string]string{"vm1": "PowerState/Running"},
nodeName: "vm1", nodeName: "vm1",
existedDisk: compute.Disk{Name: to.StringPtr("disk-name-1")}, existedDisk: compute.Disk{Name: pointer.String("disk-name-1")},
expectedLun: -1, expectedLun: -1,
expectedErr: true, expectedErr: true,
}, },
@ -189,7 +188,7 @@ func TestCommonAttachDiskWithVMSS(t *testing.T) {
isVMSS: false, isVMSS: false,
isManagedBy: false, isManagedBy: false,
isManagedDisk: false, isManagedDisk: false,
existedDisk: compute.Disk{Name: to.StringPtr("disk-name")}, existedDisk: compute.Disk{Name: pointer.String("disk-name")},
expectedLun: -1, expectedLun: -1,
expectedErr: true, expectedErr: true,
}, },
@ -200,7 +199,7 @@ func TestCommonAttachDiskWithVMSS(t *testing.T) {
isVMSS: true, isVMSS: true,
isManagedBy: false, isManagedBy: false,
isManagedDisk: false, isManagedDisk: false,
existedDisk: compute.Disk{Name: to.StringPtr("disk-name")}, existedDisk: compute.Disk{Name: pointer.String("disk-name")},
expectedLun: -1, expectedLun: -1,
expectedErr: true, expectedErr: true,
}, },
@ -213,7 +212,7 @@ func TestCommonAttachDiskWithVMSS(t *testing.T) {
if test.isManagedBy { if test.isManagedBy {
testCloud.DisableAvailabilitySetNodes = false testCloud.DisableAvailabilitySetNodes = false
testVMSSName := "vmss" testVMSSName := "vmss"
expectedVMSS := compute.VirtualMachineScaleSet{Name: to.StringPtr(testVMSSName)} expectedVMSS := compute.VirtualMachineScaleSet{Name: pointer.String(testVMSSName)}
mockVMSSClient := testCloud.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) mockVMSSClient := testCloud.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface)
mockVMSSClient.EXPECT().List(gomock.Any(), testCloud.ResourceGroup).Return([]compute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes() mockVMSSClient.EXPECT().List(gomock.Any(), testCloud.ResourceGroup).Return([]compute.VirtualMachineScaleSet{expectedVMSS}, nil).AnyTimes()

View File

@ -24,11 +24,11 @@ import (
"strings" "strings"
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute"
"github.com/Azure/go-autorest/autorest/to"
"k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/types"
"k8s.io/klog/v2" "k8s.io/klog/v2"
azcache "k8s.io/legacy-cloud-providers/azure/cache" azcache "k8s.io/legacy-cloud-providers/azure/cache"
"k8s.io/utils/pointer"
) )
// AttachDisk attaches a vhd to vm // AttachDisk attaches a vhd to vm
@ -69,7 +69,7 @@ func (as *availabilitySet) AttachDisk(isManagedDisk bool, diskName, diskURI stri
Caching: cachingMode, Caching: cachingMode,
CreateOption: "attach", CreateOption: "attach",
ManagedDisk: managedDisk, ManagedDisk: managedDisk,
WriteAcceleratorEnabled: to.BoolPtr(writeAcceleratorEnabled), WriteAcceleratorEnabled: pointer.Bool(writeAcceleratorEnabled),
}) })
} else { } else {
disks = append(disks, disks = append(disks,
@ -145,7 +145,7 @@ func (as *availabilitySet) DetachDisk(diskName, diskURI string, nodeName types.N
if strings.EqualFold(as.cloud.Environment.Name, AzureStackCloudName) { if strings.EqualFold(as.cloud.Environment.Name, AzureStackCloudName) {
disks = append(disks[:i], disks[i+1:]...) disks = append(disks[:i], disks[i+1:]...)
} else { } else {
disks[i].ToBeDetached = to.BoolPtr(true) disks[i].ToBeDetached = pointer.Bool(true)
} }
bFoundDisk = true bFoundDisk = true
break break

View File

@ -25,7 +25,6 @@ import (
"time" "time"
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute"
"github.com/Azure/go-autorest/autorest/to"
"github.com/golang/mock/gomock" "github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -34,6 +33,7 @@ import (
azcache "k8s.io/legacy-cloud-providers/azure/cache" azcache "k8s.io/legacy-cloud-providers/azure/cache"
"k8s.io/legacy-cloud-providers/azure/clients/vmclient/mockvmclient" "k8s.io/legacy-cloud-providers/azure/clients/vmclient/mockvmclient"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
) )
var ( var (
@ -86,11 +86,11 @@ func TestStandardAttachDisk(t *testing.T) {
for _, vm := range expectedVMs { for _, vm := range expectedVMs {
vm.StorageProfile = &compute.StorageProfile{ vm.StorageProfile = &compute.StorageProfile{
OsDisk: &compute.OSDisk{ OsDisk: &compute.OSDisk{
Name: to.StringPtr("osdisk1"), Name: pointer.String("osdisk1"),
ManagedDisk: &compute.ManagedDiskParameters{ ManagedDisk: &compute.ManagedDiskParameters{
ID: to.StringPtr("ManagedID"), ID: pointer.String("ManagedID"),
DiskEncryptionSet: &compute.DiskEncryptionSetParameters{ DiskEncryptionSet: &compute.DiskEncryptionSetParameters{
ID: to.StringPtr("DiskEncryptionSetID"), ID: pointer.String("DiskEncryptionSetID"),
}, },
}, },
}, },
@ -195,8 +195,8 @@ func TestGetDataDisks(t *testing.T) {
nodeName: "vm1", nodeName: "vm1",
expectedDataDisks: []compute.DataDisk{ expectedDataDisks: []compute.DataDisk{
{ {
Lun: to.Int32Ptr(0), Lun: pointer.Int32(0),
Name: to.StringPtr("disk1"), Name: pointer.String("disk1"),
}, },
}, },
expectedError: false, expectedError: false,
@ -207,8 +207,8 @@ func TestGetDataDisks(t *testing.T) {
nodeName: "vm1", nodeName: "vm1",
expectedDataDisks: []compute.DataDisk{ expectedDataDisks: []compute.DataDisk{
{ {
Lun: to.Int32Ptr(0), Lun: pointer.Int32(0),
Name: to.StringPtr("disk1"), Name: pointer.String("disk1"),
}, },
}, },
expectedError: false, expectedError: false,

View File

@ -24,11 +24,11 @@ import (
"strings" "strings"
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute"
"github.com/Azure/go-autorest/autorest/to"
"k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/types"
"k8s.io/klog/v2" "k8s.io/klog/v2"
azcache "k8s.io/legacy-cloud-providers/azure/cache" azcache "k8s.io/legacy-cloud-providers/azure/cache"
"k8s.io/utils/pointer"
) )
// AttachDisk attaches a vhd to vm // AttachDisk attaches a vhd to vm
@ -71,7 +71,7 @@ func (ss *scaleSet) AttachDisk(isManagedDisk bool, diskName, diskURI string, nod
Caching: compute.CachingTypes(cachingMode), Caching: compute.CachingTypes(cachingMode),
CreateOption: "attach", CreateOption: "attach",
ManagedDisk: managedDisk, ManagedDisk: managedDisk,
WriteAcceleratorEnabled: to.BoolPtr(writeAcceleratorEnabled), WriteAcceleratorEnabled: pointer.Bool(writeAcceleratorEnabled),
}) })
} else { } else {
disks = append(disks, disks = append(disks,
@ -147,7 +147,7 @@ func (ss *scaleSet) DetachDisk(diskName, diskURI string, nodeName types.NodeName
if strings.EqualFold(ss.cloud.Environment.Name, AzureStackCloudName) { if strings.EqualFold(ss.cloud.Environment.Name, AzureStackCloudName) {
disks = append(disks[:i], disks[i+1:]...) disks = append(disks[:i], disks[i+1:]...)
} else { } else {
disks[i].ToBeDetached = to.BoolPtr(true) disks[i].ToBeDetached = pointer.Bool(true)
} }
bFoundDisk = true bFoundDisk = true
break break

View File

@ -25,7 +25,6 @@ import (
"testing" "testing"
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute"
"github.com/Azure/go-autorest/autorest/to"
"github.com/golang/mock/gomock" "github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -35,6 +34,7 @@ import (
"k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient" "k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient"
"k8s.io/legacy-cloud-providers/azure/clients/vmssvmclient/mockvmssvmclient" "k8s.io/legacy-cloud-providers/azure/clients/vmssvmclient/mockvmssvmclient"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
) )
func TestAttachDiskWithVMSS(t *testing.T) { func TestAttachDiskWithVMSS(t *testing.T) {
@ -59,7 +59,7 @@ func TestAttachDiskWithVMSS(t *testing.T) {
vmssName: "vm1", vmssName: "vm1",
vmssvmName: "vm1", vmssvmName: "vm1",
isManagedDisk: false, isManagedDisk: false,
existedDisk: compute.Disk{Name: to.StringPtr("disk-name")}, existedDisk: compute.Disk{Name: pointer.String("disk-name")},
expectedErr: true, expectedErr: true,
expectedErrMsg: fmt.Errorf("not a vmss instance"), expectedErrMsg: fmt.Errorf("not a vmss instance"),
}, },
@ -69,7 +69,7 @@ func TestAttachDiskWithVMSS(t *testing.T) {
vmssName: "vmss00", vmssName: "vmss00",
vmssvmName: "vmss00-vm-000000", vmssvmName: "vmss00-vm-000000",
isManagedDisk: true, isManagedDisk: true,
existedDisk: compute.Disk{Name: to.StringPtr("disk-name")}, existedDisk: compute.Disk{Name: pointer.String("disk-name")},
expectedErr: false, expectedErr: false,
}, },
{ {
@ -78,7 +78,7 @@ func TestAttachDiskWithVMSS(t *testing.T) {
vmssName: "vmss00", vmssName: "vmss00",
vmssvmName: "vmss00-vm-000000", vmssvmName: "vmss00-vm-000000",
isManagedDisk: false, isManagedDisk: false,
existedDisk: compute.Disk{Name: to.StringPtr("disk-name")}, existedDisk: compute.Disk{Name: pointer.String("disk-name")},
expectedErr: false, expectedErr: false,
}, },
{ {
@ -87,7 +87,7 @@ func TestAttachDiskWithVMSS(t *testing.T) {
vmssName: fakeStatusNotFoundVMSSName, vmssName: fakeStatusNotFoundVMSSName,
vmssvmName: "vmss00-vm-000000", vmssvmName: "vmss00-vm-000000",
isManagedDisk: false, isManagedDisk: false,
existedDisk: compute.Disk{Name: to.StringPtr("disk-name")}, existedDisk: compute.Disk{Name: pointer.String("disk-name")},
expectedErr: true, expectedErr: true,
expectedErrMsg: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 404, RawError: %w", cloudprovider.InstanceNotFound), expectedErrMsg: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 404, RawError: %w", cloudprovider.InstanceNotFound),
}, },
@ -109,11 +109,11 @@ func TestAttachDiskWithVMSS(t *testing.T) {
for _, vmssvm := range expectedVMSSVMs { for _, vmssvm := range expectedVMSSVMs {
vmssvm.StorageProfile = &compute.StorageProfile{ vmssvm.StorageProfile = &compute.StorageProfile{
OsDisk: &compute.OSDisk{ OsDisk: &compute.OSDisk{
Name: to.StringPtr("osdisk1"), Name: pointer.String("osdisk1"),
ManagedDisk: &compute.ManagedDiskParameters{ ManagedDisk: &compute.ManagedDiskParameters{
ID: to.StringPtr("ManagedID"), ID: pointer.String("ManagedID"),
DiskEncryptionSet: &compute.DiskEncryptionSetParameters{ DiskEncryptionSet: &compute.DiskEncryptionSetParameters{
ID: to.StringPtr("DiskEncryptionSetID"), ID: pointer.String("DiskEncryptionSetID"),
}, },
}, },
}, },
@ -158,7 +158,7 @@ func TestDetachDiskWithVMSS(t *testing.T) {
vmssVMList: []string{"vmss-vm-000001"}, vmssVMList: []string{"vmss-vm-000001"},
vmssName: "vm1", vmssName: "vm1",
vmssvmName: "vm1", vmssvmName: "vm1",
existedDisk: compute.Disk{Name: to.StringPtr(diskName)}, existedDisk: compute.Disk{Name: pointer.String(diskName)},
expectedErr: true, expectedErr: true,
expectedErrMsg: fmt.Errorf("not a vmss instance"), expectedErrMsg: fmt.Errorf("not a vmss instance"),
}, },
@ -167,7 +167,7 @@ func TestDetachDiskWithVMSS(t *testing.T) {
vmssVMList: []string{"vmss00-vm-000000", "vmss00-vm-000001", "vmss00-vm-000002"}, vmssVMList: []string{"vmss00-vm-000000", "vmss00-vm-000001", "vmss00-vm-000002"},
vmssName: "vmss00", vmssName: "vmss00",
vmssvmName: "vmss00-vm-000000", vmssvmName: "vmss00-vm-000000",
existedDisk: compute.Disk{Name: to.StringPtr(diskName)}, existedDisk: compute.Disk{Name: pointer.String(diskName)},
expectedErr: false, expectedErr: false,
}, },
{ {
@ -175,7 +175,7 @@ func TestDetachDiskWithVMSS(t *testing.T) {
vmssVMList: []string{"vmss00-vm-000000", "vmss00-vm-000001", "vmss00-vm-000002"}, vmssVMList: []string{"vmss00-vm-000000", "vmss00-vm-000001", "vmss00-vm-000002"},
vmssName: fakeStatusNotFoundVMSSName, vmssName: fakeStatusNotFoundVMSSName,
vmssvmName: "vmss00-vm-000000", vmssvmName: "vmss00-vm-000000",
existedDisk: compute.Disk{Name: to.StringPtr(diskName)}, existedDisk: compute.Disk{Name: pointer.String(diskName)},
expectedErr: true, expectedErr: true,
expectedErrMsg: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 404, RawError: %w", cloudprovider.InstanceNotFound), expectedErrMsg: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 404, RawError: %w", cloudprovider.InstanceNotFound),
}, },
@ -184,7 +184,7 @@ func TestDetachDiskWithVMSS(t *testing.T) {
vmssVMList: []string{"vmss00-vm-000000", "vmss00-vm-000001", "vmss00-vm-000002"}, vmssVMList: []string{"vmss00-vm-000000", "vmss00-vm-000001", "vmss00-vm-000002"},
vmssName: "vmss00", vmssName: "vmss00",
vmssvmName: "vmss00-vm-000000", vmssvmName: "vmss00-vm-000000",
existedDisk: compute.Disk{Name: to.StringPtr("disk-name-err")}, existedDisk: compute.Disk{Name: pointer.String("disk-name-err")},
expectedErr: false, expectedErr: false,
}, },
} }
@ -205,17 +205,17 @@ func TestDetachDiskWithVMSS(t *testing.T) {
for _, vmssvm := range expectedVMSSVMs { for _, vmssvm := range expectedVMSSVMs {
vmssvm.StorageProfile = &compute.StorageProfile{ vmssvm.StorageProfile = &compute.StorageProfile{
OsDisk: &compute.OSDisk{ OsDisk: &compute.OSDisk{
Name: to.StringPtr("osdisk1"), Name: pointer.String("osdisk1"),
ManagedDisk: &compute.ManagedDiskParameters{ ManagedDisk: &compute.ManagedDiskParameters{
ID: to.StringPtr("ManagedID"), ID: pointer.String("ManagedID"),
DiskEncryptionSet: &compute.DiskEncryptionSetParameters{ DiskEncryptionSet: &compute.DiskEncryptionSetParameters{
ID: to.StringPtr("DiskEncryptionSetID"), ID: pointer.String("DiskEncryptionSetID"),
}, },
}, },
}, },
DataDisks: &[]compute.DataDisk{{ DataDisks: &[]compute.DataDisk{{
Lun: to.Int32Ptr(0), Lun: pointer.Int32(0),
Name: to.StringPtr(diskName), Name: pointer.String(diskName),
}}, }},
} }
} }
@ -264,8 +264,8 @@ func TestGetDataDisksWithVMSS(t *testing.T) {
nodeName: "vmss00-vm-000000", nodeName: "vmss00-vm-000000",
expectedDataDisks: []compute.DataDisk{ expectedDataDisks: []compute.DataDisk{
{ {
Lun: to.Int32Ptr(0), Lun: pointer.Int32(0),
Name: to.StringPtr("disk1"), Name: pointer.String("disk1"),
}, },
}, },
expectedErr: false, expectedErr: false,
@ -276,8 +276,8 @@ func TestGetDataDisksWithVMSS(t *testing.T) {
nodeName: "vmss00-vm-000000", nodeName: "vmss00-vm-000000",
expectedDataDisks: []compute.DataDisk{ expectedDataDisks: []compute.DataDisk{
{ {
Lun: to.Int32Ptr(0), Lun: pointer.Int32(0),
Name: to.StringPtr("disk1"), Name: pointer.String("disk1"),
}, },
}, },
expectedErr: false, expectedErr: false,
@ -309,8 +309,8 @@ func TestGetDataDisksWithVMSS(t *testing.T) {
for _, vmssvm := range expectedVMSSVMs { for _, vmssvm := range expectedVMSSVMs {
vmssvm.StorageProfile = &compute.StorageProfile{ vmssvm.StorageProfile = &compute.StorageProfile{
DataDisks: &[]compute.DataDisk{{ DataDisks: &[]compute.DataDisk{{
Lun: to.Int32Ptr(0), Lun: pointer.Int32(0),
Name: to.StringPtr("disk1"), Name: pointer.String("disk1"),
}}, }},
} }
} }

View File

@ -29,7 +29,6 @@ import (
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute"
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network"
"github.com/Azure/go-autorest/autorest/to"
"github.com/golang/mock/gomock" "github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -43,6 +42,7 @@ import (
"k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient" "k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient"
"k8s.io/legacy-cloud-providers/azure/clients/vmssvmclient/mockvmssvmclient" "k8s.io/legacy-cloud-providers/azure/clients/vmssvmclient/mockvmssvmclient"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
) )
// setTestVirtualMachines sets test virtual machine with powerstate. // setTestVirtualMachines sets test virtual machine with powerstate.
@ -58,14 +58,14 @@ func setTestVirtualMachines(c *Cloud, vmList map[string]string, isDataDisksFull
} }
status := []compute.InstanceViewStatus{ status := []compute.InstanceViewStatus{
{ {
Code: to.StringPtr(powerState), Code: pointer.String(powerState),
}, },
{ {
Code: to.StringPtr("ProvisioningState/succeeded"), Code: pointer.String("ProvisioningState/succeeded"),
}, },
} }
vm.VirtualMachineProperties = &compute.VirtualMachineProperties{ vm.VirtualMachineProperties = &compute.VirtualMachineProperties{
ProvisioningState: to.StringPtr(string(compute.ProvisioningStateSucceeded)), ProvisioningState: pointer.String(string(compute.ProvisioningStateSucceeded)),
HardwareProfile: &compute.HardwareProfile{ HardwareProfile: &compute.HardwareProfile{
VMSize: compute.VirtualMachineSizeTypesStandardA0, VMSize: compute.VirtualMachineSizeTypesStandardA0,
}, },
@ -78,13 +78,13 @@ func setTestVirtualMachines(c *Cloud, vmList map[string]string, isDataDisksFull
} }
if !isDataDisksFull { if !isDataDisksFull {
vm.StorageProfile.DataDisks = &[]compute.DataDisk{{ vm.StorageProfile.DataDisks = &[]compute.DataDisk{{
Lun: to.Int32Ptr(0), Lun: pointer.Int32(0),
Name: to.StringPtr("disk1"), Name: pointer.String("disk1"),
}} }}
} else { } else {
dataDisks := make([]compute.DataDisk, maxLUN) dataDisks := make([]compute.DataDisk, maxLUN)
for i := 0; i < maxLUN; i++ { for i := 0; i < maxLUN; i++ {
dataDisks[i] = compute.DataDisk{Lun: to.Int32Ptr(int32(i))} dataDisks[i] = compute.DataDisk{Lun: pointer.Int32(int32(i))}
} }
vm.StorageProfile.DataDisks = &dataDisks vm.StorageProfile.DataDisks = &dataDisks
} }
@ -348,7 +348,7 @@ func TestInstanceShutdownByProviderID(t *testing.T) {
cloud := GetTestCloud(ctrl) cloud := GetTestCloud(ctrl)
expectedVMs := setTestVirtualMachines(cloud, test.vmList, false) expectedVMs := setTestVirtualMachines(cloud, test.vmList, false)
if test.provisioningState != "" { if test.provisioningState != "" {
expectedVMs[0].ProvisioningState = to.StringPtr(test.provisioningState) expectedVMs[0].ProvisioningState = pointer.String(test.provisioningState)
} }
mockVMsClient := cloud.VirtualMachinesClient.(*mockvmclient.MockInterface) mockVMsClient := cloud.VirtualMachinesClient.(*mockvmclient.MockInterface)
for _, vm := range expectedVMs { for _, vm := range expectedVMs {
@ -373,9 +373,9 @@ func TestNodeAddresses(t *testing.T) {
NetworkInterfaces: &[]compute.NetworkInterfaceReference{ NetworkInterfaces: &[]compute.NetworkInterfaceReference{
{ {
NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{ NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{
Primary: to.BoolPtr(true), Primary: pointer.Bool(true),
}, },
ID: to.StringPtr("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic"), ID: pointer.String("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic"),
}, },
}, },
}, },
@ -383,9 +383,9 @@ func TestNodeAddresses(t *testing.T) {
} }
expectedPIP := network.PublicIPAddress{ expectedPIP := network.PublicIPAddress{
ID: to.StringPtr("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/pip1"), ID: pointer.String("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/pip1"),
PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{
IPAddress: to.StringPtr("192.168.1.12"), IPAddress: pointer.String("192.168.1.12"),
}, },
} }
@ -394,7 +394,7 @@ func TestNodeAddresses(t *testing.T) {
IPConfigurations: &[]network.InterfaceIPConfiguration{ IPConfigurations: &[]network.InterfaceIPConfiguration{
{ {
InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{
PrivateIPAddress: to.StringPtr("172.1.0.3"), PrivateIPAddress: pointer.String("172.1.0.3"),
PublicIPAddress: &expectedPIP, PublicIPAddress: &expectedPIP,
}, },
}, },

View File

@ -30,7 +30,6 @@ import (
"strings" "strings"
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network"
"github.com/Azure/go-autorest/autorest/to"
v1 "k8s.io/api/core/v1" v1 "k8s.io/api/core/v1"
utilerrors "k8s.io/apimachinery/pkg/util/errors" utilerrors "k8s.io/apimachinery/pkg/util/errors"
@ -42,6 +41,7 @@ import (
"k8s.io/legacy-cloud-providers/azure/metrics" "k8s.io/legacy-cloud-providers/azure/metrics"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
utilnet "k8s.io/utils/net" utilnet "k8s.io/utils/net"
"k8s.io/utils/pointer"
) )
const ( const (
@ -205,7 +205,7 @@ func (az *Cloud) EnsureLoadBalancer(ctx context.Context, clusterName string, ser
return nil, err return nil, err
} }
updateService := updateServiceLoadBalancerIP(service, to.String(serviceIP)) updateService := updateServiceLoadBalancerIP(service, pointer.StringDeref(serviceIP, ""))
flippedService := flipServiceInternalAnnotation(updateService) flippedService := flipServiceInternalAnnotation(updateService)
if _, err := az.reconcileLoadBalancer(clusterName, flippedService, nil, false /* wantLb */); err != nil { if _, err := az.reconcileLoadBalancer(clusterName, flippedService, nil, false /* wantLb */); err != nil {
klog.Errorf("reconcileLoadBalancer(%s) failed: %#v", serviceName, err) klog.Errorf("reconcileLoadBalancer(%s) failed: %#v", serviceName, err)
@ -214,7 +214,7 @@ func (az *Cloud) EnsureLoadBalancer(ctx context.Context, clusterName string, ser
// lb is not reused here because the ETAG may be changed in above operations, hence reconcilePublicIP() would get lb again from cache. // lb is not reused here because the ETAG may be changed in above operations, hence reconcilePublicIP() would get lb again from cache.
klog.V(2).Infof("EnsureLoadBalancer: reconciling pip") klog.V(2).Infof("EnsureLoadBalancer: reconciling pip")
if _, err := az.reconcilePublicIP(clusterName, updateService, to.String(lb.Name), true /* wantLb */); err != nil { if _, err := az.reconcilePublicIP(clusterName, updateService, pointer.StringDeref(lb.Name, ""), true /* wantLb */); err != nil {
klog.Errorf("reconcilePublicIP(%s) failed: %#v", serviceName, err) klog.Errorf("reconcilePublicIP(%s) failed: %#v", serviceName, err)
return nil, err return nil, err
} }
@ -294,19 +294,19 @@ func (az *Cloud) getLoadBalancerResourceGroup() string {
func (az *Cloud) cleanBackendpoolForPrimarySLB(primarySLB *network.LoadBalancer, service *v1.Service, clusterName string) (*network.LoadBalancer, error) { func (az *Cloud) cleanBackendpoolForPrimarySLB(primarySLB *network.LoadBalancer, service *v1.Service, clusterName string) (*network.LoadBalancer, error) {
lbBackendPoolName := getBackendPoolName(clusterName, service) lbBackendPoolName := getBackendPoolName(clusterName, service)
lbResourceGroup := az.getLoadBalancerResourceGroup() lbResourceGroup := az.getLoadBalancerResourceGroup()
lbBackendPoolID := az.getBackendPoolID(to.String(primarySLB.Name), lbResourceGroup, lbBackendPoolName) lbBackendPoolID := az.getBackendPoolID(pointer.StringDeref(primarySLB.Name, ""), lbResourceGroup, lbBackendPoolName)
newBackendPools := make([]network.BackendAddressPool, 0) newBackendPools := make([]network.BackendAddressPool, 0)
if primarySLB.LoadBalancerPropertiesFormat != nil && primarySLB.BackendAddressPools != nil { if primarySLB.LoadBalancerPropertiesFormat != nil && primarySLB.BackendAddressPools != nil {
newBackendPools = *primarySLB.BackendAddressPools newBackendPools = *primarySLB.BackendAddressPools
} }
vmSetNameToBackendIPConfigurationsToBeDeleted := make(map[string][]network.InterfaceIPConfiguration) vmSetNameToBackendIPConfigurationsToBeDeleted := make(map[string][]network.InterfaceIPConfiguration)
for j, bp := range newBackendPools { for j, bp := range newBackendPools {
if strings.EqualFold(to.String(bp.Name), lbBackendPoolName) { if strings.EqualFold(pointer.StringDeref(bp.Name, ""), lbBackendPoolName) {
klog.V(2).Infof("cleanBackendpoolForPrimarySLB: checking the backend pool %s from standard load balancer %s", to.String(bp.Name), to.String(primarySLB.Name)) klog.V(2).Infof("cleanBackendpoolForPrimarySLB: checking the backend pool %s from standard load balancer %s", pointer.StringDeref(bp.Name, ""), pointer.StringDeref(primarySLB.Name, ""))
if bp.BackendAddressPoolPropertiesFormat != nil && bp.BackendIPConfigurations != nil { if bp.BackendAddressPoolPropertiesFormat != nil && bp.BackendIPConfigurations != nil {
for i := len(*bp.BackendIPConfigurations) - 1; i >= 0; i-- { for i := len(*bp.BackendIPConfigurations) - 1; i >= 0; i-- {
ipConf := (*bp.BackendIPConfigurations)[i] ipConf := (*bp.BackendIPConfigurations)[i]
ipConfigID := to.String(ipConf.ID) ipConfigID := pointer.StringDeref(ipConf.ID, "")
_, vmSetName, err := az.VMSet.GetNodeNameByIPConfigurationID(ipConfigID) _, vmSetName, err := az.VMSet.GetNodeNameByIPConfigurationID(ipConfigID)
if err != nil && !errors.Is(err, cloudprovider.InstanceNotFound) { if err != nil && !errors.Is(err, cloudprovider.InstanceNotFound) {
return nil, err return nil, err
@ -316,7 +316,7 @@ func (az *Cloud) cleanBackendpoolForPrimarySLB(primarySLB *network.LoadBalancer,
klog.V(2).Infof("cleanBackendpoolForPrimarySLB: found unwanted vmSet %s, decouple it from the LB", vmSetName) klog.V(2).Infof("cleanBackendpoolForPrimarySLB: found unwanted vmSet %s, decouple it from the LB", vmSetName)
// construct a backendPool that only contains the IP config of the node to be deleted // construct a backendPool that only contains the IP config of the node to be deleted
interfaceIPConfigToBeDeleted := network.InterfaceIPConfiguration{ interfaceIPConfigToBeDeleted := network.InterfaceIPConfiguration{
ID: to.StringPtr(ipConfigID), ID: pointer.String(ipConfigID),
} }
vmSetNameToBackendIPConfigurationsToBeDeleted[vmSetName] = append(vmSetNameToBackendIPConfigurationsToBeDeleted[vmSetName], interfaceIPConfigToBeDeleted) vmSetNameToBackendIPConfigurationsToBeDeleted[vmSetName] = append(vmSetNameToBackendIPConfigurationsToBeDeleted[vmSetName], interfaceIPConfigToBeDeleted)
*bp.BackendIPConfigurations = append((*bp.BackendIPConfigurations)[:i], (*bp.BackendIPConfigurations)[i+1:]...) *bp.BackendIPConfigurations = append((*bp.BackendIPConfigurations)[:i], (*bp.BackendIPConfigurations)[i+1:]...)
@ -330,7 +330,7 @@ func (az *Cloud) cleanBackendpoolForPrimarySLB(primarySLB *network.LoadBalancer,
for vmSetName, backendIPConfigurationsToBeDeleted := range vmSetNameToBackendIPConfigurationsToBeDeleted { for vmSetName, backendIPConfigurationsToBeDeleted := range vmSetNameToBackendIPConfigurationsToBeDeleted {
backendpoolToBeDeleted := &[]network.BackendAddressPool{ backendpoolToBeDeleted := &[]network.BackendAddressPool{
{ {
ID: to.StringPtr(lbBackendPoolID), ID: pointer.String(lbBackendPoolID),
BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{
BackendIPConfigurations: &backendIPConfigurationsToBeDeleted, BackendIPConfigurations: &backendIPConfigurationsToBeDeleted,
}, },
@ -366,7 +366,7 @@ func (az *Cloud) getServiceLoadBalancer(service *v1.Service, clusterName string,
// check if the service already has a load balancer // check if the service already has a load balancer
for i := range existingLBs { for i := range existingLBs {
existingLB := existingLBs[i] existingLB := existingLBs[i]
if strings.EqualFold(to.String(existingLB.Name), clusterName) && useMultipleSLBs { if strings.EqualFold(pointer.StringDeref(existingLB.Name, ""), clusterName) && useMultipleSLBs {
cleanedLB, err := az.cleanBackendpoolForPrimarySLB(&existingLB, service, clusterName) cleanedLB, err := az.cleanBackendpoolForPrimarySLB(&existingLB, service, clusterName)
if err != nil { if err != nil {
return nil, nil, false, err return nil, nil, false, err
@ -509,10 +509,10 @@ func (az *Cloud) getServiceLoadBalancerStatus(service *v1.Service, lb *network.L
for _, ipConfiguration := range *lb.FrontendIPConfigurations { for _, ipConfiguration := range *lb.FrontendIPConfigurations {
owns, isPrimaryService, err := az.serviceOwnsFrontendIP(ipConfiguration, service) owns, isPrimaryService, err := az.serviceOwnsFrontendIP(ipConfiguration, service)
if err != nil { if err != nil {
return nil, fmt.Errorf("get(%s): lb(%s) - failed to filter frontend IP configs with error: %v", serviceName, to.String(lb.Name), err) return nil, fmt.Errorf("get(%s): lb(%s) - failed to filter frontend IP configs with error: %v", serviceName, pointer.StringDeref(lb.Name, ""), err)
} }
if owns { if owns {
klog.V(2).Infof("get(%s): lb(%s) - found frontend IP config, primary service: %v", serviceName, to.String(lb.Name), isPrimaryService) klog.V(2).Infof("get(%s): lb(%s) - found frontend IP config, primary service: %v", serviceName, pointer.StringDeref(lb.Name, ""), isPrimaryService)
var lbIP *string var lbIP *string
if isInternal { if isInternal {
@ -538,8 +538,8 @@ func (az *Cloud) getServiceLoadBalancerStatus(service *v1.Service, lb *network.L
} }
} }
klog.V(2).Infof("getServiceLoadBalancerStatus gets ingress IP %q from frontendIPConfiguration %q for service %q", to.String(lbIP), to.String(ipConfiguration.Name), serviceName) klog.V(2).Infof("getServiceLoadBalancerStatus gets ingress IP %q from frontendIPConfiguration %q for service %q", pointer.StringDeref(lbIP, ""), pointer.StringDeref(ipConfiguration.Name, ""), serviceName)
return &v1.LoadBalancerStatus{Ingress: []v1.LoadBalancerIngress{{IP: to.String(lbIP)}}}, nil return &v1.LoadBalancerStatus{Ingress: []v1.LoadBalancerIngress{{IP: pointer.StringDeref(lbIP, "")}}}, nil
} }
} }
@ -701,14 +701,14 @@ func (az *Cloud) ensurePublicIPExists(service *v1.Service, pipName string, domai
if shouldPIPExisted { if shouldPIPExisted {
return nil, fmt.Errorf("PublicIP from annotation azure-pip-name=%s for service %s doesn't exist", pipName, serviceName) return nil, fmt.Errorf("PublicIP from annotation azure-pip-name=%s for service %s doesn't exist", pipName, serviceName)
} }
pip.Name = to.StringPtr(pipName) pip.Name = pointer.String(pipName)
pip.Location = to.StringPtr(az.Location) pip.Location = pointer.String(az.Location)
pip.PublicIPAddressPropertiesFormat = &network.PublicIPAddressPropertiesFormat{ pip.PublicIPAddressPropertiesFormat = &network.PublicIPAddressPropertiesFormat{
PublicIPAllocationMethod: network.Static, PublicIPAllocationMethod: network.Static,
IPTags: getServiceIPTagRequestForPublicIP(service).IPTags, IPTags: getServiceIPTagRequestForPublicIP(service).IPTags,
} }
pip.Tags = map[string]*string{ pip.Tags = map[string]*string{
serviceTagKey: to.StringPtr(""), serviceTagKey: pointer.String(""),
clusterNameKey: &clusterName, clusterNameKey: &clusterName,
} }
if _, err = bindServicesToPIP(&pip, []string{serviceName}, false); err != nil { if _, err = bindServicesToPIP(&pip, []string{serviceName}, false); err != nil {
@ -724,7 +724,7 @@ func (az *Cloud) ensurePublicIPExists(service *v1.Service, pipName string, domai
} }
if foundDNSLabelAnnotation { if foundDNSLabelAnnotation {
if existingServiceName, ok := pip.Tags[serviceUsingDNSKey]; ok { if existingServiceName, ok := pip.Tags[serviceUsingDNSKey]; ok {
if !strings.EqualFold(to.String(existingServiceName), serviceName) { if !strings.EqualFold(pointer.StringDeref(existingServiceName, ""), serviceName) {
return nil, fmt.Errorf("ensurePublicIPExists for service(%s): pip(%s) - there is an existing service %s consuming the DNS label on the public IP, so the service cannot set the DNS label annotation with this value", serviceName, pipName, *existingServiceName) return nil, fmt.Errorf("ensurePublicIPExists for service(%s): pip(%s) - there is an existing service %s consuming the DNS label on the public IP, so the service cannot set the DNS label annotation with this value", serviceName, pipName, *existingServiceName)
} }
} }
@ -740,7 +740,7 @@ func (az *Cloud) ensurePublicIPExists(service *v1.Service, pipName string, domai
} }
} else { } else {
existingDNSLabel := pip.PublicIPAddressPropertiesFormat.DNSSettings.DomainNameLabel existingDNSLabel := pip.PublicIPAddressPropertiesFormat.DNSSettings.DomainNameLabel
if !strings.EqualFold(to.String(existingDNSLabel), domainNameLabel) { if !strings.EqualFold(pointer.StringDeref(existingDNSLabel, ""), domainNameLabel) {
return nil, fmt.Errorf("ensurePublicIPExists for service(%s): pip(%s) - there is an existing DNS label %s on the public IP", serviceName, pipName, *existingDNSLabel) return nil, fmt.Errorf("ensurePublicIPExists for service(%s): pip(%s) - there is an existing DNS label %s on the public IP", serviceName, pipName, *existingDNSLabel)
} }
} }
@ -827,8 +827,8 @@ func sortIPTags(ipTags *[]network.IPTag) {
if ipTags != nil { if ipTags != nil {
sort.Slice(*ipTags, func(i, j int) bool { sort.Slice(*ipTags, func(i, j int) bool {
ipTag := *ipTags ipTag := *ipTags
return to.String(ipTag[i].IPTagType) < to.String(ipTag[j].IPTagType) || return pointer.StringDeref(ipTag[i].IPTagType, "") < pointer.StringDeref(ipTag[j].IPTagType, "") ||
to.String(ipTag[i].Tag) < to.String(ipTag[j].Tag) pointer.StringDeref(ipTag[i].Tag, "") < pointer.StringDeref(ipTag[j].Tag, "")
}) })
} }
} }
@ -860,8 +860,8 @@ func convertIPTagMapToSlice(ipTagMap map[string]string) *[]network.IPTag {
outputTags := []network.IPTag{} outputTags := []network.IPTag{}
for k, v := range ipTagMap { for k, v := range ipTagMap {
ipTag := network.IPTag{ ipTag := network.IPTag{
IPTagType: to.StringPtr(k), IPTagType: pointer.String(k),
Tag: to.StringPtr(v), Tag: pointer.String(v),
} }
outputTags = append(outputTags, ipTag) outputTags = append(outputTags, ipTag)
} }
@ -873,7 +873,7 @@ func getDomainNameLabel(pip *network.PublicIPAddress) string {
if pip == nil || pip.PublicIPAddressPropertiesFormat == nil || pip.PublicIPAddressPropertiesFormat.DNSSettings == nil { if pip == nil || pip.PublicIPAddressPropertiesFormat == nil || pip.PublicIPAddressPropertiesFormat.DNSSettings == nil {
return "" return ""
} }
return to.String(pip.PublicIPAddressPropertiesFormat.DNSSettings.DomainNameLabel) return pointer.StringDeref(pip.PublicIPAddressPropertiesFormat.DNSSettings.DomainNameLabel, "")
} }
func getIdleTimeout(s *v1.Service) (*int32, error) { func getIdleTimeout(s *v1.Service) (*int32, error) {
@ -906,10 +906,10 @@ func (az *Cloud) isFrontendIPChanged(clusterName string, config network.Frontend
if err != nil { if err != nil {
return false, err return false, err
} }
if isServiceOwnsFrontendIP && isPrimaryService && !strings.EqualFold(to.String(config.Name), lbFrontendIPConfigName) { if isServiceOwnsFrontendIP && isPrimaryService && !strings.EqualFold(pointer.StringDeref(config.Name, ""), lbFrontendIPConfigName) {
return true, nil return true, nil
} }
if !strings.EqualFold(to.String(config.Name), lbFrontendIPConfigName) { if !strings.EqualFold(pointer.StringDeref(config.Name, ""), lbFrontendIPConfigName) {
return false, nil return false, nil
} }
loadBalancerIP := service.Spec.LoadBalancerIP loadBalancerIP := service.Spec.LoadBalancerIP
@ -925,14 +925,14 @@ func (az *Cloud) isFrontendIPChanged(clusterName string, config network.Frontend
if !existsSubnet { if !existsSubnet {
return false, fmt.Errorf("failed to get subnet") return false, fmt.Errorf("failed to get subnet")
} }
if config.Subnet != nil && !strings.EqualFold(to.String(config.Subnet.Name), to.String(subnet.Name)) { if config.Subnet != nil && !strings.EqualFold(pointer.StringDeref(config.Subnet.Name, ""), pointer.StringDeref(subnet.Name, "")) {
return true, nil return true, nil
} }
} }
if loadBalancerIP == "" { if loadBalancerIP == "" {
return config.PrivateIPAllocationMethod == network.Static, nil return config.PrivateIPAllocationMethod == network.Static, nil
} }
return config.PrivateIPAllocationMethod != network.Static || !strings.EqualFold(loadBalancerIP, to.String(config.PrivateIPAddress)), nil return config.PrivateIPAllocationMethod != network.Static || !strings.EqualFold(loadBalancerIP, pointer.StringDeref(config.PrivateIPAddress, "")), nil
} }
pipName, _, err := az.determinePublicIPName(clusterName, service) pipName, _, err := az.determinePublicIPName(clusterName, service)
if err != nil { if err != nil {
@ -946,7 +946,7 @@ func (az *Cloud) isFrontendIPChanged(clusterName string, config network.Frontend
if !existsPip { if !existsPip {
return true, nil return true, nil
} }
return config.PublicIPAddress != nil && !strings.EqualFold(to.String(pip.ID), to.String(config.PublicIPAddress.ID)), nil return config.PublicIPAddress != nil && !strings.EqualFold(pointer.StringDeref(pip.ID, ""), pointer.StringDeref(config.PublicIPAddress.ID, "")), nil
} }
// isFrontendIPConfigUnsafeToDelete checks if a frontend IP config is safe to be deleted. // isFrontendIPConfigUnsafeToDelete checks if a frontend IP config is safe to be deleted.
@ -1122,7 +1122,7 @@ func (az *Cloud) reconcileLoadBalancer(clusterName string, service *v1.Service,
var backendIPConfigurationsToBeDeleted []network.InterfaceIPConfiguration var backendIPConfigurationsToBeDeleted []network.InterfaceIPConfiguration
if bp.BackendAddressPoolPropertiesFormat != nil && bp.BackendIPConfigurations != nil { if bp.BackendAddressPoolPropertiesFormat != nil && bp.BackendIPConfigurations != nil {
for _, ipConf := range *bp.BackendIPConfigurations { for _, ipConf := range *bp.BackendIPConfigurations {
ipConfID := to.String(ipConf.ID) ipConfID := pointer.StringDeref(ipConf.ID, "")
nodeName, _, err := az.VMSet.GetNodeNameByIPConfigurationID(ipConfID) nodeName, _, err := az.VMSet.GetNodeNameByIPConfigurationID(ipConfID)
if err != nil && !errors.Is(err, cloudprovider.InstanceNotFound) { if err != nil && !errors.Is(err, cloudprovider.InstanceNotFound) {
return nil, err return nil, err
@ -1137,13 +1137,13 @@ func (az *Cloud) reconcileLoadBalancer(clusterName string, service *v1.Service,
if shouldExcludeLoadBalancer { if shouldExcludeLoadBalancer {
klog.V(2).Infof("reconcileLoadBalancer for service (%s)(%t): lb backendpool - found unwanted node %s, decouple it from the LB", serviceName, wantLb, nodeName) klog.V(2).Infof("reconcileLoadBalancer for service (%s)(%t): lb backendpool - found unwanted node %s, decouple it from the LB", serviceName, wantLb, nodeName)
// construct a backendPool that only contains the IP config of the node to be deleted // construct a backendPool that only contains the IP config of the node to be deleted
backendIPConfigurationsToBeDeleted = append(backendIPConfigurationsToBeDeleted, network.InterfaceIPConfiguration{ID: to.StringPtr(ipConfID)}) backendIPConfigurationsToBeDeleted = append(backendIPConfigurationsToBeDeleted, network.InterfaceIPConfiguration{ID: pointer.String(ipConfID)})
} }
} }
if len(backendIPConfigurationsToBeDeleted) > 0 { if len(backendIPConfigurationsToBeDeleted) > 0 {
backendpoolToBeDeleted := &[]network.BackendAddressPool{ backendpoolToBeDeleted := &[]network.BackendAddressPool{
{ {
ID: to.StringPtr(lbBackendPoolID), ID: pointer.String(lbBackendPoolID),
BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{
BackendIPConfigurations: &backendIPConfigurationsToBeDeleted, BackendIPConfigurations: &backendIPConfigurationsToBeDeleted,
}, },
@ -1172,7 +1172,7 @@ func (az *Cloud) reconcileLoadBalancer(clusterName string, service *v1.Service,
} }
newBackendPools = append(newBackendPools, network.BackendAddressPool{ newBackendPools = append(newBackendPools, network.BackendAddressPool{
Name: to.StringPtr(lbBackendPoolName), Name: pointer.String(lbBackendPoolName),
}) })
klog.V(10).Infof("reconcileLoadBalancer for service (%s)(%t): lb backendpool - adding backendpool", serviceName, wantLb) klog.V(10).Infof("reconcileLoadBalancer for service (%s)(%t): lb backendpool - adding backendpool", serviceName, wantLb)
@ -1295,8 +1295,8 @@ func (az *Cloud) reconcileLoadBalancer(clusterName string, service *v1.Service,
newConfigs = append(newConfigs, newConfigs = append(newConfigs,
network.FrontendIPConfiguration{ network.FrontendIPConfiguration{
Name: to.StringPtr(defaultLBFrontendIPConfigName), Name: pointer.String(defaultLBFrontendIPConfigName),
ID: to.StringPtr(fmt.Sprintf(frontendIPConfigIDTemplate, az.SubscriptionID, az.ResourceGroup, *lb.Name, defaultLBFrontendIPConfigName)), ID: pointer.String(fmt.Sprintf(frontendIPConfigIDTemplate, az.SubscriptionID, az.ResourceGroup, *lb.Name, defaultLBFrontendIPConfigName)),
FrontendIPConfigurationPropertiesFormat: fipConfigurationProperties, FrontendIPConfigurationPropertiesFormat: fipConfigurationProperties,
}) })
klog.V(2).Infof("reconcileLoadBalancer for service (%s)(%t): lb frontendconfig(%s) - adding", serviceName, wantLb, defaultLBFrontendIPConfigName) klog.V(2).Infof("reconcileLoadBalancer for service (%s)(%t): lb frontendconfig(%s) - adding", serviceName, wantLb, defaultLBFrontendIPConfigName)
@ -1450,7 +1450,7 @@ func (az *Cloud) reconcileLoadBalancer(clusterName string, service *v1.Service,
foundLB := false foundLB := false
for _, existingLB := range existingLBs { for _, existingLB := range existingLBs {
if strings.EqualFold(lbName, to.String(existingLB.Name)) { if strings.EqualFold(lbName, pointer.StringDeref(existingLB.Name, "")) {
foundLB = true foundLB = true
break break
} }
@ -1627,7 +1627,7 @@ func (az *Cloud) reconcileLoadBalancerRule(
var enableTCPReset *bool var enableTCPReset *bool
if az.useStandardLoadBalancer() { if az.useStandardLoadBalancer() {
enableTCPReset = to.BoolPtr(true) enableTCPReset = pointer.Bool(true)
} }
var expectedProbes []network.Probe var expectedProbes []network.Probe
@ -1662,11 +1662,11 @@ func (az *Cloud) reconcileLoadBalancerRule(
expectedProbes = append(expectedProbes, network.Probe{ expectedProbes = append(expectedProbes, network.Probe{
Name: &lbRuleName, Name: &lbRuleName,
ProbePropertiesFormat: &network.ProbePropertiesFormat{ ProbePropertiesFormat: &network.ProbePropertiesFormat{
RequestPath: to.StringPtr(requestPath), RequestPath: pointer.String(requestPath),
Protocol: network.ProbeProtocol(probeProtocol), Protocol: network.ProbeProtocol(probeProtocol),
Port: to.Int32Ptr(podPresencePort), Port: pointer.Int32(podPresencePort),
IntervalInSeconds: to.Int32Ptr(5), IntervalInSeconds: pointer.Int32(5),
NumberOfProbes: to.Int32Ptr(2), NumberOfProbes: pointer.Int32(2),
}, },
}) })
} else if port.Protocol != v1.ProtocolUDP && port.Protocol != v1.ProtocolSCTP { } else if port.Protocol != v1.ProtocolUDP && port.Protocol != v1.ProtocolSCTP {
@ -1677,9 +1677,9 @@ func (az *Cloud) reconcileLoadBalancerRule(
var actualPath *string var actualPath *string
if !strings.EqualFold(probeProtocol, string(network.ProbeProtocolTCP)) { if !strings.EqualFold(probeProtocol, string(network.ProbeProtocolTCP)) {
if requestPath != "" { if requestPath != "" {
actualPath = to.StringPtr(requestPath) actualPath = pointer.String(requestPath)
} else { } else {
actualPath = to.StringPtr("/healthz") actualPath = pointer.String("/healthz")
} }
} }
expectedProbes = append(expectedProbes, network.Probe{ expectedProbes = append(expectedProbes, network.Probe{
@ -1687,9 +1687,9 @@ func (az *Cloud) reconcileLoadBalancerRule(
ProbePropertiesFormat: &network.ProbePropertiesFormat{ ProbePropertiesFormat: &network.ProbePropertiesFormat{
Protocol: network.ProbeProtocol(probeProtocol), Protocol: network.ProbeProtocol(probeProtocol),
RequestPath: actualPath, RequestPath: actualPath,
Port: to.Int32Ptr(port.NodePort), Port: pointer.Int32(port.NodePort),
IntervalInSeconds: to.Int32Ptr(5), IntervalInSeconds: pointer.Int32(5),
NumberOfProbes: to.Int32Ptr(2), NumberOfProbes: pointer.Int32(2),
}, },
}) })
} }
@ -1708,17 +1708,17 @@ func (az *Cloud) reconcileLoadBalancerRule(
LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{
Protocol: *transportProto, Protocol: *transportProto,
FrontendIPConfiguration: &network.SubResource{ FrontendIPConfiguration: &network.SubResource{
ID: to.StringPtr(lbFrontendIPConfigID), ID: pointer.String(lbFrontendIPConfigID),
}, },
BackendAddressPool: &network.SubResource{ BackendAddressPool: &network.SubResource{
ID: to.StringPtr(lbBackendPoolID), ID: pointer.String(lbBackendPoolID),
}, },
LoadDistribution: loadDistribution, LoadDistribution: loadDistribution,
FrontendPort: to.Int32Ptr(port.Port), FrontendPort: pointer.Int32(port.Port),
BackendPort: to.Int32Ptr(port.Port), BackendPort: pointer.Int32(port.Port),
DisableOutboundSnat: to.BoolPtr(az.disableLoadBalancerOutboundSNAT()), DisableOutboundSnat: pointer.Bool(az.disableLoadBalancerOutboundSNAT()),
EnableTCPReset: tcpReset, EnableTCPReset: tcpReset,
EnableFloatingIP: to.BoolPtr(true), EnableFloatingIP: pointer.Bool(true),
}, },
} }
@ -1729,8 +1729,8 @@ func (az *Cloud) reconcileLoadBalancerRule(
if requiresInternalLoadBalancer(service) && if requiresInternalLoadBalancer(service) &&
strings.EqualFold(az.LoadBalancerSku, loadBalancerSkuStandard) && strings.EqualFold(az.LoadBalancerSku, loadBalancerSkuStandard) &&
strings.EqualFold(service.Annotations[ServiceAnnotationLoadBalancerEnableHighAvailabilityPorts], "true") { strings.EqualFold(service.Annotations[ServiceAnnotationLoadBalancerEnableHighAvailabilityPorts], "true") {
expectedRule.FrontendPort = to.Int32Ptr(0) expectedRule.FrontendPort = pointer.Int32(0)
expectedRule.BackendPort = to.Int32Ptr(0) expectedRule.BackendPort = pointer.Int32(0)
expectedRule.Protocol = network.TransportProtocolAll expectedRule.Protocol = network.TransportProtocolAll
highAvailabilityPortsEnabled = true highAvailabilityPortsEnabled = true
} }
@ -1739,7 +1739,7 @@ func (az *Cloud) reconcileLoadBalancerRule(
// However, when externalTrafficPolicy is Local, Kubernetes HTTP health check would be used for probing. // However, when externalTrafficPolicy is Local, Kubernetes HTTP health check would be used for probing.
if servicehelpers.NeedsHealthCheck(service) || (port.Protocol != v1.ProtocolUDP && port.Protocol != v1.ProtocolSCTP) { if servicehelpers.NeedsHealthCheck(service) || (port.Protocol != v1.ProtocolUDP && port.Protocol != v1.ProtocolSCTP) {
expectedRule.Probe = &network.SubResource{ expectedRule.Probe = &network.SubResource{
ID: to.StringPtr(az.getLoadBalancerProbeID(lbName, az.getLoadBalancerResourceGroup(), lbRuleName)), ID: pointer.String(az.getLoadBalancerProbeID(lbName, az.getLoadBalancerResourceGroup(), lbRuleName)),
} }
} }
@ -1817,13 +1817,13 @@ func (az *Cloud) reconcileSecurityGroup(clusterName string, service *v1.Service,
ix := i*len(sourceAddressPrefixes) + j ix := i*len(sourceAddressPrefixes) + j
securityRuleName := az.getSecurityRuleName(service, port, sourceAddressPrefixes[j]) securityRuleName := az.getSecurityRuleName(service, port, sourceAddressPrefixes[j])
expectedSecurityRules[ix] = network.SecurityRule{ expectedSecurityRules[ix] = network.SecurityRule{
Name: to.StringPtr(securityRuleName), Name: pointer.String(securityRuleName),
SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{ SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{
Protocol: *securityProto, Protocol: *securityProto,
SourcePortRange: to.StringPtr("*"), SourcePortRange: pointer.String("*"),
DestinationPortRange: to.StringPtr(strconv.Itoa(int(port.Port))), DestinationPortRange: pointer.String(strconv.Itoa(int(port.Port))),
SourceAddressPrefix: to.StringPtr(sourceAddressPrefixes[j]), SourceAddressPrefix: pointer.String(sourceAddressPrefixes[j]),
DestinationAddressPrefix: to.StringPtr(destinationIPAddress), DestinationAddressPrefix: pointer.String(destinationIPAddress),
Access: network.SecurityRuleAccessAllow, Access: network.SecurityRuleAccessAllow,
Direction: network.SecurityRuleDirectionInbound, Direction: network.SecurityRuleDirectionInbound,
}, },
@ -1929,7 +1929,7 @@ func (az *Cloud) reconcileSecurityGroup(clusterName string, service *v1.Service,
return nil, err return nil, err
} }
expectedRule.Priority = to.Int32Ptr(nextAvailablePriority) expectedRule.Priority = pointer.Int32(nextAvailablePriority)
updatedRules = append(updatedRules, expectedRule) updatedRules = append(updatedRules, expectedRule)
dirtySg = true dirtySg = true
} }
@ -1954,7 +1954,7 @@ func (az *Cloud) reconcileSecurityGroup(clusterName string, service *v1.Service,
return nil, err return nil, err
} }
klog.V(10).Infof("CreateOrUpdateSecurityGroup(%q): end", *sg.Name) klog.V(10).Infof("CreateOrUpdateSecurityGroup(%q): end", *sg.Name)
az.nsgCache.Delete(to.String(sg.Name)) az.nsgCache.Delete(pointer.StringDeref(sg.Name, ""))
} }
return &sg, nil return &sg, nil
} }
@ -2000,13 +2000,13 @@ func findIndex(strs []string, s string) (int, bool) {
} }
func allowsConsolidation(rule network.SecurityRule) bool { func allowsConsolidation(rule network.SecurityRule) bool {
return strings.HasPrefix(to.String(rule.Name), "shared") return strings.HasPrefix(pointer.StringDeref(rule.Name, ""), "shared")
} }
func findConsolidationCandidate(rules []network.SecurityRule, rule network.SecurityRule) (int, bool) { func findConsolidationCandidate(rules []network.SecurityRule, rule network.SecurityRule) (int, bool) {
for index, r := range rules { for index, r := range rules {
if allowsConsolidation(r) { if allowsConsolidation(r) {
if strings.EqualFold(to.String(r.Name), to.String(rule.Name)) { if strings.EqualFold(pointer.StringDeref(r.Name, ""), pointer.StringDeref(rule.Name, "")) {
return index, true return index, true
} }
} }
@ -2320,12 +2320,12 @@ func (az *Cloud) safeDeletePublicIP(service *v1.Service, pipResourceGroup string
loadBalancerRuleUpdated := false loadBalancerRuleUpdated := false
// Check whether there are still frontend IP configurations referring to it. // Check whether there are still frontend IP configurations referring to it.
ipConfigurationID := to.String(pip.PublicIPAddressPropertiesFormat.IPConfiguration.ID) ipConfigurationID := pointer.StringDeref(pip.PublicIPAddressPropertiesFormat.IPConfiguration.ID, "")
if ipConfigurationID != "" { if ipConfigurationID != "" {
lbFrontendIPConfigs := *lb.LoadBalancerPropertiesFormat.FrontendIPConfigurations lbFrontendIPConfigs := *lb.LoadBalancerPropertiesFormat.FrontendIPConfigurations
for i := len(lbFrontendIPConfigs) - 1; i >= 0; i-- { for i := len(lbFrontendIPConfigs) - 1; i >= 0; i-- {
config := lbFrontendIPConfigs[i] config := lbFrontendIPConfigs[i]
if strings.EqualFold(ipConfigurationID, to.String(config.ID)) { if strings.EqualFold(ipConfigurationID, pointer.StringDeref(config.ID, "")) {
if config.FrontendIPConfigurationPropertiesFormat != nil && if config.FrontendIPConfigurationPropertiesFormat != nil &&
config.FrontendIPConfigurationPropertiesFormat.LoadBalancingRules != nil { config.FrontendIPConfigurationPropertiesFormat.LoadBalancingRules != nil {
referencedLBRules = *config.FrontendIPConfigurationPropertiesFormat.LoadBalancingRules referencedLBRules = *config.FrontendIPConfigurationPropertiesFormat.LoadBalancingRules
@ -2346,13 +2346,13 @@ func (az *Cloud) safeDeletePublicIP(service *v1.Service, pipResourceGroup string
if len(referencedLBRules) > 0 { if len(referencedLBRules) > 0 {
referencedLBRuleIDs := sets.NewString() referencedLBRuleIDs := sets.NewString()
for _, refer := range referencedLBRules { for _, refer := range referencedLBRules {
referencedLBRuleIDs.Insert(to.String(refer.ID)) referencedLBRuleIDs.Insert(pointer.StringDeref(refer.ID, ""))
} }
if lb.LoadBalancerPropertiesFormat.LoadBalancingRules != nil { if lb.LoadBalancerPropertiesFormat.LoadBalancingRules != nil {
lbRules := *lb.LoadBalancerPropertiesFormat.LoadBalancingRules lbRules := *lb.LoadBalancerPropertiesFormat.LoadBalancingRules
for i := len(lbRules) - 1; i >= 0; i-- { for i := len(lbRules) - 1; i >= 0; i-- {
ruleID := to.String(lbRules[i].ID) ruleID := pointer.StringDeref(lbRules[i].ID, "")
if ruleID != "" && referencedLBRuleIDs.Has(ruleID) { if ruleID != "" && referencedLBRuleIDs.Has(ruleID) {
loadBalancerRuleUpdated = true loadBalancerRuleUpdated = true
lbRules = append(lbRules[:i], lbRules[i+1:]...) lbRules = append(lbRules[:i], lbRules[i+1:]...)
@ -2375,7 +2375,7 @@ func (az *Cloud) safeDeletePublicIP(service *v1.Service, pipResourceGroup string
} }
} }
pipName := to.String(pip.Name) pipName := pointer.StringDeref(pip.Name, "")
klog.V(10).Infof("DeletePublicIP(%s, %q): start", pipResourceGroup, pipName) klog.V(10).Infof("DeletePublicIP(%s, %q): start", pipResourceGroup, pipName)
err := az.DeletePublicIP(service, pipResourceGroup, pipName) err := az.DeletePublicIP(service, pipResourceGroup, pipName)
if err != nil { if err != nil {
@ -2388,7 +2388,7 @@ func (az *Cloud) safeDeletePublicIP(service *v1.Service, pipResourceGroup string
func findProbe(probes []network.Probe, probe network.Probe) bool { func findProbe(probes []network.Probe, probe network.Probe) bool {
for _, existingProbe := range probes { for _, existingProbe := range probes {
if strings.EqualFold(to.String(existingProbe.Name), to.String(probe.Name)) && to.Int32(existingProbe.Port) == to.Int32(probe.Port) { if strings.EqualFold(pointer.StringDeref(existingProbe.Name, ""), pointer.StringDeref(probe.Name, "")) && pointer.Int32Deref(existingProbe.Port, 0) == pointer.Int32Deref(probe.Port, 0) {
return true return true
} }
} }
@ -2397,7 +2397,7 @@ func findProbe(probes []network.Probe, probe network.Probe) bool {
func findRule(rules []network.LoadBalancingRule, rule network.LoadBalancingRule, wantLB bool) bool { func findRule(rules []network.LoadBalancingRule, rule network.LoadBalancingRule, wantLB bool) bool {
for _, existingRule := range rules { for _, existingRule := range rules {
if strings.EqualFold(to.String(existingRule.Name), to.String(rule.Name)) && if strings.EqualFold(pointer.StringDeref(existingRule.Name, ""), pointer.StringDeref(rule.Name, "")) &&
equalLoadBalancingRulePropertiesFormat(existingRule.LoadBalancingRulePropertiesFormat, rule.LoadBalancingRulePropertiesFormat, wantLB) { equalLoadBalancingRulePropertiesFormat(existingRule.LoadBalancingRulePropertiesFormat, rule.LoadBalancingRulePropertiesFormat, wantLB) {
return true return true
} }
@ -2418,7 +2418,7 @@ func equalLoadBalancingRulePropertiesFormat(s *network.LoadBalancingRuleProperti
} }
if reflect.DeepEqual(s.Protocol, network.TransportProtocolTCP) { if reflect.DeepEqual(s.Protocol, network.TransportProtocolTCP) {
properties = properties && reflect.DeepEqual(to.Bool(s.EnableTCPReset), to.Bool(t.EnableTCPReset)) properties = properties && reflect.DeepEqual(pointer.BoolDeref(s.EnableTCPReset, false), pointer.BoolDeref(t.EnableTCPReset, false))
} }
properties = properties && reflect.DeepEqual(s.FrontendIPConfiguration, t.FrontendIPConfiguration) && properties = properties && reflect.DeepEqual(s.FrontendIPConfiguration, t.FrontendIPConfiguration) &&
@ -2427,7 +2427,7 @@ func equalLoadBalancingRulePropertiesFormat(s *network.LoadBalancingRuleProperti
reflect.DeepEqual(s.FrontendPort, t.FrontendPort) && reflect.DeepEqual(s.FrontendPort, t.FrontendPort) &&
reflect.DeepEqual(s.BackendPort, t.BackendPort) && reflect.DeepEqual(s.BackendPort, t.BackendPort) &&
reflect.DeepEqual(s.EnableFloatingIP, t.EnableFloatingIP) && reflect.DeepEqual(s.EnableFloatingIP, t.EnableFloatingIP) &&
reflect.DeepEqual(to.Bool(s.DisableOutboundSnat), to.Bool(t.DisableOutboundSnat)) reflect.DeepEqual(pointer.BoolDeref(s.DisableOutboundSnat, false), pointer.BoolDeref(t.DisableOutboundSnat, false))
if wantLB && s.IdleTimeoutInMinutes != nil && t.IdleTimeoutInMinutes != nil { if wantLB && s.IdleTimeoutInMinutes != nil && t.IdleTimeoutInMinutes != nil {
return properties && reflect.DeepEqual(s.IdleTimeoutInMinutes, t.IdleTimeoutInMinutes) return properties && reflect.DeepEqual(s.IdleTimeoutInMinutes, t.IdleTimeoutInMinutes)
@ -2441,23 +2441,23 @@ func equalLoadBalancingRulePropertiesFormat(s *network.LoadBalancingRuleProperti
// despite different DestinationAddressPrefixes, in order to give it a chance to consolidate the two rules. // despite different DestinationAddressPrefixes, in order to give it a chance to consolidate the two rules.
func findSecurityRule(rules []network.SecurityRule, rule network.SecurityRule) bool { func findSecurityRule(rules []network.SecurityRule, rule network.SecurityRule) bool {
for _, existingRule := range rules { for _, existingRule := range rules {
if !strings.EqualFold(to.String(existingRule.Name), to.String(rule.Name)) { if !strings.EqualFold(pointer.StringDeref(existingRule.Name, ""), pointer.StringDeref(rule.Name, "")) {
continue continue
} }
if !strings.EqualFold(string(existingRule.Protocol), string(rule.Protocol)) { if !strings.EqualFold(string(existingRule.Protocol), string(rule.Protocol)) {
continue continue
} }
if !strings.EqualFold(to.String(existingRule.SourcePortRange), to.String(rule.SourcePortRange)) { if !strings.EqualFold(pointer.StringDeref(existingRule.SourcePortRange, ""), pointer.StringDeref(rule.SourcePortRange, "")) {
continue continue
} }
if !strings.EqualFold(to.String(existingRule.DestinationPortRange), to.String(rule.DestinationPortRange)) { if !strings.EqualFold(pointer.StringDeref(existingRule.DestinationPortRange, ""), pointer.StringDeref(rule.DestinationPortRange, "")) {
continue continue
} }
if !strings.EqualFold(to.String(existingRule.SourceAddressPrefix), to.String(rule.SourceAddressPrefix)) { if !strings.EqualFold(pointer.StringDeref(existingRule.SourceAddressPrefix, ""), pointer.StringDeref(rule.SourceAddressPrefix, "")) {
continue continue
} }
if !allowsConsolidation(existingRule) && !allowsConsolidation(rule) { if !allowsConsolidation(existingRule) && !allowsConsolidation(rule) {
if !strings.EqualFold(to.String(existingRule.DestinationAddressPrefix), to.String(rule.DestinationAddressPrefix)) { if !strings.EqualFold(pointer.StringDeref(existingRule.DestinationAddressPrefix, ""), pointer.StringDeref(rule.DestinationAddressPrefix, "")) {
continue continue
} }
} }
@ -2583,7 +2583,7 @@ func serviceOwnsPublicIP(service *v1.Service, pip *network.PublicIPAddress, clus
return false, false return false, false
} }
if pip.PublicIPAddressPropertiesFormat == nil || to.String(pip.IPAddress) == "" { if pip.PublicIPAddressPropertiesFormat == nil || pointer.StringDeref(pip.IPAddress, "") == "" {
klog.Warningf("serviceOwnsPublicIP: empty pip.IPAddress") klog.Warningf("serviceOwnsPublicIP: empty pip.IPAddress")
return false, false return false, false
} }
@ -2595,8 +2595,8 @@ func serviceOwnsPublicIP(service *v1.Service, pip *network.PublicIPAddress, clus
clusterTag := pip.Tags[clusterNameKey] clusterTag := pip.Tags[clusterNameKey]
// if there is no service tag on the pip, it is user-created pip // if there is no service tag on the pip, it is user-created pip
if to.String(serviceTag) == "" { if pointer.StringDeref(serviceTag, "") == "" {
return strings.EqualFold(to.String(pip.IPAddress), service.Spec.LoadBalancerIP), true return strings.EqualFold(pointer.StringDeref(pip.IPAddress, ""), service.Spec.LoadBalancerIP), true
} }
if serviceTag != nil { if serviceTag != nil {
@ -2615,7 +2615,7 @@ func serviceOwnsPublicIP(service *v1.Service, pip *network.PublicIPAddress, clus
} else { } else {
// if the service is not included in te tags of the system-created pip, check the ip address // if the service is not included in te tags of the system-created pip, check the ip address
// this could happen for secondary services // this could happen for secondary services
return strings.EqualFold(to.String(pip.IPAddress), service.Spec.LoadBalancerIP), false return strings.EqualFold(pointer.StringDeref(pip.IPAddress, ""), service.Spec.LoadBalancerIP), false
} }
} }
} }
@ -2663,7 +2663,7 @@ func bindServicesToPIP(pip *network.PublicIPAddress, incomingServiceNames []stri
} }
if pip.Tags == nil { if pip.Tags == nil {
pip.Tags = map[string]*string{serviceTagKey: to.StringPtr("")} pip.Tags = map[string]*string{serviceTagKey: pointer.String("")}
} }
serviceTagValue := pip.Tags[serviceTagKey] serviceTagValue := pip.Tags[serviceTagKey]
@ -2673,7 +2673,7 @@ func bindServicesToPIP(pip *network.PublicIPAddress, incomingServiceNames []stri
// replace is used when unbinding the service from PIP so addedNew remains false all the time // replace is used when unbinding the service from PIP so addedNew remains false all the time
if replace { if replace {
serviceTagValue = to.StringPtr(strings.Join(incomingServiceNames, ",")) serviceTagValue = pointer.String(strings.Join(incomingServiceNames, ","))
pip.Tags[serviceTagKey] = serviceTagValue pip.Tags[serviceTagKey] = serviceTagValue
return false, nil return false, nil
@ -2687,7 +2687,7 @@ func bindServicesToPIP(pip *network.PublicIPAddress, incomingServiceNames []stri
for _, serviceName := range incomingServiceNames { for _, serviceName := range incomingServiceNames {
if serviceTagValue == nil || *serviceTagValue == "" { if serviceTagValue == nil || *serviceTagValue == "" {
serviceTagValue = to.StringPtr(serviceName) serviceTagValue = pointer.String(serviceName)
addedNew = true addedNew = true
} else { } else {
// detect duplicates // detect duplicates
@ -2729,7 +2729,7 @@ func unbindServiceFromPIP(pip *network.PublicIPAddress, serviceName string) erro
if existingServiceName, ok := pip.Tags[serviceUsingDNSKey]; ok { if existingServiceName, ok := pip.Tags[serviceUsingDNSKey]; ok {
if strings.EqualFold(*existingServiceName, serviceName) { if strings.EqualFold(*existingServiceName, serviceName) {
pip.Tags[serviceUsingDNSKey] = to.StringPtr("") pip.Tags[serviceUsingDNSKey] = pointer.String("")
} }
} }

View File

@ -28,7 +28,6 @@ import (
"strings" "strings"
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute"
"github.com/Azure/go-autorest/autorest/to"
v1 "k8s.io/api/core/v1" v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource" "k8s.io/apimachinery/pkg/api/resource"
@ -36,6 +35,7 @@ import (
cloudvolume "k8s.io/cloud-provider/volume" cloudvolume "k8s.io/cloud-provider/volume"
volumehelpers "k8s.io/cloud-provider/volume/helpers" volumehelpers "k8s.io/cloud-provider/volume/helpers"
"k8s.io/klog/v2" "k8s.io/klog/v2"
"k8s.io/utils/pointer"
) )
const ( const (
@ -128,7 +128,7 @@ func (c *ManagedDiskController) CreateManagedDisk(options *ManagedDiskOptions) (
} }
diskIOPSReadWrite = int64(v) diskIOPSReadWrite = int64(v)
} }
diskProperties.DiskIOPSReadWrite = to.Int64Ptr(diskIOPSReadWrite) diskProperties.DiskIOPSReadWrite = pointer.Int64(diskIOPSReadWrite)
diskMBpsReadWrite := int64(defaultDiskMBpsReadWrite) diskMBpsReadWrite := int64(defaultDiskMBpsReadWrite)
if options.DiskMBpsReadWrite != "" { if options.DiskMBpsReadWrite != "" {
@ -138,7 +138,7 @@ func (c *ManagedDiskController) CreateManagedDisk(options *ManagedDiskOptions) (
} }
diskMBpsReadWrite = int64(v) diskMBpsReadWrite = int64(v)
} }
diskProperties.DiskMBpsReadWrite = to.Int64Ptr(diskMBpsReadWrite) diskProperties.DiskMBpsReadWrite = pointer.Int64(diskMBpsReadWrite)
} else { } else {
if options.DiskIOPSReadWrite != "" { if options.DiskIOPSReadWrite != "" {
return "", fmt.Errorf("AzureDisk - DiskIOPSReadWrite parameter is only applicable in UltraSSD_LRS disk type") return "", fmt.Errorf("AzureDisk - DiskIOPSReadWrite parameter is only applicable in UltraSSD_LRS disk type")
@ -308,7 +308,7 @@ func (c *ManagedDiskController) ResizeDisk(diskURI string, oldSize resource.Quan
} }
if result.DiskProperties.DiskState != compute.Unattached { if result.DiskProperties.DiskState != compute.Unattached {
return oldSize, fmt.Errorf("azureDisk - disk resize is only supported on Unattached disk, current disk state: %s, already attached to %s", result.DiskProperties.DiskState, to.String(result.ManagedBy)) return oldSize, fmt.Errorf("azureDisk - disk resize is only supported on Unattached disk, current disk state: %s, already attached to %s", result.DiskProperties.DiskState, pointer.StringDeref(result.ManagedBy, ""))
} }
diskParameter := compute.DiskUpdate{ diskParameter := compute.DiskUpdate{

View File

@ -26,7 +26,6 @@ import (
"testing" "testing"
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute"
"github.com/Azure/go-autorest/autorest/to"
"github.com/golang/mock/gomock" "github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -35,6 +34,7 @@ import (
cloudvolume "k8s.io/cloud-provider/volume" cloudvolume "k8s.io/cloud-provider/volume"
"k8s.io/legacy-cloud-providers/azure/clients/diskclient/mockdiskclient" "k8s.io/legacy-cloud-providers/azure/clients/diskclient/mockdiskclient"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
) )
func TestCreateManagedDisk(t *testing.T) { func TestCreateManagedDisk(t *testing.T) {
@ -45,7 +45,7 @@ func TestCreateManagedDisk(t *testing.T) {
goodDiskEncryptionSetID := fmt.Sprintf("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Compute/diskEncryptionSets/%s", "diskEncryptionSet-name") goodDiskEncryptionSetID := fmt.Sprintf("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Compute/diskEncryptionSets/%s", "diskEncryptionSet-name")
badDiskEncryptionSetID := fmt.Sprintf("badDiskEncryptionSetID") badDiskEncryptionSetID := fmt.Sprintf("badDiskEncryptionSetID")
testTags := make(map[string]*string) testTags := make(map[string]*string)
testTags[WriteAcceleratorEnabled] = to.StringPtr("true") testTags[WriteAcceleratorEnabled] = pointer.String("true")
testCases := []struct { testCases := []struct {
desc string desc string
diskID string diskID string
@ -68,7 +68,7 @@ func TestCreateManagedDisk(t *testing.T) {
diskMBPSReadWrite: "100", diskMBPSReadWrite: "100",
diskEncryptionSetID: goodDiskEncryptionSetID, diskEncryptionSetID: goodDiskEncryptionSetID,
expectedDiskID: "diskid1", expectedDiskID: "diskid1",
existedDisk: compute.Disk{ID: to.StringPtr("diskid1"), Name: to.StringPtr("disk1"), DiskProperties: &compute.DiskProperties{Encryption: &compute.Encryption{DiskEncryptionSetID: &goodDiskEncryptionSetID, Type: compute.EncryptionAtRestWithCustomerKey}, ProvisioningState: to.StringPtr("Succeeded")}, Tags: testTags}, existedDisk: compute.Disk{ID: pointer.String("diskid1"), Name: pointer.String("disk1"), DiskProperties: &compute.DiskProperties{Encryption: &compute.Encryption{DiskEncryptionSetID: &goodDiskEncryptionSetID, Type: compute.EncryptionAtRestWithCustomerKey}, ProvisioningState: pointer.String("Succeeded")}, Tags: testTags},
expectedErr: false, expectedErr: false,
}, },
{ {
@ -80,7 +80,7 @@ func TestCreateManagedDisk(t *testing.T) {
diskMBPSReadWrite: "", diskMBPSReadWrite: "",
diskEncryptionSetID: goodDiskEncryptionSetID, diskEncryptionSetID: goodDiskEncryptionSetID,
expectedDiskID: "diskid1", expectedDiskID: "diskid1",
existedDisk: compute.Disk{ID: to.StringPtr("diskid1"), Name: to.StringPtr("disk1"), DiskProperties: &compute.DiskProperties{Encryption: &compute.Encryption{DiskEncryptionSetID: &goodDiskEncryptionSetID, Type: compute.EncryptionAtRestWithCustomerKey}, ProvisioningState: to.StringPtr("Succeeded")}, Tags: testTags}, existedDisk: compute.Disk{ID: pointer.String("diskid1"), Name: pointer.String("disk1"), DiskProperties: &compute.DiskProperties{Encryption: &compute.Encryption{DiskEncryptionSetID: &goodDiskEncryptionSetID, Type: compute.EncryptionAtRestWithCustomerKey}, ProvisioningState: pointer.String("Succeeded")}, Tags: testTags},
expectedErr: false, expectedErr: false,
}, },
{ {
@ -92,7 +92,7 @@ func TestCreateManagedDisk(t *testing.T) {
diskMBPSReadWrite: "100", diskMBPSReadWrite: "100",
diskEncryptionSetID: goodDiskEncryptionSetID, diskEncryptionSetID: goodDiskEncryptionSetID,
expectedDiskID: "", expectedDiskID: "",
existedDisk: compute.Disk{ID: to.StringPtr("diskid1"), Name: to.StringPtr("disk1"), DiskProperties: &compute.DiskProperties{Encryption: &compute.Encryption{DiskEncryptionSetID: &goodDiskEncryptionSetID, Type: compute.EncryptionAtRestWithCustomerKey}, ProvisioningState: to.StringPtr("Succeeded")}, Tags: testTags}, existedDisk: compute.Disk{ID: pointer.String("diskid1"), Name: pointer.String("disk1"), DiskProperties: &compute.DiskProperties{Encryption: &compute.Encryption{DiskEncryptionSetID: &goodDiskEncryptionSetID, Type: compute.EncryptionAtRestWithCustomerKey}, ProvisioningState: pointer.String("Succeeded")}, Tags: testTags},
expectedErr: true, expectedErr: true,
expectedErrMsg: fmt.Errorf("AzureDisk - failed to parse DiskIOPSReadWrite: strconv.Atoi: parsing \"invalid\": invalid syntax"), expectedErrMsg: fmt.Errorf("AzureDisk - failed to parse DiskIOPSReadWrite: strconv.Atoi: parsing \"invalid\": invalid syntax"),
}, },
@ -105,7 +105,7 @@ func TestCreateManagedDisk(t *testing.T) {
diskMBPSReadWrite: "invalid", diskMBPSReadWrite: "invalid",
diskEncryptionSetID: goodDiskEncryptionSetID, diskEncryptionSetID: goodDiskEncryptionSetID,
expectedDiskID: "", expectedDiskID: "",
existedDisk: compute.Disk{ID: to.StringPtr("diskid1"), Name: to.StringPtr("disk1"), DiskProperties: &compute.DiskProperties{Encryption: &compute.Encryption{DiskEncryptionSetID: &goodDiskEncryptionSetID, Type: compute.EncryptionAtRestWithCustomerKey}, ProvisioningState: to.StringPtr("Succeeded")}, Tags: testTags}, existedDisk: compute.Disk{ID: pointer.String("diskid1"), Name: pointer.String("disk1"), DiskProperties: &compute.DiskProperties{Encryption: &compute.Encryption{DiskEncryptionSetID: &goodDiskEncryptionSetID, Type: compute.EncryptionAtRestWithCustomerKey}, ProvisioningState: pointer.String("Succeeded")}, Tags: testTags},
expectedErr: true, expectedErr: true,
expectedErrMsg: fmt.Errorf("AzureDisk - failed to parse DiskMBpsReadWrite: strconv.Atoi: parsing \"invalid\": invalid syntax"), expectedErrMsg: fmt.Errorf("AzureDisk - failed to parse DiskMBpsReadWrite: strconv.Atoi: parsing \"invalid\": invalid syntax"),
}, },
@ -118,7 +118,7 @@ func TestCreateManagedDisk(t *testing.T) {
diskMBPSReadWrite: "100", diskMBPSReadWrite: "100",
diskEncryptionSetID: badDiskEncryptionSetID, diskEncryptionSetID: badDiskEncryptionSetID,
expectedDiskID: "", expectedDiskID: "",
existedDisk: compute.Disk{ID: to.StringPtr("diskid1"), Name: to.StringPtr("disk1"), DiskProperties: &compute.DiskProperties{Encryption: &compute.Encryption{DiskEncryptionSetID: &goodDiskEncryptionSetID, Type: compute.EncryptionAtRestWithCustomerKey}, ProvisioningState: to.StringPtr("Succeeded")}, Tags: testTags}, existedDisk: compute.Disk{ID: pointer.String("diskid1"), Name: pointer.String("disk1"), DiskProperties: &compute.DiskProperties{Encryption: &compute.Encryption{DiskEncryptionSetID: &goodDiskEncryptionSetID, Type: compute.EncryptionAtRestWithCustomerKey}, ProvisioningState: pointer.String("Succeeded")}, Tags: testTags},
expectedErr: true, expectedErr: true,
expectedErrMsg: fmt.Errorf("AzureDisk - format of DiskEncryptionSetID(%s) is incorrect, correct format: %s", badDiskEncryptionSetID, diskEncryptionSetIDFormat), expectedErrMsg: fmt.Errorf("AzureDisk - format of DiskEncryptionSetID(%s) is incorrect, correct format: %s", badDiskEncryptionSetID, diskEncryptionSetIDFormat),
}, },
@ -131,7 +131,7 @@ func TestCreateManagedDisk(t *testing.T) {
diskMBPSReadWrite: "", diskMBPSReadWrite: "",
diskEncryptionSetID: goodDiskEncryptionSetID, diskEncryptionSetID: goodDiskEncryptionSetID,
expectedDiskID: "", expectedDiskID: "",
existedDisk: compute.Disk{ID: to.StringPtr("diskid1"), Name: to.StringPtr("disk1"), DiskProperties: &compute.DiskProperties{Encryption: &compute.Encryption{DiskEncryptionSetID: &goodDiskEncryptionSetID, Type: compute.EncryptionAtRestWithCustomerKey}, ProvisioningState: to.StringPtr("Succeeded")}, Tags: testTags}, existedDisk: compute.Disk{ID: pointer.String("diskid1"), Name: pointer.String("disk1"), DiskProperties: &compute.DiskProperties{Encryption: &compute.Encryption{DiskEncryptionSetID: &goodDiskEncryptionSetID, Type: compute.EncryptionAtRestWithCustomerKey}, ProvisioningState: pointer.String("Succeeded")}, Tags: testTags},
expectedErr: true, expectedErr: true,
expectedErrMsg: fmt.Errorf("AzureDisk - DiskIOPSReadWrite parameter is only applicable in UltraSSD_LRS disk type"), expectedErrMsg: fmt.Errorf("AzureDisk - DiskIOPSReadWrite parameter is only applicable in UltraSSD_LRS disk type"),
}, },
@ -144,7 +144,7 @@ func TestCreateManagedDisk(t *testing.T) {
diskMBPSReadWrite: "100", diskMBPSReadWrite: "100",
diskEncryptionSetID: goodDiskEncryptionSetID, diskEncryptionSetID: goodDiskEncryptionSetID,
expectedDiskID: "", expectedDiskID: "",
existedDisk: compute.Disk{ID: to.StringPtr("diskid1"), Name: to.StringPtr("disk1"), DiskProperties: &compute.DiskProperties{Encryption: &compute.Encryption{DiskEncryptionSetID: &goodDiskEncryptionSetID, Type: compute.EncryptionAtRestWithCustomerKey}, ProvisioningState: to.StringPtr("Succeeded")}, Tags: testTags}, existedDisk: compute.Disk{ID: pointer.String("diskid1"), Name: pointer.String("disk1"), DiskProperties: &compute.DiskProperties{Encryption: &compute.Encryption{DiskEncryptionSetID: &goodDiskEncryptionSetID, Type: compute.EncryptionAtRestWithCustomerKey}, ProvisioningState: pointer.String("Succeeded")}, Tags: testTags},
expectedErr: true, expectedErr: true,
expectedErrMsg: fmt.Errorf("AzureDisk - DiskMBpsReadWrite parameter is only applicable in UltraSSD_LRS disk type"), expectedErrMsg: fmt.Errorf("AzureDisk - DiskMBpsReadWrite parameter is only applicable in UltraSSD_LRS disk type"),
}, },
@ -195,20 +195,20 @@ func TestDeleteManagedDisk(t *testing.T) {
desc: "an error shall be returned if delete an attaching disk", desc: "an error shall be returned if delete an attaching disk",
diskName: "disk1", diskName: "disk1",
diskState: "attaching", diskState: "attaching",
existedDisk: compute.Disk{Name: to.StringPtr("disk1")}, existedDisk: compute.Disk{Name: pointer.String("disk1")},
expectedErr: true, expectedErr: true,
expectedErrMsg: fmt.Errorf("failed to delete disk(/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Compute/disks/disk1) since it's in attaching or detaching state"), expectedErrMsg: fmt.Errorf("failed to delete disk(/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Compute/disks/disk1) since it's in attaching or detaching state"),
}, },
{ {
desc: "no error shall be returned if everything is good", desc: "no error shall be returned if everything is good",
diskName: "disk1", diskName: "disk1",
existedDisk: compute.Disk{Name: to.StringPtr("disk1")}, existedDisk: compute.Disk{Name: pointer.String("disk1")},
expectedErr: false, expectedErr: false,
}, },
{ {
desc: "an error shall be returned if get disk failed", desc: "an error shall be returned if get disk failed",
diskName: fakeGetDiskFailed, diskName: fakeGetDiskFailed,
existedDisk: compute.Disk{Name: to.StringPtr(fakeGetDiskFailed)}, existedDisk: compute.Disk{Name: pointer.String(fakeGetDiskFailed)},
expectedErr: true, expectedErr: true,
expectedErrMsg: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: %w", fmt.Errorf("Get Disk failed")), expectedErrMsg: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: %w", fmt.Errorf("Get Disk failed")),
}, },
@ -254,7 +254,7 @@ func TestGetDisk(t *testing.T) {
{ {
desc: "no error shall be returned if get a normal disk without DiskProperties", desc: "no error shall be returned if get a normal disk without DiskProperties",
diskName: "disk1", diskName: "disk1",
existedDisk: compute.Disk{Name: to.StringPtr("disk1")}, existedDisk: compute.Disk{Name: pointer.String("disk1")},
expectedErr: false, expectedErr: false,
expectedProvisioningState: "", expectedProvisioningState: "",
expectedDiskID: "", expectedDiskID: "",
@ -262,7 +262,7 @@ func TestGetDisk(t *testing.T) {
{ {
desc: "an error shall be returned if get disk failed", desc: "an error shall be returned if get disk failed",
diskName: fakeGetDiskFailed, diskName: fakeGetDiskFailed,
existedDisk: compute.Disk{Name: to.StringPtr(fakeGetDiskFailed)}, existedDisk: compute.Disk{Name: pointer.String(fakeGetDiskFailed)},
expectedErr: true, expectedErr: true,
expectedErrMsg: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: %w", fmt.Errorf("Get Disk failed")), expectedErrMsg: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: %w", fmt.Errorf("Get Disk failed")),
expectedProvisioningState: "", expectedProvisioningState: "",
@ -312,7 +312,7 @@ func TestResizeDisk(t *testing.T) {
diskName: diskName, diskName: diskName,
oldSize: *resource.NewQuantity(2*(1024*1024*1024), resource.BinarySI), oldSize: *resource.NewQuantity(2*(1024*1024*1024), resource.BinarySI),
newSize: *resource.NewQuantity(3*(1024*1024*1024), resource.BinarySI), newSize: *resource.NewQuantity(3*(1024*1024*1024), resource.BinarySI),
existedDisk: compute.Disk{Name: to.StringPtr("disk1"), DiskProperties: &compute.DiskProperties{DiskSizeGB: &diskSizeGB, DiskState: compute.Unattached}}, existedDisk: compute.Disk{Name: pointer.String("disk1"), DiskProperties: &compute.DiskProperties{DiskSizeGB: &diskSizeGB, DiskState: compute.Unattached}},
expectedQuantity: *resource.NewQuantity(3*(1024*1024*1024), resource.BinarySI), expectedQuantity: *resource.NewQuantity(3*(1024*1024*1024), resource.BinarySI),
expectedErr: false, expectedErr: false,
}, },
@ -321,7 +321,7 @@ func TestResizeDisk(t *testing.T) {
diskName: diskName, diskName: diskName,
oldSize: *resource.NewQuantity(2*(1024*1024*1024), resource.BinarySI), oldSize: *resource.NewQuantity(2*(1024*1024*1024), resource.BinarySI),
newSize: *resource.NewQuantity(3*(1024*1024*1024), resource.BinarySI), newSize: *resource.NewQuantity(3*(1024*1024*1024), resource.BinarySI),
existedDisk: compute.Disk{Name: to.StringPtr("disk1")}, existedDisk: compute.Disk{Name: pointer.String("disk1")},
expectedQuantity: *resource.NewQuantity(2*(1024*1024*1024), resource.BinarySI), expectedQuantity: *resource.NewQuantity(2*(1024*1024*1024), resource.BinarySI),
expectedErr: true, expectedErr: true,
expectedErrMsg: fmt.Errorf("DiskProperties of disk(%s) is nil", diskName), expectedErrMsg: fmt.Errorf("DiskProperties of disk(%s) is nil", diskName),
@ -331,7 +331,7 @@ func TestResizeDisk(t *testing.T) {
diskName: diskName, diskName: diskName,
oldSize: *resource.NewQuantity(1*(1024*1024*1024), resource.BinarySI), oldSize: *resource.NewQuantity(1*(1024*1024*1024), resource.BinarySI),
newSize: *resource.NewQuantity(2*(1024*1024*1024), resource.BinarySI), newSize: *resource.NewQuantity(2*(1024*1024*1024), resource.BinarySI),
existedDisk: compute.Disk{Name: to.StringPtr("disk1"), DiskProperties: &compute.DiskProperties{DiskSizeGB: &diskSizeGB, DiskState: compute.Unattached}}, existedDisk: compute.Disk{Name: pointer.String("disk1"), DiskProperties: &compute.DiskProperties{DiskSizeGB: &diskSizeGB, DiskState: compute.Unattached}},
expectedQuantity: *resource.NewQuantity(2*(1024*1024*1024), resource.BinarySI), expectedQuantity: *resource.NewQuantity(2*(1024*1024*1024), resource.BinarySI),
expectedErr: false, expectedErr: false,
}, },
@ -340,7 +340,7 @@ func TestResizeDisk(t *testing.T) {
diskName: fakeGetDiskFailed, diskName: fakeGetDiskFailed,
oldSize: *resource.NewQuantity(2*(1024*1024*1024), resource.BinarySI), oldSize: *resource.NewQuantity(2*(1024*1024*1024), resource.BinarySI),
newSize: *resource.NewQuantity(3*(1024*1024*1024), resource.BinarySI), newSize: *resource.NewQuantity(3*(1024*1024*1024), resource.BinarySI),
existedDisk: compute.Disk{Name: to.StringPtr(fakeGetDiskFailed), DiskProperties: &compute.DiskProperties{DiskSizeGB: &diskSizeGB, DiskState: compute.Unattached}}, existedDisk: compute.Disk{Name: pointer.String(fakeGetDiskFailed), DiskProperties: &compute.DiskProperties{DiskSizeGB: &diskSizeGB, DiskState: compute.Unattached}},
expectedQuantity: *resource.NewQuantity(2*(1024*1024*1024), resource.BinarySI), expectedQuantity: *resource.NewQuantity(2*(1024*1024*1024), resource.BinarySI),
expectedErr: true, expectedErr: true,
expectedErrMsg: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: %w", fmt.Errorf("Get Disk failed")), expectedErrMsg: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: %w", fmt.Errorf("Get Disk failed")),
@ -350,7 +350,7 @@ func TestResizeDisk(t *testing.T) {
diskName: fakeCreateDiskFailed, diskName: fakeCreateDiskFailed,
oldSize: *resource.NewQuantity(2*(1024*1024*1024), resource.BinarySI), oldSize: *resource.NewQuantity(2*(1024*1024*1024), resource.BinarySI),
newSize: *resource.NewQuantity(3*(1024*1024*1024), resource.BinarySI), newSize: *resource.NewQuantity(3*(1024*1024*1024), resource.BinarySI),
existedDisk: compute.Disk{Name: to.StringPtr(fakeCreateDiskFailed), DiskProperties: &compute.DiskProperties{DiskSizeGB: &diskSizeGB, DiskState: compute.Unattached}}, existedDisk: compute.Disk{Name: pointer.String(fakeCreateDiskFailed), DiskProperties: &compute.DiskProperties{DiskSizeGB: &diskSizeGB, DiskState: compute.Unattached}},
expectedQuantity: *resource.NewQuantity(2*(1024*1024*1024), resource.BinarySI), expectedQuantity: *resource.NewQuantity(2*(1024*1024*1024), resource.BinarySI),
expectedErr: true, expectedErr: true,
expectedErrMsg: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: %w", fmt.Errorf("Create Disk failed")), expectedErrMsg: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: %w", fmt.Errorf("Create Disk failed")),
@ -360,7 +360,7 @@ func TestResizeDisk(t *testing.T) {
diskName: fakeCreateDiskFailed, diskName: fakeCreateDiskFailed,
oldSize: *resource.NewQuantity(2*(1024*1024*1024), resource.BinarySI), oldSize: *resource.NewQuantity(2*(1024*1024*1024), resource.BinarySI),
newSize: *resource.NewQuantity(3*(1024*1024*1024), resource.BinarySI), newSize: *resource.NewQuantity(3*(1024*1024*1024), resource.BinarySI),
existedDisk: compute.Disk{Name: to.StringPtr(fakeCreateDiskFailed), DiskProperties: &compute.DiskProperties{DiskSizeGB: &diskSizeGB, DiskState: compute.Attached}}, existedDisk: compute.Disk{Name: pointer.String(fakeCreateDiskFailed), DiskProperties: &compute.DiskProperties{DiskSizeGB: &diskSizeGB, DiskState: compute.Attached}},
expectedQuantity: *resource.NewQuantity(2*(1024*1024*1024), resource.BinarySI), expectedQuantity: *resource.NewQuantity(2*(1024*1024*1024), resource.BinarySI),
expectedErr: true, expectedErr: true,
expectedErrMsg: fmt.Errorf("azureDisk - disk resize is only supported on Unattached disk, current disk state: Attached, already attached to "), expectedErrMsg: fmt.Errorf("azureDisk - disk resize is only supported on Unattached disk, current disk state: Attached, already attached to "),
@ -426,7 +426,7 @@ func TestGetLabelsForVolume(t *testing.T) {
}, },
}, },
}, },
existedDisk: compute.Disk{Name: to.StringPtr(diskName), DiskProperties: &compute.DiskProperties{DiskSizeGB: &diskSizeGB}, Zones: &[]string{"1"}}, existedDisk: compute.Disk{Name: pointer.String(diskName), DiskProperties: &compute.DiskProperties{DiskSizeGB: &diskSizeGB}, Zones: &[]string{"1"}},
expected: map[string]string{ expected: map[string]string{
v1.LabelTopologyRegion: testCloud0.Location, v1.LabelTopologyRegion: testCloud0.Location,
v1.LabelTopologyZone: testCloud0.makeZone(testCloud0.Location, 1), v1.LabelTopologyZone: testCloud0.makeZone(testCloud0.Location, 1),
@ -446,7 +446,7 @@ func TestGetLabelsForVolume(t *testing.T) {
}, },
}, },
}, },
existedDisk: compute.Disk{Name: to.StringPtr(diskName), DiskProperties: &compute.DiskProperties{DiskSizeGB: &diskSizeGB}, Zones: &[]string{"invalid"}}, existedDisk: compute.Disk{Name: pointer.String(diskName), DiskProperties: &compute.DiskProperties{DiskSizeGB: &diskSizeGB}, Zones: &[]string{"invalid"}},
expectedErr: true, expectedErr: true,
expectedErrMsg: fmt.Errorf("failed to parse zone [invalid] for AzureDisk %v: %v", diskName, "strconv.Atoi: parsing \"invalid\": invalid syntax"), expectedErrMsg: fmt.Errorf("failed to parse zone [invalid] for AzureDisk %v: %v", diskName, "strconv.Atoi: parsing \"invalid\": invalid syntax"),
}, },
@ -463,7 +463,7 @@ func TestGetLabelsForVolume(t *testing.T) {
}, },
}, },
}, },
existedDisk: compute.Disk{Name: to.StringPtr(diskName), DiskProperties: &compute.DiskProperties{DiskSizeGB: &diskSizeGB}}, existedDisk: compute.Disk{Name: pointer.String(diskName), DiskProperties: &compute.DiskProperties{DiskSizeGB: &diskSizeGB}},
expected: map[string]string{ expected: map[string]string{
v1.LabelTopologyRegion: testCloud0.Location, v1.LabelTopologyRegion: testCloud0.Location,
}, },
@ -483,7 +483,7 @@ func TestGetLabelsForVolume(t *testing.T) {
}, },
}, },
}, },
existedDisk: compute.Disk{Name: to.StringPtr(fakeGetDiskFailed), DiskProperties: &compute.DiskProperties{DiskSizeGB: &diskSizeGB}, Zones: &[]string{"1"}}, existedDisk: compute.Disk{Name: pointer.String(fakeGetDiskFailed), DiskProperties: &compute.DiskProperties{DiskSizeGB: &diskSizeGB}, Zones: &[]string{"1"}},
expectedErr: true, expectedErr: true,
expectedErrMsg: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: %w", fmt.Errorf("Get Disk failed")), expectedErrMsg: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: %w", fmt.Errorf("Get Disk failed")),
}, },
@ -500,7 +500,7 @@ func TestGetLabelsForVolume(t *testing.T) {
}, },
}, },
}, },
existedDisk: compute.Disk{Name: to.StringPtr(diskName), DiskProperties: &compute.DiskProperties{DiskSizeGB: &diskSizeGB}, Zones: &[]string{"1"}}, existedDisk: compute.Disk{Name: pointer.String(diskName), DiskProperties: &compute.DiskProperties{DiskSizeGB: &diskSizeGB}, Zones: &[]string{"1"}},
expectedErr: true, expectedErr: true,
expectedErrMsg: fmt.Errorf("invalid disk URI: invalidDiskURI"), expectedErrMsg: fmt.Errorf("invalid disk URI: invalidDiskURI"),
}, },
@ -517,7 +517,7 @@ func TestGetLabelsForVolume(t *testing.T) {
}, },
}, },
}, },
existedDisk: compute.Disk{Name: to.StringPtr(diskName), DiskProperties: &compute.DiskProperties{DiskSizeGB: &diskSizeGB}}, existedDisk: compute.Disk{Name: pointer.String(diskName), DiskProperties: &compute.DiskProperties{DiskSizeGB: &diskSizeGB}},
expected: nil, expected: nil,
expectedErr: false, expectedErr: false,
}, },
@ -529,7 +529,7 @@ func TestGetLabelsForVolume(t *testing.T) {
PersistentVolumeSource: v1.PersistentVolumeSource{}, PersistentVolumeSource: v1.PersistentVolumeSource{},
}, },
}, },
existedDisk: compute.Disk{Name: to.StringPtr(diskName), DiskProperties: &compute.DiskProperties{DiskSizeGB: &diskSizeGB}}, existedDisk: compute.Disk{Name: pointer.String(diskName), DiskProperties: &compute.DiskProperties{DiskSizeGB: &diskSizeGB}},
expected: nil, expected: nil,
expectedErr: false, expectedErr: false,
}, },

View File

@ -27,7 +27,6 @@ import (
"time" "time"
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network"
"github.com/Azure/go-autorest/autorest/to"
"k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/wait" "k8s.io/apimachinery/pkg/util/wait"
@ -36,6 +35,7 @@ import (
azcache "k8s.io/legacy-cloud-providers/azure/cache" azcache "k8s.io/legacy-cloud-providers/azure/cache"
"k8s.io/legacy-cloud-providers/azure/metrics" "k8s.io/legacy-cloud-providers/azure/metrics"
utilnet "k8s.io/utils/net" utilnet "k8s.io/utils/net"
"k8s.io/utils/pointer"
) )
var ( var (
@ -173,13 +173,13 @@ func (d *delayedRouteUpdater) updateRoutes() {
routeMatch := false routeMatch := false
onlyUpdateTags = false onlyUpdateTags = false
for i, existingRoute := range routes { for i, existingRoute := range routes {
if strings.EqualFold(to.String(existingRoute.Name), to.String(rt.route.Name)) { if strings.EqualFold(pointer.StringDeref(existingRoute.Name, ""), pointer.StringDeref(rt.route.Name, "")) {
// delete the name-matched routes here (missing routes would be added later if the operation is add). // delete the name-matched routes here (missing routes would be added later if the operation is add).
routes = append(routes[:i], routes[i+1:]...) routes = append(routes[:i], routes[i+1:]...)
if existingRoute.RoutePropertiesFormat != nil && if existingRoute.RoutePropertiesFormat != nil &&
rt.route.RoutePropertiesFormat != nil && rt.route.RoutePropertiesFormat != nil &&
strings.EqualFold(to.String(existingRoute.AddressPrefix), to.String(rt.route.AddressPrefix)) && strings.EqualFold(pointer.StringDeref(existingRoute.AddressPrefix, ""), pointer.StringDeref(rt.route.AddressPrefix, "")) &&
strings.EqualFold(to.String(existingRoute.NextHopIPAddress), to.String(rt.route.NextHopIPAddress)) { strings.EqualFold(pointer.StringDeref(existingRoute.NextHopIPAddress, ""), pointer.StringDeref(rt.route.NextHopIPAddress, "")) {
routeMatch = true routeMatch = true
} }
if rt.operation == routeOperationDelete { if rt.operation == routeOperationDelete {
@ -216,7 +216,7 @@ func (d *delayedRouteUpdater) updateRoutes() {
// and deletes all dualstack routes when dualstack is not enabled. // and deletes all dualstack routes when dualstack is not enabled.
func (d *delayedRouteUpdater) cleanupOutdatedRoutes(existingRoutes []network.Route) (routes []network.Route, changed bool) { func (d *delayedRouteUpdater) cleanupOutdatedRoutes(existingRoutes []network.Route) (routes []network.Route, changed bool) {
for i := len(existingRoutes) - 1; i >= 0; i-- { for i := len(existingRoutes) - 1; i >= 0; i-- {
existingRouteName := to.String(existingRoutes[i].Name) existingRouteName := pointer.StringDeref(existingRoutes[i].Name, "")
split := strings.Split(existingRouteName, routeNameSeparator) split := strings.Split(existingRouteName, routeNameSeparator)
klog.V(4).Infof("cleanupOutdatedRoutes: checking route %s", existingRouteName) klog.V(4).Infof("cleanupOutdatedRoutes: checking route %s", existingRouteName)
@ -299,7 +299,7 @@ func (az *Cloud) ListRoutes(ctx context.Context, clusterName string) ([]*cloudpr
// ensure the route table is tagged as configured // ensure the route table is tagged as configured
tags, changed := az.ensureRouteTableTagged(&routeTable) tags, changed := az.ensureRouteTableTagged(&routeTable)
if changed { if changed {
klog.V(2).Infof("ListRoutes: updating tags on route table %s", to.String(routeTable.Name)) klog.V(2).Infof("ListRoutes: updating tags on route table %s", pointer.StringDeref(routeTable.Name, ""))
op, err := az.routeUpdater.addUpdateRouteTableTagsOperation(routeTableOperationUpdateTags, tags) op, err := az.routeUpdater.addUpdateRouteTableTagsOperation(routeTableOperationUpdateTags, tags)
if err != nil { if err != nil {
klog.Errorf("ListRoutes: failed to add route table operation with error: %v", err) klog.Errorf("ListRoutes: failed to add route table operation with error: %v", err)
@ -348,8 +348,8 @@ func processRoutes(ipv6DualStackEnabled bool, routeTable network.RouteTable, exi
func (az *Cloud) createRouteTable() error { func (az *Cloud) createRouteTable() error {
routeTable := network.RouteTable{ routeTable := network.RouteTable{
Name: to.StringPtr(az.RouteTableName), Name: pointer.String(az.RouteTableName),
Location: to.StringPtr(az.Location), Location: pointer.String(az.Location),
RouteTablePropertiesFormat: &network.RouteTablePropertiesFormat{}, RouteTablePropertiesFormat: &network.RouteTablePropertiesFormat{},
} }
@ -420,11 +420,11 @@ func (az *Cloud) CreateRoute(ctx context.Context, clusterName string, nameHint s
} }
routeName := mapNodeNameToRouteName(az.ipv6DualStackEnabled, kubeRoute.TargetNode, string(kubeRoute.DestinationCIDR)) routeName := mapNodeNameToRouteName(az.ipv6DualStackEnabled, kubeRoute.TargetNode, string(kubeRoute.DestinationCIDR))
route := network.Route{ route := network.Route{
Name: to.StringPtr(routeName), Name: pointer.String(routeName),
RoutePropertiesFormat: &network.RoutePropertiesFormat{ RoutePropertiesFormat: &network.RoutePropertiesFormat{
AddressPrefix: to.StringPtr(kubeRoute.DestinationCIDR), AddressPrefix: pointer.String(kubeRoute.DestinationCIDR),
NextHopType: network.RouteNextHopTypeVirtualAppliance, NextHopType: network.RouteNextHopTypeVirtualAppliance,
NextHopIPAddress: to.StringPtr(targetIP), NextHopIPAddress: pointer.String(targetIP),
}, },
} }
@ -474,7 +474,7 @@ func (az *Cloud) DeleteRoute(ctx context.Context, clusterName string, kubeRoute
routeName := mapNodeNameToRouteName(az.ipv6DualStackEnabled, kubeRoute.TargetNode, string(kubeRoute.DestinationCIDR)) routeName := mapNodeNameToRouteName(az.ipv6DualStackEnabled, kubeRoute.TargetNode, string(kubeRoute.DestinationCIDR))
klog.V(2).Infof("DeleteRoute: deleting route. clusterName=%q instance=%q cidr=%q routeName=%q", clusterName, kubeRoute.TargetNode, kubeRoute.DestinationCIDR, routeName) klog.V(2).Infof("DeleteRoute: deleting route. clusterName=%q instance=%q cidr=%q routeName=%q", clusterName, kubeRoute.TargetNode, kubeRoute.DestinationCIDR, routeName)
route := network.Route{ route := network.Route{
Name: to.StringPtr(routeName), Name: pointer.String(routeName),
RoutePropertiesFormat: &network.RoutePropertiesFormat{}, RoutePropertiesFormat: &network.RoutePropertiesFormat{},
} }
op, err := az.routeUpdater.addRouteOperation(routeOperationDelete, route) op, err := az.routeUpdater.addRouteOperation(routeOperationDelete, route)
@ -495,7 +495,7 @@ func (az *Cloud) DeleteRoute(ctx context.Context, clusterName string, kubeRoute
routeNameWithoutIPV6Suffix := strings.Split(routeName, routeNameSeparator)[0] routeNameWithoutIPV6Suffix := strings.Split(routeName, routeNameSeparator)[0]
klog.V(2).Infof("DeleteRoute: deleting route. clusterName=%q instance=%q cidr=%q routeName=%q", clusterName, kubeRoute.TargetNode, kubeRoute.DestinationCIDR, routeNameWithoutIPV6Suffix) klog.V(2).Infof("DeleteRoute: deleting route. clusterName=%q instance=%q cidr=%q routeName=%q", clusterName, kubeRoute.TargetNode, kubeRoute.DestinationCIDR, routeNameWithoutIPV6Suffix)
route := network.Route{ route := network.Route{
Name: to.StringPtr(routeNameWithoutIPV6Suffix), Name: pointer.String(routeNameWithoutIPV6Suffix),
RoutePropertiesFormat: &network.RoutePropertiesFormat{}, RoutePropertiesFormat: &network.RoutePropertiesFormat{},
} }
op, err := az.routeUpdater.addRouteOperation(routeOperationDelete, route) op, err := az.routeUpdater.addRouteOperation(routeOperationDelete, route)

View File

@ -28,7 +28,6 @@ import (
"time" "time"
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network"
"github.com/Azure/go-autorest/autorest/to"
"github.com/golang/mock/gomock" "github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -38,6 +37,7 @@ import (
"k8s.io/legacy-cloud-providers/azure/clients/routetableclient/mockroutetableclient" "k8s.io/legacy-cloud-providers/azure/clients/routetableclient/mockroutetableclient"
"k8s.io/legacy-cloud-providers/azure/mockvmsets" "k8s.io/legacy-cloud-providers/azure/mockvmsets"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
) )
func TestDeleteRoute(t *testing.T) { func TestDeleteRoute(t *testing.T) {
@ -138,9 +138,9 @@ func TestCreateRoute(t *testing.T) {
nodePrivateIP := "2.4.6.8" nodePrivateIP := "2.4.6.8"
networkRoute := &[]network.Route{ networkRoute := &[]network.Route{
{ {
Name: to.StringPtr("node"), Name: pointer.String("node"),
RoutePropertiesFormat: &network.RoutePropertiesFormat{ RoutePropertiesFormat: &network.RoutePropertiesFormat{
AddressPrefix: to.StringPtr("1.2.3.4/24"), AddressPrefix: pointer.String("1.2.3.4/24"),
NextHopIPAddress: &nodePrivateIP, NextHopIPAddress: &nodePrivateIP,
NextHopType: network.RouteNextHopTypeVirtualAppliance, NextHopType: network.RouteNextHopTypeVirtualAppliance,
}, },
@ -248,9 +248,9 @@ func TestCreateRoute(t *testing.T) {
routeTableName: "rt9", routeTableName: "rt9",
updatedRoute: &[]network.Route{ updatedRoute: &[]network.Route{
{ {
Name: to.StringPtr("node____123424"), Name: pointer.String("node____123424"),
RoutePropertiesFormat: &network.RoutePropertiesFormat{ RoutePropertiesFormat: &network.RoutePropertiesFormat{
AddressPrefix: to.StringPtr("1.2.3.4/24"), AddressPrefix: pointer.String("1.2.3.4/24"),
NextHopIPAddress: &nodePrivateIP, NextHopIPAddress: &nodePrivateIP,
NextHopType: network.RouteNextHopTypeVirtualAppliance, NextHopType: network.RouteNextHopTypeVirtualAppliance,
}, },
@ -267,14 +267,14 @@ func TestCreateRoute(t *testing.T) {
for _, test := range testCases { for _, test := range testCases {
initialTable := network.RouteTable{ initialTable := network.RouteTable{
Name: to.StringPtr(test.routeTableName), Name: pointer.String(test.routeTableName),
Location: &cloud.Location, Location: &cloud.Location,
RouteTablePropertiesFormat: &network.RouteTablePropertiesFormat{ RouteTablePropertiesFormat: &network.RouteTablePropertiesFormat{
Routes: test.initialRoute, Routes: test.initialRoute,
}, },
} }
updatedTable := network.RouteTable{ updatedTable := network.RouteTable{
Name: to.StringPtr(test.routeTableName), Name: pointer.String(test.routeTableName),
Location: &cloud.Location, Location: &cloud.Location,
RouteTablePropertiesFormat: &network.RouteTablePropertiesFormat{ RouteTablePropertiesFormat: &network.RouteTablePropertiesFormat{
Routes: test.updatedRoute, Routes: test.updatedRoute,
@ -375,9 +375,9 @@ func TestProcessRoutes(t *testing.T) {
RouteTablePropertiesFormat: &network.RouteTablePropertiesFormat{ RouteTablePropertiesFormat: &network.RouteTablePropertiesFormat{
Routes: &[]network.Route{ Routes: &[]network.Route{
{ {
Name: to.StringPtr("name"), Name: pointer.String("name"),
RoutePropertiesFormat: &network.RoutePropertiesFormat{ RoutePropertiesFormat: &network.RoutePropertiesFormat{
AddressPrefix: to.StringPtr("1.2.3.4/16"), AddressPrefix: pointer.String("1.2.3.4/16"),
}, },
}, },
}, },
@ -398,15 +398,15 @@ func TestProcessRoutes(t *testing.T) {
RouteTablePropertiesFormat: &network.RouteTablePropertiesFormat{ RouteTablePropertiesFormat: &network.RouteTablePropertiesFormat{
Routes: &[]network.Route{ Routes: &[]network.Route{
{ {
Name: to.StringPtr("name"), Name: pointer.String("name"),
RoutePropertiesFormat: &network.RoutePropertiesFormat{ RoutePropertiesFormat: &network.RoutePropertiesFormat{
AddressPrefix: to.StringPtr("1.2.3.4/16"), AddressPrefix: pointer.String("1.2.3.4/16"),
}, },
}, },
{ {
Name: to.StringPtr("name2"), Name: pointer.String("name2"),
RoutePropertiesFormat: &network.RoutePropertiesFormat{ RoutePropertiesFormat: &network.RoutePropertiesFormat{
AddressPrefix: to.StringPtr("5.6.7.8/16"), AddressPrefix: pointer.String("5.6.7.8/16"),
}, },
}, },
}, },
@ -557,14 +557,14 @@ func TestListRoutes(t *testing.T) {
name: "ListRoutes should return correct routes", name: "ListRoutes should return correct routes",
routeTableName: "rt1", routeTableName: "rt1",
routeTable: network.RouteTable{ routeTable: network.RouteTable{
Name: to.StringPtr("rt1"), Name: pointer.String("rt1"),
Location: &cloud.Location, Location: &cloud.Location,
RouteTablePropertiesFormat: &network.RouteTablePropertiesFormat{ RouteTablePropertiesFormat: &network.RouteTablePropertiesFormat{
Routes: &[]network.Route{ Routes: &[]network.Route{
{ {
Name: to.StringPtr("node"), Name: pointer.String("node"),
RoutePropertiesFormat: &network.RoutePropertiesFormat{ RoutePropertiesFormat: &network.RoutePropertiesFormat{
AddressPrefix: to.StringPtr("1.2.3.4/24"), AddressPrefix: pointer.String("1.2.3.4/24"),
}, },
}, },
}, },
@ -585,14 +585,14 @@ func TestListRoutes(t *testing.T) {
unmanagedNodeName: "unmanaged-node", unmanagedNodeName: "unmanaged-node",
routeCIDRs: map[string]string{"unmanaged-node": "2.2.3.4/24"}, routeCIDRs: map[string]string{"unmanaged-node": "2.2.3.4/24"},
routeTable: network.RouteTable{ routeTable: network.RouteTable{
Name: to.StringPtr("rt2"), Name: pointer.String("rt2"),
Location: &cloud.Location, Location: &cloud.Location,
RouteTablePropertiesFormat: &network.RouteTablePropertiesFormat{ RouteTablePropertiesFormat: &network.RouteTablePropertiesFormat{
Routes: &[]network.Route{ Routes: &[]network.Route{
{ {
Name: to.StringPtr("node"), Name: pointer.String("node"),
RoutePropertiesFormat: &network.RoutePropertiesFormat{ RoutePropertiesFormat: &network.RoutePropertiesFormat{
AddressPrefix: to.StringPtr("1.2.3.4/24"), AddressPrefix: pointer.String("1.2.3.4/24"),
}, },
}, },
}, },
@ -677,11 +677,11 @@ func TestCleanupOutdatedRoutes(t *testing.T) {
{ {
description: "cleanupOutdatedRoutes should delete outdated non-dualstack routes when dualstack is enabled", description: "cleanupOutdatedRoutes should delete outdated non-dualstack routes when dualstack is enabled",
existingRoutes: []network.Route{ existingRoutes: []network.Route{
{Name: to.StringPtr("aks-node1-vmss000000____xxx")}, {Name: pointer.String("aks-node1-vmss000000____xxx")},
{Name: to.StringPtr("aks-node1-vmss000000")}, {Name: pointer.String("aks-node1-vmss000000")},
}, },
expectedRoutes: []network.Route{ expectedRoutes: []network.Route{
{Name: to.StringPtr("aks-node1-vmss000000____xxx")}, {Name: pointer.String("aks-node1-vmss000000____xxx")},
}, },
existingNodeNames: sets.NewString("aks-node1-vmss000000"), existingNodeNames: sets.NewString("aks-node1-vmss000000"),
enableIPV6DualStack: true, enableIPV6DualStack: true,
@ -690,11 +690,11 @@ func TestCleanupOutdatedRoutes(t *testing.T) {
{ {
description: "cleanupOutdatedRoutes should delete outdated dualstack routes when dualstack is disabled", description: "cleanupOutdatedRoutes should delete outdated dualstack routes when dualstack is disabled",
existingRoutes: []network.Route{ existingRoutes: []network.Route{
{Name: to.StringPtr("aks-node1-vmss000000____xxx")}, {Name: pointer.String("aks-node1-vmss000000____xxx")},
{Name: to.StringPtr("aks-node1-vmss000000")}, {Name: pointer.String("aks-node1-vmss000000")},
}, },
expectedRoutes: []network.Route{ expectedRoutes: []network.Route{
{Name: to.StringPtr("aks-node1-vmss000000")}, {Name: pointer.String("aks-node1-vmss000000")},
}, },
existingNodeNames: sets.NewString("aks-node1-vmss000000"), existingNodeNames: sets.NewString("aks-node1-vmss000000"),
expectedChanged: true, expectedChanged: true,
@ -702,12 +702,12 @@ func TestCleanupOutdatedRoutes(t *testing.T) {
{ {
description: "cleanupOutdatedRoutes should not delete unmanaged routes when dualstack is enabled", description: "cleanupOutdatedRoutes should not delete unmanaged routes when dualstack is enabled",
existingRoutes: []network.Route{ existingRoutes: []network.Route{
{Name: to.StringPtr("aks-node1-vmss000000____xxx")}, {Name: pointer.String("aks-node1-vmss000000____xxx")},
{Name: to.StringPtr("aks-node1-vmss000000")}, {Name: pointer.String("aks-node1-vmss000000")},
}, },
expectedRoutes: []network.Route{ expectedRoutes: []network.Route{
{Name: to.StringPtr("aks-node1-vmss000000____xxx")}, {Name: pointer.String("aks-node1-vmss000000____xxx")},
{Name: to.StringPtr("aks-node1-vmss000000")}, {Name: pointer.String("aks-node1-vmss000000")},
}, },
existingNodeNames: sets.NewString("aks-node1-vmss000001"), existingNodeNames: sets.NewString("aks-node1-vmss000001"),
enableIPV6DualStack: true, enableIPV6DualStack: true,
@ -715,12 +715,12 @@ func TestCleanupOutdatedRoutes(t *testing.T) {
{ {
description: "cleanupOutdatedRoutes should not delete unmanaged routes when dualstack is disabled", description: "cleanupOutdatedRoutes should not delete unmanaged routes when dualstack is disabled",
existingRoutes: []network.Route{ existingRoutes: []network.Route{
{Name: to.StringPtr("aks-node1-vmss000000____xxx")}, {Name: pointer.String("aks-node1-vmss000000____xxx")},
{Name: to.StringPtr("aks-node1-vmss000000")}, {Name: pointer.String("aks-node1-vmss000000")},
}, },
expectedRoutes: []network.Route{ expectedRoutes: []network.Route{
{Name: to.StringPtr("aks-node1-vmss000000____xxx")}, {Name: pointer.String("aks-node1-vmss000000____xxx")},
{Name: to.StringPtr("aks-node1-vmss000000")}, {Name: pointer.String("aks-node1-vmss000000")},
}, },
existingNodeNames: sets.NewString("aks-node1-vmss000001"), existingNodeNames: sets.NewString("aks-node1-vmss000001"),
}, },

View File

@ -31,7 +31,6 @@ import (
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute"
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network"
"github.com/Azure/go-autorest/autorest/to"
v1 "k8s.io/api/core/v1" v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/types"
@ -43,6 +42,7 @@ import (
azcache "k8s.io/legacy-cloud-providers/azure/cache" azcache "k8s.io/legacy-cloud-providers/azure/cache"
"k8s.io/legacy-cloud-providers/azure/metrics" "k8s.io/legacy-cloud-providers/azure/metrics"
utilnet "k8s.io/utils/net" utilnet "k8s.io/utils/net"
"k8s.io/utils/pointer"
) )
const ( const (
@ -216,7 +216,7 @@ func getPrimaryInterfaceID(machine compute.VirtualMachine) (string, error) {
} }
for _, ref := range *machine.NetworkProfile.NetworkInterfaces { for _, ref := range *machine.NetworkProfile.NetworkInterfaces {
if to.Bool(ref.Primary) { if pointer.BoolDeref(ref.Primary, false) {
return *ref.ID, nil return *ref.ID, nil
} }
} }
@ -259,7 +259,7 @@ func getIPConfigByIPFamily(nic network.Interface, IPv6 bool) (*network.Interface
return &ref, nil return &ref, nil
} }
} }
return nil, fmt.Errorf("failed to determine the ipconfig(IPv6=%v). nicname=%q", IPv6, to.String(nic.Name)) return nil, fmt.Errorf("failed to determine the ipconfig(IPv6=%v). nicname=%q", IPv6, pointer.StringDeref(nic.Name, ""))
} }
func isInternalLoadBalancer(lb *network.LoadBalancer) bool { func isInternalLoadBalancer(lb *network.LoadBalancer) bool {
@ -342,7 +342,7 @@ func (az *Cloud) serviceOwnsRule(service *v1.Service, rule string) bool {
func (az *Cloud) serviceOwnsFrontendIP(fip network.FrontendIPConfiguration, service *v1.Service) (bool, bool, error) { func (az *Cloud) serviceOwnsFrontendIP(fip network.FrontendIPConfiguration, service *v1.Service) (bool, bool, error) {
var isPrimaryService bool var isPrimaryService bool
baseName := az.GetLoadBalancerName(context.TODO(), "", service) baseName := az.GetLoadBalancerName(context.TODO(), "", service)
if strings.HasPrefix(to.String(fip.Name), baseName) { if strings.HasPrefix(pointer.StringDeref(fip.Name, ""), baseName) {
klog.V(6).Infof("serviceOwnsFrontendIP: found primary service %s of the "+ klog.V(6).Infof("serviceOwnsFrontendIP: found primary service %s of the "+
"frontend IP config %s", service.Name, *fip.Name) "frontend IP config %s", service.Name, *fip.Name)
isPrimaryService = true isPrimaryService = true
@ -369,7 +369,7 @@ func (az *Cloud) serviceOwnsFrontendIP(fip network.FrontendIPConfiguration, serv
pip.IPAddress != nil && pip.IPAddress != nil &&
fip.FrontendIPConfigurationPropertiesFormat != nil && fip.FrontendIPConfigurationPropertiesFormat != nil &&
fip.FrontendIPConfigurationPropertiesFormat.PublicIPAddress != nil { fip.FrontendIPConfigurationPropertiesFormat.PublicIPAddress != nil {
if strings.EqualFold(to.String(pip.ID), to.String(fip.PublicIPAddress.ID)) { if strings.EqualFold(pointer.StringDeref(pip.ID, ""), pointer.StringDeref(fip.PublicIPAddress.ID, "")) {
klog.V(4).Infof("serviceOwnsFrontendIP: found secondary service %s of the frontend IP config %s", service.Name, *fip.Name) klog.V(4).Infof("serviceOwnsFrontendIP: found secondary service %s of the frontend IP config %s", service.Name, *fip.Name)
return true, isPrimaryService, nil return true, isPrimaryService, nil
@ -491,7 +491,7 @@ func (as *availabilitySet) GetPowerStatusByNodeName(name string) (powerState str
if vm.InstanceView != nil && vm.InstanceView.Statuses != nil { if vm.InstanceView != nil && vm.InstanceView.Statuses != nil {
statuses := *vm.InstanceView.Statuses statuses := *vm.InstanceView.Statuses
for _, status := range statuses { for _, status := range statuses {
state := to.String(status.Code) state := pointer.StringDeref(status.Code, "")
if strings.HasPrefix(state, vmPowerStatePrefix) { if strings.HasPrefix(state, vmPowerStatePrefix) {
return strings.TrimPrefix(state, vmPowerStatePrefix), nil return strings.TrimPrefix(state, vmPowerStatePrefix), nil
} }
@ -514,7 +514,7 @@ func (as *availabilitySet) GetProvisioningStateByNodeName(name string) (provisio
return provisioningState, nil return provisioningState, nil
} }
return to.String(vm.VirtualMachineProperties.ProvisioningState), nil return pointer.StringDeref(vm.VirtualMachineProperties.ProvisioningState, ""), nil
} }
// GetNodeNameByProviderID gets the node name by provider ID. // GetNodeNameByProviderID gets the node name by provider ID.
@ -556,15 +556,15 @@ func (as *availabilitySet) GetZoneByNodeName(name string) (cloudprovider.Zone, e
return cloudprovider.Zone{}, fmt.Errorf("failed to parse zone %q: %v", zones, err) return cloudprovider.Zone{}, fmt.Errorf("failed to parse zone %q: %v", zones, err)
} }
failureDomain = as.makeZone(to.String(vm.Location), zoneID) failureDomain = as.makeZone(pointer.StringDeref(vm.Location, ""), zoneID)
} else { } else {
// Availability zone is not used for the node, falling back to fault domain. // Availability zone is not used for the node, falling back to fault domain.
failureDomain = strconv.Itoa(int(to.Int32(vm.VirtualMachineProperties.InstanceView.PlatformFaultDomain))) failureDomain = strconv.Itoa(int(pointer.Int32Deref(vm.VirtualMachineProperties.InstanceView.PlatformFaultDomain, 0)))
} }
zone := cloudprovider.Zone{ zone := cloudprovider.Zone{
FailureDomain: strings.ToLower(failureDomain), FailureDomain: strings.ToLower(failureDomain),
Region: strings.ToLower(to.String(vm.Location)), Region: strings.ToLower(pointer.StringDeref(vm.Location, "")),
} }
return zone, nil return zone, nil
} }
@ -805,7 +805,7 @@ func (as *availabilitySet) getPrimaryInterfaceWithVMSet(nodeName, vmSetName stri
var availabilitySetID string var availabilitySetID string
if machine.VirtualMachineProperties != nil && machine.AvailabilitySet != nil { if machine.VirtualMachineProperties != nil && machine.AvailabilitySet != nil {
availabilitySetID = to.String(machine.AvailabilitySet.ID) availabilitySetID = pointer.StringDeref(machine.AvailabilitySet.ID, "")
} }
return nic, availabilitySetID, nil return nic, availabilitySetID, nil
} }
@ -882,7 +882,7 @@ func (as *availabilitySet) EnsureHostInPool(service *v1.Service, nodeName types.
newBackendPools = append(newBackendPools, newBackendPools = append(newBackendPools,
network.BackendAddressPool{ network.BackendAddressPool{
ID: to.StringPtr(backendPoolID), ID: pointer.String(backendPoolID),
}) })
primaryIPConfig.LoadBalancerBackendAddressPools = &newBackendPools primaryIPConfig.LoadBalancerBackendAddressPools = &newBackendPools
@ -958,7 +958,7 @@ func (as *availabilitySet) EnsureBackendPoolDeleted(service *v1.Service, backend
ipConfigurationIDs := []string{} ipConfigurationIDs := []string{}
for _, backendPool := range *backendAddressPools { for _, backendPool := range *backendAddressPools {
if strings.EqualFold(to.String(backendPool.ID), backendPoolID) && if strings.EqualFold(pointer.StringDeref(backendPool.ID, ""), backendPoolID) &&
backendPool.BackendAddressPoolPropertiesFormat != nil && backendPool.BackendAddressPoolPropertiesFormat != nil &&
backendPool.BackendIPConfigurations != nil { backendPool.BackendIPConfigurations != nil {
for _, ipConf := range *backendPool.BackendIPConfigurations { for _, ipConf := range *backendPool.BackendIPConfigurations {
@ -1013,7 +1013,7 @@ func (as *availabilitySet) EnsureBackendPoolDeleted(service *v1.Service, backend
if nic.InterfacePropertiesFormat != nil && nic.InterfacePropertiesFormat.IPConfigurations != nil { if nic.InterfacePropertiesFormat != nil && nic.InterfacePropertiesFormat.IPConfigurations != nil {
newIPConfigs := *nic.IPConfigurations newIPConfigs := *nic.IPConfigurations
for j, ipConf := range newIPConfigs { for j, ipConf := range newIPConfigs {
if !to.Bool(ipConf.Primary) { if !pointer.BoolDeref(ipConf.Primary, false) {
continue continue
} }
// found primary ip configuration // found primary ip configuration
@ -1021,7 +1021,7 @@ func (as *availabilitySet) EnsureBackendPoolDeleted(service *v1.Service, backend
newLBAddressPools := *ipConf.LoadBalancerBackendAddressPools newLBAddressPools := *ipConf.LoadBalancerBackendAddressPools
for k := len(newLBAddressPools) - 1; k >= 0; k-- { for k := len(newLBAddressPools) - 1; k >= 0; k-- {
pool := newLBAddressPools[k] pool := newLBAddressPools[k]
if strings.EqualFold(to.String(pool.ID), backendPoolID) { if strings.EqualFold(pointer.StringDeref(pool.ID, ""), backendPoolID) {
newLBAddressPools = append(newLBAddressPools[:k], newLBAddressPools[k+1:]...) newLBAddressPools = append(newLBAddressPools[:k], newLBAddressPools[k+1:]...)
break break
} }
@ -1033,10 +1033,10 @@ func (as *availabilitySet) EnsureBackendPoolDeleted(service *v1.Service, backend
nicUpdaters = append(nicUpdaters, func() error { nicUpdaters = append(nicUpdaters, func() error {
ctx, cancel := getContextWithCancel() ctx, cancel := getContextWithCancel()
defer cancel() defer cancel()
klog.V(2).Infof("EnsureBackendPoolDeleted begins to CreateOrUpdate for NIC(%s, %s) with backendPoolID %s", as.resourceGroup, to.String(nic.Name), backendPoolID) klog.V(2).Infof("EnsureBackendPoolDeleted begins to CreateOrUpdate for NIC(%s, %s) with backendPoolID %s", as.resourceGroup, pointer.StringDeref(nic.Name, ""), backendPoolID)
rerr := as.InterfacesClient.CreateOrUpdate(ctx, as.ResourceGroup, to.String(nic.Name), nic) rerr := as.InterfacesClient.CreateOrUpdate(ctx, as.ResourceGroup, pointer.StringDeref(nic.Name, ""), nic)
if rerr != nil { if rerr != nil {
klog.Errorf("EnsureBackendPoolDeleted CreateOrUpdate for NIC(%s, %s) failed with error %v", as.resourceGroup, to.String(nic.Name), rerr.Error()) klog.Errorf("EnsureBackendPoolDeleted CreateOrUpdate for NIC(%s, %s) failed with error %v", as.resourceGroup, pointer.StringDeref(nic.Name, ""), rerr.Error())
return rerr.Error() return rerr.Error()
} }
return nil return nil
@ -1098,7 +1098,7 @@ func (as *availabilitySet) GetNodeNameByIPConfigurationID(ipConfigurationID stri
} }
vmID := "" vmID := ""
if nic.InterfacePropertiesFormat != nil && nic.VirtualMachine != nil { if nic.InterfacePropertiesFormat != nil && nic.VirtualMachine != nil {
vmID = to.String(nic.VirtualMachine.ID) vmID = pointer.StringDeref(nic.VirtualMachine.ID, "")
} }
if vmID == "" { if vmID == "" {
klog.V(2).Infof("GetNodeNameByIPConfigurationID(%s): empty vmID", ipConfigurationID) klog.V(2).Infof("GetNodeNameByIPConfigurationID(%s): empty vmID", ipConfigurationID)
@ -1118,7 +1118,7 @@ func (as *availabilitySet) GetNodeNameByIPConfigurationID(ipConfigurationID stri
} }
asID := "" asID := ""
if vm.VirtualMachineProperties != nil && vm.AvailabilitySet != nil { if vm.VirtualMachineProperties != nil && vm.AvailabilitySet != nil {
asID = to.String(vm.AvailabilitySet.ID) asID = pointer.StringDeref(vm.AvailabilitySet.ID, "")
} }
if asID == "" { if asID == "" {
return vmName, "", nil return vmName, "", nil

View File

@ -27,7 +27,6 @@ import (
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute"
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network"
"github.com/Azure/go-autorest/autorest/to"
"github.com/golang/mock/gomock" "github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -40,6 +39,7 @@ import (
"k8s.io/legacy-cloud-providers/azure/clients/publicipclient/mockpublicipclient" "k8s.io/legacy-cloud-providers/azure/clients/publicipclient/mockpublicipclient"
"k8s.io/legacy-cloud-providers/azure/clients/vmclient/mockvmclient" "k8s.io/legacy-cloud-providers/azure/clients/vmclient/mockvmclient"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
) )
const ( const (
@ -592,21 +592,21 @@ func TestGetStandardVMPrimaryInterfaceID(t *testing.T) {
{ {
name: "GetPrimaryInterfaceID should get primary NIC ID", name: "GetPrimaryInterfaceID should get primary NIC ID",
vm: compute.VirtualMachine{ vm: compute.VirtualMachine{
Name: to.StringPtr("vm2"), Name: pointer.String("vm2"),
VirtualMachineProperties: &compute.VirtualMachineProperties{ VirtualMachineProperties: &compute.VirtualMachineProperties{
NetworkProfile: &compute.NetworkProfile{ NetworkProfile: &compute.NetworkProfile{
NetworkInterfaces: &[]compute.NetworkInterfaceReference{ NetworkInterfaces: &[]compute.NetworkInterfaceReference{
{ {
NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{ NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{
Primary: to.BoolPtr(true), Primary: pointer.Bool(true),
}, },
ID: to.StringPtr("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic1"), ID: pointer.String("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic1"),
}, },
{ {
NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{ NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{
Primary: to.BoolPtr(false), Primary: pointer.Bool(false),
}, },
ID: to.StringPtr("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic2"), ID: pointer.String("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic2"),
}, },
}, },
}, },
@ -617,21 +617,21 @@ func TestGetStandardVMPrimaryInterfaceID(t *testing.T) {
{ {
name: "GetPrimaryInterfaceID should report error if node don't have primary NIC", name: "GetPrimaryInterfaceID should report error if node don't have primary NIC",
vm: compute.VirtualMachine{ vm: compute.VirtualMachine{
Name: to.StringPtr("vm3"), Name: pointer.String("vm3"),
VirtualMachineProperties: &compute.VirtualMachineProperties{ VirtualMachineProperties: &compute.VirtualMachineProperties{
NetworkProfile: &compute.NetworkProfile{ NetworkProfile: &compute.NetworkProfile{
NetworkInterfaces: &[]compute.NetworkInterfaceReference{ NetworkInterfaces: &[]compute.NetworkInterfaceReference{
{ {
NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{ NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{
Primary: to.BoolPtr(false), Primary: pointer.Bool(false),
}, },
ID: to.StringPtr("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic1"), ID: pointer.String("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic1"),
}, },
{ {
NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{ NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{
Primary: to.BoolPtr(false), Primary: pointer.Bool(false),
}, },
ID: to.StringPtr("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic2"), ID: pointer.String("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic2"),
}, },
}, },
}, },
@ -659,51 +659,51 @@ func TestGetPrimaryIPConfig(t *testing.T) {
{ {
name: "GetPrimaryIPConfig should get the only IP configuration", name: "GetPrimaryIPConfig should get the only IP configuration",
nic: network.Interface{ nic: network.Interface{
Name: to.StringPtr("nic"), Name: pointer.String("nic"),
InterfacePropertiesFormat: &network.InterfacePropertiesFormat{ InterfacePropertiesFormat: &network.InterfacePropertiesFormat{
IPConfigurations: &[]network.InterfaceIPConfiguration{ IPConfigurations: &[]network.InterfaceIPConfiguration{
{ {
Name: to.StringPtr("ipconfig1"), Name: pointer.String("ipconfig1"),
}, },
}, },
}, },
}, },
expectedIPConfig: &network.InterfaceIPConfiguration{ expectedIPConfig: &network.InterfaceIPConfiguration{
Name: to.StringPtr("ipconfig1"), Name: pointer.String("ipconfig1"),
}, },
}, },
{ {
name: "GetPrimaryIPConfig should get the primary IP configuration", name: "GetPrimaryIPConfig should get the primary IP configuration",
nic: network.Interface{ nic: network.Interface{
Name: to.StringPtr("nic"), Name: pointer.String("nic"),
InterfacePropertiesFormat: &network.InterfacePropertiesFormat{ InterfacePropertiesFormat: &network.InterfacePropertiesFormat{
IPConfigurations: &[]network.InterfaceIPConfiguration{ IPConfigurations: &[]network.InterfaceIPConfiguration{
{ {
Name: to.StringPtr("ipconfig1"), Name: pointer.String("ipconfig1"),
InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{
Primary: to.BoolPtr(true), Primary: pointer.Bool(true),
}, },
}, },
{ {
Name: to.StringPtr("ipconfig2"), Name: pointer.String("ipconfig2"),
InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{
Primary: to.BoolPtr(false), Primary: pointer.Bool(false),
}, },
}, },
}, },
}, },
}, },
expectedIPConfig: &network.InterfaceIPConfiguration{ expectedIPConfig: &network.InterfaceIPConfiguration{
Name: to.StringPtr("ipconfig1"), Name: pointer.String("ipconfig1"),
InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{
Primary: to.BoolPtr(true), Primary: pointer.Bool(true),
}, },
}, },
}, },
{ {
name: "GetPrimaryIPConfig should report error if nic don't have IP configuration", name: "GetPrimaryIPConfig should report error if nic don't have IP configuration",
nic: network.Interface{ nic: network.Interface{
Name: to.StringPtr("nic"), Name: pointer.String("nic"),
InterfacePropertiesFormat: &network.InterfacePropertiesFormat{}, InterfacePropertiesFormat: &network.InterfacePropertiesFormat{},
}, },
expectedErrMsg: fmt.Errorf("nic.IPConfigurations for nic (nicname=%q) is nil", "nic"), expectedErrMsg: fmt.Errorf("nic.IPConfigurations for nic (nicname=%q) is nil", "nic"),
@ -711,19 +711,19 @@ func TestGetPrimaryIPConfig(t *testing.T) {
{ {
name: "GetPrimaryIPConfig should report error if node has more than one IP configuration and don't have primary IP configuration", name: "GetPrimaryIPConfig should report error if node has more than one IP configuration and don't have primary IP configuration",
nic: network.Interface{ nic: network.Interface{
Name: to.StringPtr("nic"), Name: pointer.String("nic"),
InterfacePropertiesFormat: &network.InterfacePropertiesFormat{ InterfacePropertiesFormat: &network.InterfacePropertiesFormat{
IPConfigurations: &[]network.InterfaceIPConfiguration{ IPConfigurations: &[]network.InterfaceIPConfiguration{
{ {
Name: to.StringPtr("ipconfig1"), Name: pointer.String("ipconfig1"),
InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{
Primary: to.BoolPtr(false), Primary: pointer.Bool(false),
}, },
}, },
{ {
Name: to.StringPtr("ipconfig2"), Name: pointer.String("ipconfig2"),
InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{
Primary: to.BoolPtr(false), Primary: pointer.Bool(false),
}, },
}, },
}, },
@ -742,21 +742,21 @@ func TestGetPrimaryIPConfig(t *testing.T) {
func TestGetIPConfigByIPFamily(t *testing.T) { func TestGetIPConfigByIPFamily(t *testing.T) {
ipv4IPconfig := network.InterfaceIPConfiguration{ ipv4IPconfig := network.InterfaceIPConfiguration{
Name: to.StringPtr("ipconfig1"), Name: pointer.String("ipconfig1"),
InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{
PrivateIPAddressVersion: network.IPv4, PrivateIPAddressVersion: network.IPv4,
PrivateIPAddress: to.StringPtr("10.10.0.12"), PrivateIPAddress: pointer.String("10.10.0.12"),
}, },
} }
ipv6IPconfig := network.InterfaceIPConfiguration{ ipv6IPconfig := network.InterfaceIPConfiguration{
Name: to.StringPtr("ipconfig2"), Name: pointer.String("ipconfig2"),
InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{
PrivateIPAddressVersion: network.IPv6, PrivateIPAddressVersion: network.IPv6,
PrivateIPAddress: to.StringPtr("1111:11111:00:00:1111:1111:000:111"), PrivateIPAddress: pointer.String("1111:11111:00:00:1111:1111:000:111"),
}, },
} }
testNic := network.Interface{ testNic := network.Interface{
Name: to.StringPtr("nic"), Name: pointer.String("nic"),
InterfacePropertiesFormat: &network.InterfacePropertiesFormat{ InterfacePropertiesFormat: &network.InterfacePropertiesFormat{
IPConfigurations: &[]network.InterfaceIPConfiguration{ipv4IPconfig, ipv6IPconfig}, IPConfigurations: &[]network.InterfaceIPConfiguration{ipv4IPconfig, ipv6IPconfig},
}, },
@ -782,7 +782,7 @@ func TestGetIPConfigByIPFamily(t *testing.T) {
{ {
name: "GetIPConfigByIPFamily should report error if nic don't have IP configuration", name: "GetIPConfigByIPFamily should report error if nic don't have IP configuration",
nic: network.Interface{ nic: network.Interface{
Name: to.StringPtr("nic"), Name: pointer.String("nic"),
InterfacePropertiesFormat: &network.InterfacePropertiesFormat{}, InterfacePropertiesFormat: &network.InterfacePropertiesFormat{},
}, },
expectedErrMsg: fmt.Errorf("nic.IPConfigurations for nic (nicname=%q) is nil", "nic"), expectedErrMsg: fmt.Errorf("nic.IPConfigurations for nic (nicname=%q) is nil", "nic"),
@ -790,7 +790,7 @@ func TestGetIPConfigByIPFamily(t *testing.T) {
{ {
name: "GetIPConfigByIPFamily should report error if nic don't have IPv6 configuration when IPv6 is true", name: "GetIPConfigByIPFamily should report error if nic don't have IPv6 configuration when IPv6 is true",
nic: network.Interface{ nic: network.Interface{
Name: to.StringPtr("nic"), Name: pointer.String("nic"),
InterfacePropertiesFormat: &network.InterfacePropertiesFormat{ InterfacePropertiesFormat: &network.InterfacePropertiesFormat{
IPConfigurations: &[]network.InterfaceIPConfiguration{ipv4IPconfig}, IPConfigurations: &[]network.InterfaceIPConfiguration{ipv4IPconfig},
}, },
@ -801,11 +801,11 @@ func TestGetIPConfigByIPFamily(t *testing.T) {
{ {
name: "GetIPConfigByIPFamily should report error if nic don't have PrivateIPAddress", name: "GetIPConfigByIPFamily should report error if nic don't have PrivateIPAddress",
nic: network.Interface{ nic: network.Interface{
Name: to.StringPtr("nic"), Name: pointer.String("nic"),
InterfacePropertiesFormat: &network.InterfacePropertiesFormat{ InterfacePropertiesFormat: &network.InterfacePropertiesFormat{
IPConfigurations: &[]network.InterfaceIPConfiguration{ IPConfigurations: &[]network.InterfaceIPConfiguration{
{ {
Name: to.StringPtr("ipconfig1"), Name: pointer.String("ipconfig1"),
InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{
PrivateIPAddressVersion: network.IPv4, PrivateIPAddressVersion: network.IPv4,
}, },
@ -856,8 +856,8 @@ func TestGetStandardInstanceIDByNodeName(t *testing.T) {
cloud := GetTestCloud(ctrl) cloud := GetTestCloud(ctrl)
expectedVM := compute.VirtualMachine{ expectedVM := compute.VirtualMachine{
Name: to.StringPtr("vm1"), Name: pointer.String("vm1"),
ID: to.StringPtr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/vm1"), ID: pointer.String("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/vm1"),
} }
invalidResouceID := "/subscriptions/subscription/resourceGroups/rg/Microsoft.Compute/virtualMachines/vm4" invalidResouceID := "/subscriptions/subscription/resourceGroups/rg/Microsoft.Compute/virtualMachines/vm4"
testcases := []struct { testcases := []struct {
@ -896,8 +896,8 @@ func TestGetStandardInstanceIDByNodeName(t *testing.T) {
RawError: fmt.Errorf("VMGet error"), RawError: fmt.Errorf("VMGet error"),
}).AnyTimes() }).AnyTimes()
mockVMClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, "vm4", gomock.Any()).Return(compute.VirtualMachine{ mockVMClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, "vm4", gomock.Any()).Return(compute.VirtualMachine{
Name: to.StringPtr("vm4"), Name: pointer.String("vm4"),
ID: to.StringPtr(invalidResouceID), ID: pointer.String(invalidResouceID),
}, nil).AnyTimes() }, nil).AnyTimes()
instanceID, err := cloud.VMSet.GetInstanceIDByNodeName(test.nodeName) instanceID, err := cloud.VMSet.GetInstanceIDByNodeName(test.nodeName)
@ -933,12 +933,12 @@ func TestGetStandardVMPowerStatusByNodeName(t *testing.T) {
name: "GetPowerStatusByNodeName should get power status as expected", name: "GetPowerStatusByNodeName should get power status as expected",
nodeName: "vm2", nodeName: "vm2",
vm: compute.VirtualMachine{ vm: compute.VirtualMachine{
Name: to.StringPtr("vm2"), Name: pointer.String("vm2"),
VirtualMachineProperties: &compute.VirtualMachineProperties{ VirtualMachineProperties: &compute.VirtualMachineProperties{
InstanceView: &compute.VirtualMachineInstanceView{ InstanceView: &compute.VirtualMachineInstanceView{
Statuses: &[]compute.InstanceViewStatus{ Statuses: &[]compute.InstanceViewStatus{
{ {
Code: to.StringPtr("PowerState/Running"), Code: pointer.String("PowerState/Running"),
}, },
}, },
}, },
@ -950,7 +950,7 @@ func TestGetStandardVMPowerStatusByNodeName(t *testing.T) {
name: "GetPowerStatusByNodeName should get vmPowerStateStopped if vm.InstanceView is nil", name: "GetPowerStatusByNodeName should get vmPowerStateStopped if vm.InstanceView is nil",
nodeName: "vm3", nodeName: "vm3",
vm: compute.VirtualMachine{ vm: compute.VirtualMachine{
Name: to.StringPtr("vm3"), Name: pointer.String("vm3"),
VirtualMachineProperties: &compute.VirtualMachineProperties{}, VirtualMachineProperties: &compute.VirtualMachineProperties{},
}, },
expectedStatus: vmPowerStateStopped, expectedStatus: vmPowerStateStopped,
@ -959,7 +959,7 @@ func TestGetStandardVMPowerStatusByNodeName(t *testing.T) {
name: "GetPowerStatusByNodeName should get vmPowerStateStopped if vm.InstanceView.statuses is nil", name: "GetPowerStatusByNodeName should get vmPowerStateStopped if vm.InstanceView.statuses is nil",
nodeName: "vm4", nodeName: "vm4",
vm: compute.VirtualMachine{ vm: compute.VirtualMachine{
Name: to.StringPtr("vm4"), Name: pointer.String("vm4"),
VirtualMachineProperties: &compute.VirtualMachineProperties{ VirtualMachineProperties: &compute.VirtualMachineProperties{
InstanceView: &compute.VirtualMachineInstanceView{}, InstanceView: &compute.VirtualMachineInstanceView{},
}, },
@ -1004,13 +1004,13 @@ func TestGetStandardVMProvisioningStateByNodeName(t *testing.T) {
name: "GetProvisioningStateByNodeName should return Succeeded for running VM", name: "GetProvisioningStateByNodeName should return Succeeded for running VM",
nodeName: "vm2", nodeName: "vm2",
vm: compute.VirtualMachine{ vm: compute.VirtualMachine{
Name: to.StringPtr("vm2"), Name: pointer.String("vm2"),
VirtualMachineProperties: &compute.VirtualMachineProperties{ VirtualMachineProperties: &compute.VirtualMachineProperties{
ProvisioningState: to.StringPtr("Succeeded"), ProvisioningState: pointer.String("Succeeded"),
InstanceView: &compute.VirtualMachineInstanceView{ InstanceView: &compute.VirtualMachineInstanceView{
Statuses: &[]compute.InstanceViewStatus{ Statuses: &[]compute.InstanceViewStatus{
{ {
Code: to.StringPtr("PowerState/Running"), Code: pointer.String("PowerState/Running"),
}, },
}, },
}, },
@ -1022,7 +1022,7 @@ func TestGetStandardVMProvisioningStateByNodeName(t *testing.T) {
name: "GetProvisioningStateByNodeName should return empty string when vm.ProvisioningState is nil", name: "GetProvisioningStateByNodeName should return empty string when vm.ProvisioningState is nil",
nodeName: "vm3", nodeName: "vm3",
vm: compute.VirtualMachine{ vm: compute.VirtualMachine{
Name: to.StringPtr("vm3"), Name: pointer.String("vm3"),
VirtualMachineProperties: &compute.VirtualMachineProperties{ VirtualMachineProperties: &compute.VirtualMachineProperties{
ProvisioningState: nil, ProvisioningState: nil,
}, },
@ -1068,8 +1068,8 @@ func TestGetStandardVMZoneByNodeName(t *testing.T) {
name: "GetZoneByNodeName should get zone as expected", name: "GetZoneByNodeName should get zone as expected",
nodeName: "vm2", nodeName: "vm2",
vm: compute.VirtualMachine{ vm: compute.VirtualMachine{
Name: to.StringPtr("vm2"), Name: pointer.String("vm2"),
Location: to.StringPtr("EASTUS"), Location: pointer.String("EASTUS"),
Zones: &[]string{"2"}, Zones: &[]string{"2"},
VirtualMachineProperties: &compute.VirtualMachineProperties{ VirtualMachineProperties: &compute.VirtualMachineProperties{
InstanceView: &compute.VirtualMachineInstanceView{ InstanceView: &compute.VirtualMachineInstanceView{
@ -1086,8 +1086,8 @@ func TestGetStandardVMZoneByNodeName(t *testing.T) {
name: "GetZoneByNodeName should get FailureDomain as zone if zone is not used for node", name: "GetZoneByNodeName should get FailureDomain as zone if zone is not used for node",
nodeName: "vm3", nodeName: "vm3",
vm: compute.VirtualMachine{ vm: compute.VirtualMachine{
Name: to.StringPtr("vm3"), Name: pointer.String("vm3"),
Location: to.StringPtr("EASTUS"), Location: pointer.String("EASTUS"),
VirtualMachineProperties: &compute.VirtualMachineProperties{ VirtualMachineProperties: &compute.VirtualMachineProperties{
InstanceView: &compute.VirtualMachineInstanceView{ InstanceView: &compute.VirtualMachineInstanceView{
PlatformFaultDomain: &faultDomain, PlatformFaultDomain: &faultDomain,
@ -1103,8 +1103,8 @@ func TestGetStandardVMZoneByNodeName(t *testing.T) {
name: "GetZoneByNodeName should report error if zones is invalid", name: "GetZoneByNodeName should report error if zones is invalid",
nodeName: "vm4", nodeName: "vm4",
vm: compute.VirtualMachine{ vm: compute.VirtualMachine{
Name: to.StringPtr("vm4"), Name: pointer.String("vm4"),
Location: to.StringPtr("EASTUS"), Location: pointer.String("EASTUS"),
Zones: &[]string{"a"}, Zones: &[]string{"a"},
VirtualMachineProperties: &compute.VirtualMachineProperties{ VirtualMachineProperties: &compute.VirtualMachineProperties{
InstanceView: &compute.VirtualMachineInstanceView{ InstanceView: &compute.VirtualMachineInstanceView{
@ -1131,13 +1131,13 @@ func TestGetStandardVMSetNames(t *testing.T) {
asID := "/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Compute/availabilitySets/myAvailabilitySet" asID := "/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Compute/availabilitySets/myAvailabilitySet"
testVM := compute.VirtualMachine{ testVM := compute.VirtualMachine{
Name: to.StringPtr("vm1"), Name: pointer.String("vm1"),
VirtualMachineProperties: &compute.VirtualMachineProperties{ VirtualMachineProperties: &compute.VirtualMachineProperties{
AvailabilitySet: &compute.SubResource{ID: to.StringPtr(asID)}, AvailabilitySet: &compute.SubResource{ID: pointer.String(asID)},
}, },
} }
testVMWithoutAS := compute.VirtualMachine{ testVMWithoutAS := compute.VirtualMachine{
Name: to.StringPtr("vm2"), Name: pointer.String("vm2"),
VirtualMachineProperties: &compute.VirtualMachineProperties{}, VirtualMachineProperties: &compute.VirtualMachineProperties{},
} }
testCases := []struct { testCases := []struct {
@ -1384,11 +1384,11 @@ func TestStandardEnsureHostInPool(t *testing.T) {
} }
testVM := buildDefaultTestVirtualMachine(availabilitySetID, []string{test.nicID}) testVM := buildDefaultTestVirtualMachine(availabilitySetID, []string{test.nicID})
testVM.Name = to.StringPtr(string(test.nodeName)) testVM.Name = pointer.String(string(test.nodeName))
testNIC := buildDefaultTestInterface(false, []string{backendAddressPoolID}) testNIC := buildDefaultTestInterface(false, []string{backendAddressPoolID})
testNIC.Name = to.StringPtr(test.nicName) testNIC.Name = pointer.String(test.nicName)
testNIC.ID = to.StringPtr(test.nicID) testNIC.ID = pointer.String(test.nicID)
testNIC.ProvisioningState = to.StringPtr(test.nicProvisionState) testNIC.ProvisioningState = pointer.String(test.nicProvisionState)
mockVMClient := cloud.VirtualMachinesClient.(*mockvmclient.MockInterface) mockVMClient := cloud.VirtualMachinesClient.(*mockvmclient.MockInterface)
mockVMClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, string(test.nodeName), gomock.Any()).Return(testVM, nil).AnyTimes() mockVMClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, string(test.nodeName), gomock.Any()).Return(testVM, nil).AnyTimes()
@ -1522,13 +1522,13 @@ func TestStandardEnsureHostsInPool(t *testing.T) {
for _, test := range testCases { for _, test := range testCases {
cloud.Config.LoadBalancerSku = loadBalancerSkuStandard cloud.Config.LoadBalancerSku = loadBalancerSkuStandard
cloud.Config.ExcludeMasterFromStandardLB = to.BoolPtr(true) cloud.Config.ExcludeMasterFromStandardLB = pointer.Bool(true)
cloud.excludeLoadBalancerNodes = sets.NewString(test.excludeLBNodes...) cloud.excludeLoadBalancerNodes = sets.NewString(test.excludeLBNodes...)
testVM := buildDefaultTestVirtualMachine(availabilitySetID, []string{test.nicID}) testVM := buildDefaultTestVirtualMachine(availabilitySetID, []string{test.nicID})
testNIC := buildDefaultTestInterface(false, []string{backendAddressPoolID}) testNIC := buildDefaultTestInterface(false, []string{backendAddressPoolID})
testNIC.Name = to.StringPtr(test.nicName) testNIC.Name = pointer.String(test.nicName)
testNIC.ID = to.StringPtr(test.nicID) testNIC.ID = pointer.String(test.nicID)
mockVMClient := cloud.VirtualMachinesClient.(*mockvmclient.MockInterface) mockVMClient := cloud.VirtualMachinesClient.(*mockvmclient.MockInterface)
mockVMClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, test.nodeName, gomock.Any()).Return(testVM, nil).AnyTimes() mockVMClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, test.nodeName, gomock.Any()).Return(testVM, nil).AnyTimes()
@ -1563,7 +1563,7 @@ func TestServiceOwnsFrontendIP(t *testing.T) {
{ {
desc: "serviceOwnsFrontendIP should detect the primary service", desc: "serviceOwnsFrontendIP should detect the primary service",
fip: network.FrontendIPConfiguration{ fip: network.FrontendIPConfiguration{
Name: to.StringPtr("auid"), Name: pointer.String("auid"),
}, },
service: &v1.Service{ service: &v1.Service{
ObjectMeta: meta.ObjectMeta{ ObjectMeta: meta.ObjectMeta{
@ -1576,7 +1576,7 @@ func TestServiceOwnsFrontendIP(t *testing.T) {
{ {
desc: "serviceOwnsFrontendIP should return false if the secondary external service doesn't set it's loadBalancer IP", desc: "serviceOwnsFrontendIP should return false if the secondary external service doesn't set it's loadBalancer IP",
fip: network.FrontendIPConfiguration{ fip: network.FrontendIPConfiguration{
Name: to.StringPtr("auid"), Name: pointer.String("auid"),
}, },
service: &v1.Service{ service: &v1.Service{
ObjectMeta: meta.ObjectMeta{ ObjectMeta: meta.ObjectMeta{
@ -1589,17 +1589,17 @@ func TestServiceOwnsFrontendIP(t *testing.T) {
"found according to the external service's loadBalancer IP but do not return the error", "found according to the external service's loadBalancer IP but do not return the error",
existingPIPs: []network.PublicIPAddress{ existingPIPs: []network.PublicIPAddress{
{ {
ID: to.StringPtr("pip"), ID: pointer.String("pip"),
PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{
IPAddress: to.StringPtr("4.3.2.1"), IPAddress: pointer.String("4.3.2.1"),
}, },
}, },
}, },
fip: network.FrontendIPConfiguration{ fip: network.FrontendIPConfiguration{
Name: to.StringPtr("auid"), Name: pointer.String("auid"),
FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{
PublicIPAddress: &network.PublicIPAddress{ PublicIPAddress: &network.PublicIPAddress{
ID: to.StringPtr("pip"), ID: pointer.String("pip"),
}, },
}, },
}, },
@ -1617,17 +1617,17 @@ func TestServiceOwnsFrontendIP(t *testing.T) {
"the counterpart on the frontend IP config", "the counterpart on the frontend IP config",
existingPIPs: []network.PublicIPAddress{ existingPIPs: []network.PublicIPAddress{
{ {
ID: to.StringPtr("pip"), ID: pointer.String("pip"),
PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{
IPAddress: to.StringPtr("4.3.2.1"), IPAddress: pointer.String("4.3.2.1"),
}, },
}, },
}, },
fip: network.FrontendIPConfiguration{ fip: network.FrontendIPConfiguration{
Name: to.StringPtr("auid"), Name: pointer.String("auid"),
FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{
PublicIPAddress: &network.PublicIPAddress{ PublicIPAddress: &network.PublicIPAddress{
ID: to.StringPtr("pip1"), ID: pointer.String("pip1"),
}, },
}, },
}, },
@ -1644,17 +1644,17 @@ func TestServiceOwnsFrontendIP(t *testing.T) {
desc: "serviceOwnsFrontendIP should detect the secondary external service", desc: "serviceOwnsFrontendIP should detect the secondary external service",
existingPIPs: []network.PublicIPAddress{ existingPIPs: []network.PublicIPAddress{
{ {
ID: to.StringPtr("pip"), ID: pointer.String("pip"),
PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{
IPAddress: to.StringPtr("4.3.2.1"), IPAddress: pointer.String("4.3.2.1"),
}, },
}, },
}, },
fip: network.FrontendIPConfiguration{ fip: network.FrontendIPConfiguration{
Name: to.StringPtr("auid"), Name: pointer.String("auid"),
FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{
PublicIPAddress: &network.PublicIPAddress{ PublicIPAddress: &network.PublicIPAddress{
ID: to.StringPtr("pip"), ID: pointer.String("pip"),
}, },
}, },
}, },
@ -1671,9 +1671,9 @@ func TestServiceOwnsFrontendIP(t *testing.T) {
{ {
desc: "serviceOwnsFrontendIP should detect the secondary internal service", desc: "serviceOwnsFrontendIP should detect the secondary internal service",
fip: network.FrontendIPConfiguration{ fip: network.FrontendIPConfiguration{
Name: to.StringPtr("auid"), Name: pointer.String("auid"),
FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{
PrivateIPAddress: to.StringPtr("4.3.2.1"), PrivateIPAddress: pointer.String("4.3.2.1"),
}, },
}, },
service: &v1.Service{ service: &v1.Service{
@ -1720,11 +1720,11 @@ func TestStandardEnsureBackendPoolDeleted(t *testing.T) {
desc: "EnsureBackendPoolDeleted should decouple the nic and the load balancer properly", desc: "EnsureBackendPoolDeleted should decouple the nic and the load balancer properly",
backendAddressPools: &[]network.BackendAddressPool{ backendAddressPools: &[]network.BackendAddressPool{
{ {
ID: to.StringPtr(backendPoolID), ID: pointer.String(backendPoolID),
BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{
BackendIPConfigurations: &[]network.InterfaceIPConfiguration{ BackendIPConfigurations: &[]network.InterfaceIPConfiguration{
{ {
ID: to.StringPtr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/k8s-agentpool1-00000000-nic-1/ipConfigurations/ipconfig1"), ID: pointer.String("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/k8s-agentpool1-00000000-nic-1/ipConfigurations/ipconfig1"),
}, },
}, },
}, },
@ -1744,7 +1744,7 @@ func TestStandardEnsureBackendPoolDeleted(t *testing.T) {
cloud.VirtualMachinesClient = mockVMClient cloud.VirtualMachinesClient = mockVMClient
mockNICClient := mockinterfaceclient.NewMockInterface(ctrl) mockNICClient := mockinterfaceclient.NewMockInterface(ctrl)
test.existingNIC.VirtualMachine = &network.SubResource{ test.existingNIC.VirtualMachine = &network.SubResource{
ID: to.StringPtr("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/k8s-agentpool1-00000000-1"), ID: pointer.String("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/k8s-agentpool1-00000000-1"),
} }
mockNICClient.EXPECT().Get(gomock.Any(), "rg", "k8s-agentpool1-00000000-nic-1", gomock.Any()).Return(test.existingNIC, nil).Times(2) mockNICClient.EXPECT().Get(gomock.Any(), "rg", "k8s-agentpool1-00000000-nic-1", gomock.Any()).Return(test.existingNIC, nil).Times(2)
mockNICClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil) mockNICClient.EXPECT().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil)
@ -1758,11 +1758,11 @@ func TestStandardEnsureBackendPoolDeleted(t *testing.T) {
func buildDefaultTestInterface(isPrimary bool, lbBackendpoolIDs []string) network.Interface { func buildDefaultTestInterface(isPrimary bool, lbBackendpoolIDs []string) network.Interface {
expectedNIC := network.Interface{ expectedNIC := network.Interface{
InterfacePropertiesFormat: &network.InterfacePropertiesFormat{ InterfacePropertiesFormat: &network.InterfacePropertiesFormat{
ProvisioningState: to.StringPtr("Succeeded"), ProvisioningState: pointer.String("Succeeded"),
IPConfigurations: &[]network.InterfaceIPConfiguration{ IPConfigurations: &[]network.InterfaceIPConfiguration{
{ {
InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{
Primary: to.BoolPtr(isPrimary), Primary: pointer.Bool(isPrimary),
}, },
}, },
}, },
@ -1771,7 +1771,7 @@ func buildDefaultTestInterface(isPrimary bool, lbBackendpoolIDs []string) networ
backendAddressPool := make([]network.BackendAddressPool, 0) backendAddressPool := make([]network.BackendAddressPool, 0)
for _, id := range lbBackendpoolIDs { for _, id := range lbBackendpoolIDs {
backendAddressPool = append(backendAddressPool, network.BackendAddressPool{ backendAddressPool = append(backendAddressPool, network.BackendAddressPool{
ID: to.StringPtr(id), ID: pointer.String(id),
}) })
} }
(*expectedNIC.IPConfigurations)[0].LoadBalancerBackendAddressPools = &backendAddressPool (*expectedNIC.IPConfigurations)[0].LoadBalancerBackendAddressPools = &backendAddressPool
@ -1782,7 +1782,7 @@ func buildDefaultTestVirtualMachine(asID string, nicIDs []string) compute.Virtua
expectedVM := compute.VirtualMachine{ expectedVM := compute.VirtualMachine{
VirtualMachineProperties: &compute.VirtualMachineProperties{ VirtualMachineProperties: &compute.VirtualMachineProperties{
AvailabilitySet: &compute.SubResource{ AvailabilitySet: &compute.SubResource{
ID: to.StringPtr(asID), ID: pointer.String(asID),
}, },
NetworkProfile: &compute.NetworkProfile{}, NetworkProfile: &compute.NetworkProfile{},
}, },
@ -1790,7 +1790,7 @@ func buildDefaultTestVirtualMachine(asID string, nicIDs []string) compute.Virtua
networkInterfaces := make([]compute.NetworkInterfaceReference, 0) networkInterfaces := make([]compute.NetworkInterfaceReference, 0)
for _, nicID := range nicIDs { for _, nicID := range nicIDs {
networkInterfaces = append(networkInterfaces, compute.NetworkInterfaceReference{ networkInterfaces = append(networkInterfaces, compute.NetworkInterfaceReference{
ID: to.StringPtr(nicID), ID: pointer.String(nicID),
}) })
} }
expectedVM.VirtualMachineProperties.NetworkProfile.NetworkInterfaces = &networkInterfaces expectedVM.VirtualMachineProperties.NetworkProfile.NetworkInterfaces = &networkInterfaces
@ -1802,12 +1802,12 @@ func TestStandardGetNodeNameByIPConfigurationID(t *testing.T) {
defer ctrl.Finish() defer ctrl.Finish()
cloud := GetTestCloud(ctrl) cloud := GetTestCloud(ctrl)
expectedVM := buildDefaultTestVirtualMachine("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/availabilitySets/AGENTPOOL1-AVAILABILITYSET-00000000", []string{}) expectedVM := buildDefaultTestVirtualMachine("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/availabilitySets/AGENTPOOL1-AVAILABILITYSET-00000000", []string{})
expectedVM.Name = to.StringPtr("name") expectedVM.Name = pointer.String("name")
mockVMClient := cloud.VirtualMachinesClient.(*mockvmclient.MockInterface) mockVMClient := cloud.VirtualMachinesClient.(*mockvmclient.MockInterface)
mockVMClient.EXPECT().Get(gomock.Any(), "rg", "k8s-agentpool1-00000000-0", gomock.Any()).Return(expectedVM, nil) mockVMClient.EXPECT().Get(gomock.Any(), "rg", "k8s-agentpool1-00000000-0", gomock.Any()).Return(expectedVM, nil)
expectedNIC := buildDefaultTestInterface(true, []string{}) expectedNIC := buildDefaultTestInterface(true, []string{})
expectedNIC.VirtualMachine = &network.SubResource{ expectedNIC.VirtualMachine = &network.SubResource{
ID: to.StringPtr("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/k8s-agentpool1-00000000-0"), ID: pointer.String("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/k8s-agentpool1-00000000-0"),
} }
mockNICClient := cloud.InterfacesClient.(*mockinterfaceclient.MockInterface) mockNICClient := cloud.InterfacesClient.(*mockinterfaceclient.MockInterface)
mockNICClient.EXPECT().Get(gomock.Any(), "rg", "k8s-agentpool1-00000000-nic-0", gomock.Any()).Return(expectedNIC, nil) mockNICClient.EXPECT().Get(gomock.Any(), "rg", "k8s-agentpool1-00000000-nic-0", gomock.Any()).Return(expectedNIC, nil)

View File

@ -24,9 +24,9 @@ import (
"strings" "strings"
"github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2019-06-01/storage" "github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2019-06-01/storage"
"github.com/Azure/go-autorest/autorest/to"
"k8s.io/klog/v2" "k8s.io/klog/v2"
"k8s.io/utils/pointer"
) )
// AccountOptions contains the fields which are used to create storage account. // AccountOptions contains the fields which are used to create storage account.
@ -76,7 +76,7 @@ func (az *Cloud) getStorageAccounts(accountOptions *AccountOptions) ([]accountWi
found := false found := false
for _, subnetID := range accountOptions.VirtualNetworkResourceIDs { for _, subnetID := range accountOptions.VirtualNetworkResourceIDs {
for _, rule := range *acct.AccountProperties.NetworkRuleSet.VirtualNetworkRules { for _, rule := range *acct.AccountProperties.NetworkRuleSet.VirtualNetworkRules {
if strings.EqualFold(to.String(rule.VirtualNetworkResourceID), subnetID) && rule.Action == storage.Allow { if strings.EqualFold(pointer.StringDeref(rule.VirtualNetworkResourceID, ""), subnetID) && rule.Action == storage.Allow {
found = true found = true
break break
} }

View File

@ -30,7 +30,6 @@ import (
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute"
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network"
"github.com/Azure/go-autorest/autorest/to"
"github.com/golang/mock/gomock" "github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -50,6 +49,7 @@ import (
"k8s.io/legacy-cloud-providers/azure/clients/subnetclient/mocksubnetclient" "k8s.io/legacy-cloud-providers/azure/clients/subnetclient/mocksubnetclient"
"k8s.io/legacy-cloud-providers/azure/clients/vmclient/mockvmclient" "k8s.io/legacy-cloud-providers/azure/clients/vmclient/mockvmclient"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
) )
var testClusterName = "testCluster" var testClusterName = "testCluster"
@ -151,21 +151,21 @@ func setMockEnv(az *Cloud, ctrl *gomock.Controller, expectedInterfaces []network
func setMockPublicIPs(az *Cloud, ctrl *gomock.Controller, serviceCount int) { func setMockPublicIPs(az *Cloud, ctrl *gomock.Controller, serviceCount int) {
expectedPIPs := []network.PublicIPAddress{ expectedPIPs := []network.PublicIPAddress{
{ {
Name: to.StringPtr("testCluster-aservicea"), Name: pointer.String("testCluster-aservicea"),
Location: &az.Location, Location: &az.Location,
PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{
PublicIPAllocationMethod: network.Static, PublicIPAllocationMethod: network.Static,
PublicIPAddressVersion: network.IPv4, PublicIPAddressVersion: network.IPv4,
IPAddress: to.StringPtr("1.2.3.4"), IPAddress: pointer.String("1.2.3.4"),
}, },
Tags: map[string]*string{ Tags: map[string]*string{
serviceTagKey: to.StringPtr("default/servicea"), serviceTagKey: pointer.String("default/servicea"),
clusterNameKey: &testClusterName, clusterNameKey: &testClusterName,
}, },
Sku: &network.PublicIPAddressSku{ Sku: &network.PublicIPAddressSku{
Name: network.PublicIPAddressSkuNameStandard, Name: network.PublicIPAddressSkuNameStandard,
}, },
ID: to.StringPtr("testCluster-aservice1"), ID: pointer.String("testCluster-aservice1"),
}, },
} }
@ -178,12 +178,12 @@ func setMockPublicIPs(az *Cloud, ctrl *gomock.Controller, serviceCount int) {
a := 'a' a := 'a'
for i := 1; i <= serviceCount; i++ { for i := 1; i <= serviceCount; i++ {
expectedPIPs[0].Name = to.StringPtr(fmt.Sprintf("testCluster-aservice%d", i)) expectedPIPs[0].Name = pointer.String(fmt.Sprintf("testCluster-aservice%d", i))
expectedPIPs[0].Tags[serviceTagKey] = to.StringPtr(fmt.Sprintf("default/service%d", i)) expectedPIPs[0].Tags[serviceTagKey] = pointer.String(fmt.Sprintf("default/service%d", i))
mockPIPsClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, fmt.Sprintf("testCluster-aservice%d", i), gomock.Any()).Return(expectedPIPs[0], nil).AnyTimes() mockPIPsClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, fmt.Sprintf("testCluster-aservice%d", i), gomock.Any()).Return(expectedPIPs[0], nil).AnyTimes()
mockPIPsClient.EXPECT().Delete(gomock.Any(), az.ResourceGroup, fmt.Sprintf("testCluster-aservice%d", i)).Return(nil).AnyTimes() mockPIPsClient.EXPECT().Delete(gomock.Any(), az.ResourceGroup, fmt.Sprintf("testCluster-aservice%d", i)).Return(nil).AnyTimes()
expectedPIPs[0].Name = to.StringPtr(fmt.Sprintf("testCluster-aservice%c", a)) expectedPIPs[0].Name = pointer.String(fmt.Sprintf("testCluster-aservice%c", a))
expectedPIPs[0].Tags[serviceTagKey] = to.StringPtr(fmt.Sprintf("default/service%c", a)) expectedPIPs[0].Tags[serviceTagKey] = pointer.String(fmt.Sprintf("default/service%c", a))
mockPIPsClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, fmt.Sprintf("testCluster-aservice%c", a), gomock.Any()).Return(expectedPIPs[0], nil).AnyTimes() mockPIPsClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, fmt.Sprintf("testCluster-aservice%c", a), gomock.Any()).Return(expectedPIPs[0], nil).AnyTimes()
mockPIPsClient.EXPECT().Delete(gomock.Any(), az.ResourceGroup, fmt.Sprintf("testCluster-aservice%c", a)).Return(nil).AnyTimes() mockPIPsClient.EXPECT().Delete(gomock.Any(), az.ResourceGroup, fmt.Sprintf("testCluster-aservice%c", a)).Return(nil).AnyTimes()
a++ a++
@ -219,7 +219,7 @@ func setMockLBs(az *Cloud, ctrl *gomock.Controller, expectedLBs *[]network.LoadB
LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{
BackendAddressPools: &[]network.BackendAddressPool{ BackendAddressPools: &[]network.BackendAddressPool{
{ {
Name: to.StringPtr("testCluster"), Name: pointer.String("testCluster"),
}, },
}, },
}, },
@ -227,39 +227,39 @@ func setMockLBs(az *Cloud, ctrl *gomock.Controller, expectedLBs *[]network.LoadB
lb.Name = &expectedLBName lb.Name = &expectedLBName
lb.LoadBalancingRules = &[]network.LoadBalancingRule{ lb.LoadBalancingRules = &[]network.LoadBalancingRule{
{ {
Name: to.StringPtr(fmt.Sprintf("a%s%d-TCP-8081", fullServiceName, serviceIndex)), Name: pointer.String(fmt.Sprintf("a%s%d-TCP-8081", fullServiceName, serviceIndex)),
}, },
} }
fips := []network.FrontendIPConfiguration{ fips := []network.FrontendIPConfiguration{
{ {
Name: to.StringPtr(fmt.Sprintf("a%s%d", fullServiceName, serviceIndex)), Name: pointer.String(fmt.Sprintf("a%s%d", fullServiceName, serviceIndex)),
ID: to.StringPtr("fip"), ID: pointer.String("fip"),
FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{
PrivateIPAllocationMethod: "Dynamic", PrivateIPAllocationMethod: "Dynamic",
PublicIPAddress: &network.PublicIPAddress{ID: to.StringPtr(fmt.Sprintf("testCluster-a%s%d", fullServiceName, serviceIndex))}, PublicIPAddress: &network.PublicIPAddress{ID: pointer.String(fmt.Sprintf("testCluster-a%s%d", fullServiceName, serviceIndex))},
}, },
}, },
} }
if isInternal { if isInternal {
fips[0].Subnet = &network.Subnet{Name: to.StringPtr("subnet")} fips[0].Subnet = &network.Subnet{Name: pointer.String("subnet")}
} }
lb.FrontendIPConfigurations = &fips lb.FrontendIPConfigurations = &fips
*expectedLBs = append(*expectedLBs, lb) *expectedLBs = append(*expectedLBs, lb)
} else { } else {
*(*expectedLBs)[lbIndex].LoadBalancingRules = append(*(*expectedLBs)[lbIndex].LoadBalancingRules, network.LoadBalancingRule{ *(*expectedLBs)[lbIndex].LoadBalancingRules = append(*(*expectedLBs)[lbIndex].LoadBalancingRules, network.LoadBalancingRule{
Name: to.StringPtr(fmt.Sprintf("a%s%d-TCP-8081", fullServiceName, serviceIndex)), Name: pointer.String(fmt.Sprintf("a%s%d-TCP-8081", fullServiceName, serviceIndex)),
}) })
fip := network.FrontendIPConfiguration{ fip := network.FrontendIPConfiguration{
Name: to.StringPtr(fmt.Sprintf("a%s%d", fullServiceName, serviceIndex)), Name: pointer.String(fmt.Sprintf("a%s%d", fullServiceName, serviceIndex)),
ID: to.StringPtr("fip"), ID: pointer.String("fip"),
FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{
PrivateIPAllocationMethod: "Dynamic", PrivateIPAllocationMethod: "Dynamic",
PublicIPAddress: &network.PublicIPAddress{ID: to.StringPtr(fmt.Sprintf("testCluster-a%s%d", fullServiceName, serviceIndex))}, PublicIPAddress: &network.PublicIPAddress{ID: pointer.String(fmt.Sprintf("testCluster-a%s%d", fullServiceName, serviceIndex))},
}, },
} }
if isInternal { if isInternal {
fip.Subnet = &network.Subnet{Name: to.StringPtr("subnet")} fip.Subnet = &network.Subnet{Name: pointer.String("subnet")}
} }
*(*expectedLBs)[lbIndex].FrontendIPConfigurations = append(*(*expectedLBs)[lbIndex].FrontendIPConfigurations, fip) *(*expectedLBs)[lbIndex].FrontendIPConfigurations = append(*(*expectedLBs)[lbIndex].FrontendIPConfigurations, fip)
} }
@ -511,7 +511,7 @@ func testLoadBalancerMaxRulesServices(t *testing.T, isInternal bool) {
svc = getTestService(svcName, v1.ProtocolTCP, nil, false, 8081) svc = getTestService(svcName, v1.ProtocolTCP, nil, false, 8081)
} }
//*expectedLBs[0].FrontendIPConfigurations = append(*expectedLBs[0].FrontendIPConfigurations, network.FrontendIPConfiguration{ //*expectedLBs[0].FrontendIPConfigurations = append(*expectedLBs[0].FrontendIPConfigurations, network.FrontendIPConfiguration{
// Name: to.StringPtr(fmt.Sprintf("aservice%d", 2)), // Name: pointer.String(fmt.Sprintf("aservice%d", 2)),
// FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ // FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{
// PrivateIPAllocationMethod: "Dynamic", // PrivateIPAllocationMethod: "Dynamic",
// }, // },
@ -655,11 +655,11 @@ func TestReconcileSecurityGroupFromAnyDestinationAddressPrefixToLoadBalancerIP(t
setMockSecurityGroup(az, ctrl, sg) setMockSecurityGroup(az, ctrl, sg)
// Simulate a pre-Kubernetes 1.8 NSG, where we do not specify the destination address prefix // Simulate a pre-Kubernetes 1.8 NSG, where we do not specify the destination address prefix
_, err := az.reconcileSecurityGroup(testClusterName, &svc1, to.StringPtr(""), true) _, err := az.reconcileSecurityGroup(testClusterName, &svc1, pointer.String(""), true)
if err != nil { if err != nil {
t.Errorf("Unexpected error: %q", err) t.Errorf("Unexpected error: %q", err)
} }
sg, err = az.reconcileSecurityGroup(testClusterName, &svc1, to.StringPtr(svc1.Spec.LoadBalancerIP), true) sg, err = az.reconcileSecurityGroup(testClusterName, &svc1, pointer.String(svc1.Spec.LoadBalancerIP), true)
if err != nil { if err != nil {
t.Errorf("Unexpected error: %q", err) t.Errorf("Unexpected error: %q", err)
} }
@ -678,7 +678,7 @@ func TestReconcileSecurityGroupDynamicLoadBalancerIP(t *testing.T) {
setMockSecurityGroup(az, ctrl, sg) setMockSecurityGroup(az, ctrl, sg)
dynamicallyAssignedIP := "192.168.0.0" dynamicallyAssignedIP := "192.168.0.0"
sg, err := az.reconcileSecurityGroup(testClusterName, &svc1, to.StringPtr(dynamicallyAssignedIP), true) sg, err := az.reconcileSecurityGroup(testClusterName, &svc1, pointer.String(dynamicallyAssignedIP), true)
if err != nil { if err != nil {
t.Errorf("unexpected error: %q", err) t.Errorf("unexpected error: %q", err)
} }
@ -965,20 +965,20 @@ func TestServiceDefaultsToNoSessionPersistence(t *testing.T) {
setMockLBs(az, ctrl, &expectedLBs, "service-sa-omitted", 1, 1, false) setMockLBs(az, ctrl, &expectedLBs, "service-sa-omitted", 1, 1, false)
expectedPIP := network.PublicIPAddress{ expectedPIP := network.PublicIPAddress{
Name: to.StringPtr("testCluster-aservicesaomitted1"), Name: pointer.String("testCluster-aservicesaomitted1"),
Location: &az.Location, Location: &az.Location,
PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{
PublicIPAllocationMethod: network.Static, PublicIPAllocationMethod: network.Static,
PublicIPAddressVersion: network.IPv4, PublicIPAddressVersion: network.IPv4,
}, },
Tags: map[string]*string{ Tags: map[string]*string{
serviceTagKey: to.StringPtr("aservicesaomitted1"), serviceTagKey: pointer.String("aservicesaomitted1"),
clusterNameKey: &testClusterName, clusterNameKey: &testClusterName,
}, },
Sku: &network.PublicIPAddressSku{ Sku: &network.PublicIPAddressSku{
Name: network.PublicIPAddressSkuNameStandard, Name: network.PublicIPAddressSkuNameStandard,
}, },
ID: to.StringPtr("testCluster-aservicesaomitted1"), ID: pointer.String("testCluster-aservicesaomitted1"),
} }
mockPIPsClient := mockpublicipclient.NewMockInterface(ctrl) mockPIPsClient := mockpublicipclient.NewMockInterface(ctrl)
@ -1015,20 +1015,20 @@ func TestServiceRespectsNoSessionAffinity(t *testing.T) {
setMockLBs(az, ctrl, &expectedLBs, "service-sa-none", 1, 1, false) setMockLBs(az, ctrl, &expectedLBs, "service-sa-none", 1, 1, false)
expectedPIP := network.PublicIPAddress{ expectedPIP := network.PublicIPAddress{
Name: to.StringPtr("testCluster-aservicesanone"), Name: pointer.String("testCluster-aservicesanone"),
Location: &az.Location, Location: &az.Location,
PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{
PublicIPAllocationMethod: network.Static, PublicIPAllocationMethod: network.Static,
PublicIPAddressVersion: network.IPv4, PublicIPAddressVersion: network.IPv4,
}, },
Tags: map[string]*string{ Tags: map[string]*string{
serviceTagKey: to.StringPtr("aservicesanone"), serviceTagKey: pointer.String("aservicesanone"),
clusterNameKey: &testClusterName, clusterNameKey: &testClusterName,
}, },
Sku: &network.PublicIPAddressSku{ Sku: &network.PublicIPAddressSku{
Name: network.PublicIPAddressSkuNameStandard, Name: network.PublicIPAddressSkuNameStandard,
}, },
ID: to.StringPtr("testCluster-aservicesanone"), ID: pointer.String("testCluster-aservicesanone"),
} }
mockPIPsClient := mockpublicipclient.NewMockInterface(ctrl) mockPIPsClient := mockpublicipclient.NewMockInterface(ctrl)
@ -1067,20 +1067,20 @@ func TestServiceRespectsClientIPSessionAffinity(t *testing.T) {
setMockLBs(az, ctrl, &expectedLBs, "service-sa-clientip", 1, 1, false) setMockLBs(az, ctrl, &expectedLBs, "service-sa-clientip", 1, 1, false)
expectedPIP := network.PublicIPAddress{ expectedPIP := network.PublicIPAddress{
Name: to.StringPtr("testCluster-aservicesaclientip"), Name: pointer.String("testCluster-aservicesaclientip"),
Location: &az.Location, Location: &az.Location,
PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{
PublicIPAllocationMethod: network.Static, PublicIPAllocationMethod: network.Static,
PublicIPAddressVersion: network.IPv4, PublicIPAddressVersion: network.IPv4,
}, },
Tags: map[string]*string{ Tags: map[string]*string{
serviceTagKey: to.StringPtr("aservicesaclientip"), serviceTagKey: pointer.String("aservicesaclientip"),
clusterNameKey: &testClusterName, clusterNameKey: &testClusterName,
}, },
Sku: &network.PublicIPAddressSku{ Sku: &network.PublicIPAddressSku{
Name: network.PublicIPAddressSkuNameStandard, Name: network.PublicIPAddressSkuNameStandard,
}, },
ID: to.StringPtr("testCluster-aservicesaclientip"), ID: pointer.String("testCluster-aservicesaclientip"),
} }
mockPIPsClient := mockpublicipclient.NewMockInterface(ctrl) mockPIPsClient := mockpublicipclient.NewMockInterface(ctrl)
@ -1238,8 +1238,8 @@ func TestReconcileSecurityGroupEtagMismatch(t *testing.T) {
sg := getTestSecurityGroup(az) sg := getTestSecurityGroup(az)
cachedSG := *sg cachedSG := *sg
cachedSG.Etag = to.StringPtr("1111111-0000-0000-0000-000000000000") cachedSG.Etag = pointer.String("1111111-0000-0000-0000-000000000000")
az.nsgCache.Set(to.String(sg.Name), &cachedSG) az.nsgCache.Set(pointer.StringDeref(sg.Name, ""), &cachedSG)
svc1 := getTestService("service1", v1.ProtocolTCP, nil, false, 80) svc1 := getTestService("service1", v1.ProtocolTCP, nil, false, 80)
clusterResources, expectedInterfaces, expectedVirtualMachines := getClusterResources(az, 1, 1) clusterResources, expectedInterfaces, expectedVirtualMachines := getClusterResources(az, 1, 1)
@ -1563,10 +1563,10 @@ func getTestSecurityGroup(az *Cloud, services ...v1.Service) *network.SecurityGr
for _, src := range sources { for _, src := range sources {
ruleName := az.getSecurityRuleName(&service, port, src) ruleName := az.getSecurityRuleName(&service, port, src)
rules = append(rules, network.SecurityRule{ rules = append(rules, network.SecurityRule{
Name: to.StringPtr(ruleName), Name: pointer.String(ruleName),
SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{ SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{
SourceAddressPrefix: to.StringPtr(src), SourceAddressPrefix: pointer.String(src),
DestinationPortRange: to.StringPtr(fmt.Sprintf("%d", port.Port)), DestinationPortRange: pointer.String(fmt.Sprintf("%d", port.Port)),
}, },
}) })
} }
@ -1575,7 +1575,7 @@ func getTestSecurityGroup(az *Cloud, services ...v1.Service) *network.SecurityGr
sg := network.SecurityGroup{ sg := network.SecurityGroup{
Name: &az.SecurityGroupName, Name: &az.SecurityGroupName,
Etag: to.StringPtr("0000000-0000-0000-0000-000000000000"), Etag: pointer.String("0000000-0000-0000-0000-000000000000"),
SecurityGroupPropertiesFormat: &network.SecurityGroupPropertiesFormat{ SecurityGroupPropertiesFormat: &network.SecurityGroupPropertiesFormat{
SecurityRules: &rules, SecurityRules: &rules,
}, },
@ -1605,7 +1605,7 @@ func validateLoadBalancer(t *testing.T, loadBalancer *network.LoadBalancer, serv
} }
expectedFrontendIP := ExpectedFrontendIPInfo{ expectedFrontendIP := ExpectedFrontendIPInfo{
Name: az.getDefaultFrontendIPConfigName(&svc), Name: az.getDefaultFrontendIPConfigName(&svc),
Subnet: to.StringPtr(expectedSubnetName), Subnet: pointer.String(expectedSubnetName),
} }
expectedFrontendIPs = append(expectedFrontendIPs, expectedFrontendIP) expectedFrontendIPs = append(expectedFrontendIPs, expectedFrontendIP)
} }
@ -1669,7 +1669,7 @@ func validateLoadBalancer(t *testing.T, loadBalancer *network.LoadBalancer, serv
frontendIPs := *loadBalancer.FrontendIPConfigurations frontendIPs := *loadBalancer.FrontendIPConfigurations
for _, expectedFrontendIP := range expectedFrontendIPs { for _, expectedFrontendIP := range expectedFrontendIPs {
if !expectedFrontendIP.existsIn(frontendIPs) { if !expectedFrontendIP.existsIn(frontendIPs) {
t.Errorf("Expected the loadbalancer to have frontend IP %s/%s. Found %s", expectedFrontendIP.Name, to.String(expectedFrontendIP.Subnet), describeFIPs(frontendIPs)) t.Errorf("Expected the loadbalancer to have frontend IP %s/%s. Found %s", expectedFrontendIP.Name, pointer.StringDeref(expectedFrontendIP.Subnet, ""), describeFIPs(frontendIPs))
} }
} }
@ -1690,7 +1690,7 @@ type ExpectedFrontendIPInfo struct {
} }
func (expected ExpectedFrontendIPInfo) matches(frontendIP network.FrontendIPConfiguration) bool { func (expected ExpectedFrontendIPInfo) matches(frontendIP network.FrontendIPConfiguration) bool {
return strings.EqualFold(expected.Name, to.String(frontendIP.Name)) && strings.EqualFold(to.String(expected.Subnet), to.String(subnetName(frontendIP))) return strings.EqualFold(expected.Name, pointer.StringDeref(frontendIP.Name, "")) && strings.EqualFold(pointer.StringDeref(expected.Subnet, ""), pointer.StringDeref(subnetName(frontendIP), ""))
} }
func (expected ExpectedFrontendIPInfo) existsIn(frontendIPs []network.FrontendIPConfiguration) bool { func (expected ExpectedFrontendIPInfo) existsIn(frontendIPs []network.FrontendIPConfiguration) bool {
@ -1714,9 +1714,9 @@ func describeFIPs(frontendIPs []network.FrontendIPConfiguration) string {
for _, actualFIP := range frontendIPs { for _, actualFIP := range frontendIPs {
actualSubnetName := "" actualSubnetName := ""
if actualFIP.Subnet != nil { if actualFIP.Subnet != nil {
actualSubnetName = to.String(actualFIP.Subnet.Name) actualSubnetName = pointer.StringDeref(actualFIP.Subnet.Name, "")
} }
actualFIPText := fmt.Sprintf("%s/%s ", to.String(actualFIP.Name), actualSubnetName) actualFIPText := fmt.Sprintf("%s/%s ", pointer.StringDeref(actualFIP.Name, ""), actualSubnetName)
description = description + actualFIPText description = description + actualFIPText
} }
return description return description
@ -1856,7 +1856,7 @@ func TestSecurityRulePriorityPicksNextAvailablePriority(t *testing.T) {
for i = loadBalancerMinimumPriority; i < expectedPriority; i++ { for i = loadBalancerMinimumPriority; i < expectedPriority; i++ {
rules = append(rules, network.SecurityRule{ rules = append(rules, network.SecurityRule{
SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{ SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{
Priority: to.Int32Ptr(i), Priority: pointer.Int32(i),
}, },
}) })
} }
@ -1878,7 +1878,7 @@ func TestSecurityRulePriorityFailsIfExhausted(t *testing.T) {
for i = loadBalancerMinimumPriority; i < loadBalancerMaximumPriority; i++ { for i = loadBalancerMinimumPriority; i < loadBalancerMaximumPriority; i++ {
rules = append(rules, network.SecurityRule{ rules = append(rules, network.SecurityRule{
SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{ SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{
Priority: to.Int32Ptr(i), Priority: pointer.Int32(i),
}, },
}) })
} }
@ -2234,7 +2234,7 @@ func TestIfServiceSpecifiesSharedRuleAndRuleDoesNotExistItIsCreated(t *testing.T
sg := getTestSecurityGroup(az) sg := getTestSecurityGroup(az)
setMockSecurityGroup(az, ctrl, sg) setMockSecurityGroup(az, ctrl, sg)
sg, err := az.reconcileSecurityGroup(testClusterName, &svc, to.StringPtr(svc.Spec.LoadBalancerIP), true) sg, err := az.reconcileSecurityGroup(testClusterName, &svc, pointer.String(svc.Spec.LoadBalancerIP), true)
if err != nil { if err != nil {
t.Errorf("Unexpected error: %q", err) t.Errorf("Unexpected error: %q", err)
} }
@ -2282,10 +2282,10 @@ func TestIfServiceSpecifiesSharedRuleAndRuleExistsThenTheServicesPortAndAddressA
Name: &expectedRuleName, Name: &expectedRuleName,
SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{ SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{
Protocol: network.SecurityRuleProtocolTCP, Protocol: network.SecurityRuleProtocolTCP,
SourcePortRange: to.StringPtr("*"), SourcePortRange: pointer.String("*"),
SourceAddressPrefix: to.StringPtr("Internet"), SourceAddressPrefix: pointer.String("Internet"),
DestinationPortRange: to.StringPtr("80"), DestinationPortRange: pointer.String("80"),
DestinationAddressPrefix: to.StringPtr("192.168.33.44"), DestinationAddressPrefix: pointer.String("192.168.33.44"),
Access: network.SecurityRuleAccessAllow, Access: network.SecurityRuleAccessAllow,
Direction: network.SecurityRuleDirectionInbound, Direction: network.SecurityRuleDirectionInbound,
}, },
@ -2293,7 +2293,7 @@ func TestIfServiceSpecifiesSharedRuleAndRuleExistsThenTheServicesPortAndAddressA
} }
setMockSecurityGroup(az, ctrl, sg) setMockSecurityGroup(az, ctrl, sg)
sg, err := az.reconcileSecurityGroup(testClusterName, &svc, to.StringPtr(svc.Spec.LoadBalancerIP), true) sg, err := az.reconcileSecurityGroup(testClusterName, &svc, pointer.String(svc.Spec.LoadBalancerIP), true)
if err != nil { if err != nil {
t.Errorf("Unexpected error: %q", err) t.Errorf("Unexpected error: %q", err)
} }
@ -2340,12 +2340,12 @@ func TestIfServicesSpecifySharedRuleButDifferentPortsThenSeparateRulesAreCreated
sg := getTestSecurityGroup(az) sg := getTestSecurityGroup(az)
setMockSecurityGroup(az, ctrl, sg) setMockSecurityGroup(az, ctrl, sg)
_, err := az.reconcileSecurityGroup(testClusterName, &svc1, to.StringPtr(svc1.Spec.LoadBalancerIP), true) _, err := az.reconcileSecurityGroup(testClusterName, &svc1, pointer.String(svc1.Spec.LoadBalancerIP), true)
if err != nil { if err != nil {
t.Errorf("Unexpected error adding svc1: %q", err) t.Errorf("Unexpected error adding svc1: %q", err)
} }
sg, err = az.reconcileSecurityGroup(testClusterName, &svc2, to.StringPtr(svc2.Spec.LoadBalancerIP), true) sg, err = az.reconcileSecurityGroup(testClusterName, &svc2, pointer.String(svc2.Spec.LoadBalancerIP), true)
if err != nil { if err != nil {
t.Errorf("Unexpected error adding svc2: %q", err) t.Errorf("Unexpected error adding svc2: %q", err)
} }
@ -2412,12 +2412,12 @@ func TestIfServicesSpecifySharedRuleButDifferentProtocolsThenSeparateRulesAreCre
sg := getTestSecurityGroup(az) sg := getTestSecurityGroup(az)
setMockSecurityGroup(az, ctrl, sg) setMockSecurityGroup(az, ctrl, sg)
_, err := az.reconcileSecurityGroup(testClusterName, &svc1, to.StringPtr(svc1.Spec.LoadBalancerIP), true) _, err := az.reconcileSecurityGroup(testClusterName, &svc1, pointer.String(svc1.Spec.LoadBalancerIP), true)
if err != nil { if err != nil {
t.Errorf("Unexpected error adding svc1: %q", err) t.Errorf("Unexpected error adding svc1: %q", err)
} }
sg, err = az.reconcileSecurityGroup(testClusterName, &svc2, to.StringPtr(svc2.Spec.LoadBalancerIP), true) sg, err = az.reconcileSecurityGroup(testClusterName, &svc2, pointer.String(svc2.Spec.LoadBalancerIP), true)
if err != nil { if err != nil {
t.Errorf("Unexpected error adding svc2: %q", err) t.Errorf("Unexpected error adding svc2: %q", err)
} }
@ -2484,12 +2484,12 @@ func TestIfServicesSpecifySharedRuleButDifferentSourceAddressesThenSeparateRules
sg := getTestSecurityGroup(az) sg := getTestSecurityGroup(az)
setMockSecurityGroup(az, ctrl, sg) setMockSecurityGroup(az, ctrl, sg)
_, err := az.reconcileSecurityGroup(testClusterName, &svc1, to.StringPtr(svc1.Spec.LoadBalancerIP), true) _, err := az.reconcileSecurityGroup(testClusterName, &svc1, pointer.String(svc1.Spec.LoadBalancerIP), true)
if err != nil { if err != nil {
t.Errorf("Unexpected error adding svc1: %q", err) t.Errorf("Unexpected error adding svc1: %q", err)
} }
sg, err = az.reconcileSecurityGroup(testClusterName, &svc2, to.StringPtr(svc2.Spec.LoadBalancerIP), true) sg, err = az.reconcileSecurityGroup(testClusterName, &svc2, pointer.String(svc2.Spec.LoadBalancerIP), true)
if err != nil { if err != nil {
t.Errorf("Unexpected error adding svc2: %q", err) t.Errorf("Unexpected error adding svc2: %q", err)
} }
@ -2560,17 +2560,17 @@ func TestIfServicesSpecifySharedRuleButSomeAreOnDifferentPortsThenRulesAreSepara
sg := getTestSecurityGroup(az) sg := getTestSecurityGroup(az)
setMockSecurityGroup(az, ctrl, sg) setMockSecurityGroup(az, ctrl, sg)
_, err := az.reconcileSecurityGroup(testClusterName, &svc1, to.StringPtr(svc1.Spec.LoadBalancerIP), true) _, err := az.reconcileSecurityGroup(testClusterName, &svc1, pointer.String(svc1.Spec.LoadBalancerIP), true)
if err != nil { if err != nil {
t.Errorf("Unexpected error adding svc1: %q", err) t.Errorf("Unexpected error adding svc1: %q", err)
} }
_, err = az.reconcileSecurityGroup(testClusterName, &svc2, to.StringPtr(svc2.Spec.LoadBalancerIP), true) _, err = az.reconcileSecurityGroup(testClusterName, &svc2, pointer.String(svc2.Spec.LoadBalancerIP), true)
if err != nil { if err != nil {
t.Errorf("Unexpected error adding svc2: %q", err) t.Errorf("Unexpected error adding svc2: %q", err)
} }
sg, err = az.reconcileSecurityGroup(testClusterName, &svc3, to.StringPtr(svc3.Spec.LoadBalancerIP), true) sg, err = az.reconcileSecurityGroup(testClusterName, &svc3, pointer.String(svc3.Spec.LoadBalancerIP), true)
if err != nil { if err != nil {
t.Errorf("Unexpected error adding svc3: %q", err) t.Errorf("Unexpected error adding svc3: %q", err)
} }
@ -2658,19 +2658,19 @@ func TestIfServiceSpecifiesSharedRuleAndServiceIsDeletedThenTheServicesPortAndAd
sg := getTestSecurityGroup(az) sg := getTestSecurityGroup(az)
setMockSecurityGroup(az, ctrl, sg) setMockSecurityGroup(az, ctrl, sg)
_, err := az.reconcileSecurityGroup(testClusterName, &svc1, to.StringPtr(svc1.Spec.LoadBalancerIP), true) _, err := az.reconcileSecurityGroup(testClusterName, &svc1, pointer.String(svc1.Spec.LoadBalancerIP), true)
if err != nil { if err != nil {
t.Errorf("Unexpected error adding svc1: %q", err) t.Errorf("Unexpected error adding svc1: %q", err)
} }
sg, err = az.reconcileSecurityGroup(testClusterName, &svc2, to.StringPtr(svc2.Spec.LoadBalancerIP), true) sg, err = az.reconcileSecurityGroup(testClusterName, &svc2, pointer.String(svc2.Spec.LoadBalancerIP), true)
if err != nil { if err != nil {
t.Errorf("Unexpected error adding svc2: %q", err) t.Errorf("Unexpected error adding svc2: %q", err)
} }
validateSecurityGroup(t, sg, svc1, svc2) validateSecurityGroup(t, sg, svc1, svc2)
sg, err = az.reconcileSecurityGroup(testClusterName, &svc1, to.StringPtr(svc1.Spec.LoadBalancerIP), false) sg, err = az.reconcileSecurityGroup(testClusterName, &svc1, pointer.String(svc1.Spec.LoadBalancerIP), false)
if err != nil { if err != nil {
t.Errorf("Unexpected error removing svc1: %q", err) t.Errorf("Unexpected error removing svc1: %q", err)
} }
@ -2721,24 +2721,24 @@ func TestIfSomeServicesShareARuleAndOneIsDeletedItIsRemovedFromTheRightRule(t *t
sg := getTestSecurityGroup(az) sg := getTestSecurityGroup(az)
setMockSecurityGroup(az, ctrl, sg) setMockSecurityGroup(az, ctrl, sg)
_, err := az.reconcileSecurityGroup(testClusterName, &svc1, to.StringPtr(svc1.Spec.LoadBalancerIP), true) _, err := az.reconcileSecurityGroup(testClusterName, &svc1, pointer.String(svc1.Spec.LoadBalancerIP), true)
if err != nil { if err != nil {
t.Errorf("Unexpected error adding svc1: %q", err) t.Errorf("Unexpected error adding svc1: %q", err)
} }
_, err = az.reconcileSecurityGroup(testClusterName, &svc2, to.StringPtr(svc2.Spec.LoadBalancerIP), true) _, err = az.reconcileSecurityGroup(testClusterName, &svc2, pointer.String(svc2.Spec.LoadBalancerIP), true)
if err != nil { if err != nil {
t.Errorf("Unexpected error adding svc2: %q", err) t.Errorf("Unexpected error adding svc2: %q", err)
} }
sg, err = az.reconcileSecurityGroup(testClusterName, &svc3, to.StringPtr(svc3.Spec.LoadBalancerIP), true) sg, err = az.reconcileSecurityGroup(testClusterName, &svc3, pointer.String(svc3.Spec.LoadBalancerIP), true)
if err != nil { if err != nil {
t.Errorf("Unexpected error adding svc3: %q", err) t.Errorf("Unexpected error adding svc3: %q", err)
} }
validateSecurityGroup(t, sg, svc1, svc2, svc3) validateSecurityGroup(t, sg, svc1, svc2, svc3)
sg, err = az.reconcileSecurityGroup(testClusterName, &svc1, to.StringPtr(svc1.Spec.LoadBalancerIP), false) sg, err = az.reconcileSecurityGroup(testClusterName, &svc1, pointer.String(svc1.Spec.LoadBalancerIP), false)
if err != nil { if err != nil {
t.Errorf("Unexpected error removing svc1: %q", err) t.Errorf("Unexpected error removing svc1: %q", err)
} }
@ -2831,29 +2831,29 @@ func TestIfServiceSpecifiesSharedRuleAndLastServiceIsDeletedThenRuleIsDeleted(t
sg := getTestSecurityGroup(az) sg := getTestSecurityGroup(az)
setMockSecurityGroup(az, ctrl, sg) setMockSecurityGroup(az, ctrl, sg)
_, err := az.reconcileSecurityGroup(testClusterName, &svc1, to.StringPtr(svc1.Spec.LoadBalancerIP), true) _, err := az.reconcileSecurityGroup(testClusterName, &svc1, pointer.String(svc1.Spec.LoadBalancerIP), true)
if err != nil { if err != nil {
t.Errorf("Unexpected error adding svc1: %q", err) t.Errorf("Unexpected error adding svc1: %q", err)
} }
_, err = az.reconcileSecurityGroup(testClusterName, &svc2, to.StringPtr(svc2.Spec.LoadBalancerIP), true) _, err = az.reconcileSecurityGroup(testClusterName, &svc2, pointer.String(svc2.Spec.LoadBalancerIP), true)
if err != nil { if err != nil {
t.Errorf("Unexpected error adding svc2: %q", err) t.Errorf("Unexpected error adding svc2: %q", err)
} }
sg, err = az.reconcileSecurityGroup(testClusterName, &svc3, to.StringPtr(svc3.Spec.LoadBalancerIP), true) sg, err = az.reconcileSecurityGroup(testClusterName, &svc3, pointer.String(svc3.Spec.LoadBalancerIP), true)
if err != nil { if err != nil {
t.Errorf("Unexpected error adding svc3: %q", err) t.Errorf("Unexpected error adding svc3: %q", err)
} }
validateSecurityGroup(t, sg, svc1, svc2, svc3) validateSecurityGroup(t, sg, svc1, svc2, svc3)
_, err = az.reconcileSecurityGroup(testClusterName, &svc1, to.StringPtr(svc1.Spec.LoadBalancerIP), false) _, err = az.reconcileSecurityGroup(testClusterName, &svc1, pointer.String(svc1.Spec.LoadBalancerIP), false)
if err != nil { if err != nil {
t.Errorf("Unexpected error removing svc1: %q", err) t.Errorf("Unexpected error removing svc1: %q", err)
} }
sg, err = az.reconcileSecurityGroup(testClusterName, &svc3, to.StringPtr(svc3.Spec.LoadBalancerIP), false) sg, err = az.reconcileSecurityGroup(testClusterName, &svc3, pointer.String(svc3.Spec.LoadBalancerIP), false)
if err != nil { if err != nil {
t.Errorf("Unexpected error removing svc3: %q", err) t.Errorf("Unexpected error removing svc3: %q", err)
} }
@ -2924,27 +2924,27 @@ func TestCanCombineSharedAndPrivateRulesInSameGroup(t *testing.T) {
sg := getTestSecurityGroup(az) sg := getTestSecurityGroup(az)
setMockSecurityGroup(az, ctrl, sg) setMockSecurityGroup(az, ctrl, sg)
_, err := az.reconcileSecurityGroup(testClusterName, &svc1, to.StringPtr(svc1.Spec.LoadBalancerIP), true) _, err := az.reconcileSecurityGroup(testClusterName, &svc1, pointer.String(svc1.Spec.LoadBalancerIP), true)
if err != nil { if err != nil {
t.Errorf("Unexpected error adding svc1: %q", err) t.Errorf("Unexpected error adding svc1: %q", err)
} }
_, err = az.reconcileSecurityGroup(testClusterName, &svc2, to.StringPtr(svc2.Spec.LoadBalancerIP), true) _, err = az.reconcileSecurityGroup(testClusterName, &svc2, pointer.String(svc2.Spec.LoadBalancerIP), true)
if err != nil { if err != nil {
t.Errorf("Unexpected error adding svc2: %q", err) t.Errorf("Unexpected error adding svc2: %q", err)
} }
_, err = az.reconcileSecurityGroup(testClusterName, &svc3, to.StringPtr(svc3.Spec.LoadBalancerIP), true) _, err = az.reconcileSecurityGroup(testClusterName, &svc3, pointer.String(svc3.Spec.LoadBalancerIP), true)
if err != nil { if err != nil {
t.Errorf("Unexpected error adding svc3: %q", err) t.Errorf("Unexpected error adding svc3: %q", err)
} }
_, err = az.reconcileSecurityGroup(testClusterName, &svc4, to.StringPtr(svc4.Spec.LoadBalancerIP), true) _, err = az.reconcileSecurityGroup(testClusterName, &svc4, pointer.String(svc4.Spec.LoadBalancerIP), true)
if err != nil { if err != nil {
t.Errorf("Unexpected error adding svc4: %q", err) t.Errorf("Unexpected error adding svc4: %q", err)
} }
sg, err = az.reconcileSecurityGroup(testClusterName, &svc5, to.StringPtr(svc5.Spec.LoadBalancerIP), true) sg, err = az.reconcileSecurityGroup(testClusterName, &svc5, pointer.String(svc5.Spec.LoadBalancerIP), true)
if err != nil { if err != nil {
t.Errorf("Unexpected error adding svc4: %q", err) t.Errorf("Unexpected error adding svc4: %q", err)
} }
@ -3035,12 +3035,12 @@ func TestCanCombineSharedAndPrivateRulesInSameGroup(t *testing.T) {
} }
} }
_, err = az.reconcileSecurityGroup(testClusterName, &svc1, to.StringPtr(svc1.Spec.LoadBalancerIP), false) _, err = az.reconcileSecurityGroup(testClusterName, &svc1, pointer.String(svc1.Spec.LoadBalancerIP), false)
if err != nil { if err != nil {
t.Errorf("Unexpected error removing svc1: %q", err) t.Errorf("Unexpected error removing svc1: %q", err)
} }
sg, err = az.reconcileSecurityGroup(testClusterName, &svc5, to.StringPtr(svc5.Spec.LoadBalancerIP), false) sg, err = az.reconcileSecurityGroup(testClusterName, &svc5, pointer.String(svc5.Spec.LoadBalancerIP), false)
if err != nil { if err != nil {
t.Errorf("Unexpected error removing svc5: %q", err) t.Errorf("Unexpected error removing svc5: %q", err)
} }
@ -3443,13 +3443,13 @@ func TestFindSecurityRule(t *testing.T) {
testRuleName := "test-rule" testRuleName := "test-rule"
testIP1 := "192.168.192.168" testIP1 := "192.168.192.168"
sg := network.SecurityRule{ sg := network.SecurityRule{
Name: to.StringPtr(testRuleName), Name: pointer.String(testRuleName),
SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{ SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{
Protocol: network.SecurityRuleProtocolTCP, Protocol: network.SecurityRuleProtocolTCP,
SourcePortRange: to.StringPtr("*"), SourcePortRange: pointer.String("*"),
SourceAddressPrefix: to.StringPtr("Internet"), SourceAddressPrefix: pointer.String("Internet"),
DestinationPortRange: to.StringPtr("80"), DestinationPortRange: pointer.String("80"),
DestinationAddressPrefix: to.StringPtr(testIP1), DestinationAddressPrefix: pointer.String(testIP1),
Access: network.SecurityRuleAccessAllow, Access: network.SecurityRuleAccessAllow,
Direction: network.SecurityRuleDirectionInbound, Direction: network.SecurityRuleDirectionInbound,
}, },
@ -3467,14 +3467,14 @@ func TestFindSecurityRule(t *testing.T) {
{ {
desc: "false should be returned when rule name doesn't match", desc: "false should be returned when rule name doesn't match",
testRule: network.SecurityRule{ testRule: network.SecurityRule{
Name: to.StringPtr("not-the-right-name"), Name: pointer.String("not-the-right-name"),
}, },
expected: false, expected: false,
}, },
{ {
desc: "false should be returned when protocol doesn't match", desc: "false should be returned when protocol doesn't match",
testRule: network.SecurityRule{ testRule: network.SecurityRule{
Name: to.StringPtr(testRuleName), Name: pointer.String(testRuleName),
SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{ SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{
Protocol: network.SecurityRuleProtocolUDP, Protocol: network.SecurityRuleProtocolUDP,
}, },
@ -3484,10 +3484,10 @@ func TestFindSecurityRule(t *testing.T) {
{ {
desc: "false should be returned when SourcePortRange doesn't match", desc: "false should be returned when SourcePortRange doesn't match",
testRule: network.SecurityRule{ testRule: network.SecurityRule{
Name: to.StringPtr(testRuleName), Name: pointer.String(testRuleName),
SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{ SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{
Protocol: network.SecurityRuleProtocolUDP, Protocol: network.SecurityRuleProtocolUDP,
SourcePortRange: to.StringPtr("1.2.3.4/32"), SourcePortRange: pointer.String("1.2.3.4/32"),
}, },
}, },
expected: false, expected: false,
@ -3495,11 +3495,11 @@ func TestFindSecurityRule(t *testing.T) {
{ {
desc: "false should be returned when SourceAddressPrefix doesn't match", desc: "false should be returned when SourceAddressPrefix doesn't match",
testRule: network.SecurityRule{ testRule: network.SecurityRule{
Name: to.StringPtr(testRuleName), Name: pointer.String(testRuleName),
SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{ SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{
Protocol: network.SecurityRuleProtocolUDP, Protocol: network.SecurityRuleProtocolUDP,
SourcePortRange: to.StringPtr("*"), SourcePortRange: pointer.String("*"),
SourceAddressPrefix: to.StringPtr("2.3.4.0/24"), SourceAddressPrefix: pointer.String("2.3.4.0/24"),
}, },
}, },
expected: false, expected: false,
@ -3507,12 +3507,12 @@ func TestFindSecurityRule(t *testing.T) {
{ {
desc: "false should be returned when DestinationPortRange doesn't match", desc: "false should be returned when DestinationPortRange doesn't match",
testRule: network.SecurityRule{ testRule: network.SecurityRule{
Name: to.StringPtr(testRuleName), Name: pointer.String(testRuleName),
SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{ SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{
Protocol: network.SecurityRuleProtocolUDP, Protocol: network.SecurityRuleProtocolUDP,
SourcePortRange: to.StringPtr("*"), SourcePortRange: pointer.String("*"),
SourceAddressPrefix: to.StringPtr("Internet"), SourceAddressPrefix: pointer.String("Internet"),
DestinationPortRange: to.StringPtr("443"), DestinationPortRange: pointer.String("443"),
}, },
}, },
expected: false, expected: false,
@ -3520,13 +3520,13 @@ func TestFindSecurityRule(t *testing.T) {
{ {
desc: "false should be returned when DestinationAddressPrefix doesn't match", desc: "false should be returned when DestinationAddressPrefix doesn't match",
testRule: network.SecurityRule{ testRule: network.SecurityRule{
Name: to.StringPtr(testRuleName), Name: pointer.String(testRuleName),
SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{ SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{
Protocol: network.SecurityRuleProtocolUDP, Protocol: network.SecurityRuleProtocolUDP,
SourcePortRange: to.StringPtr("*"), SourcePortRange: pointer.String("*"),
SourceAddressPrefix: to.StringPtr("Internet"), SourceAddressPrefix: pointer.String("Internet"),
DestinationPortRange: to.StringPtr("80"), DestinationPortRange: pointer.String("80"),
DestinationAddressPrefix: to.StringPtr("192.168.0.3"), DestinationAddressPrefix: pointer.String("192.168.0.3"),
}, },
}, },
expected: false, expected: false,
@ -3534,13 +3534,13 @@ func TestFindSecurityRule(t *testing.T) {
{ {
desc: "false should be returned when Access doesn't match", desc: "false should be returned when Access doesn't match",
testRule: network.SecurityRule{ testRule: network.SecurityRule{
Name: to.StringPtr(testRuleName), Name: pointer.String(testRuleName),
SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{ SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{
Protocol: network.SecurityRuleProtocolUDP, Protocol: network.SecurityRuleProtocolUDP,
SourcePortRange: to.StringPtr("*"), SourcePortRange: pointer.String("*"),
SourceAddressPrefix: to.StringPtr("Internet"), SourceAddressPrefix: pointer.String("Internet"),
DestinationPortRange: to.StringPtr("80"), DestinationPortRange: pointer.String("80"),
DestinationAddressPrefix: to.StringPtr(testIP1), DestinationAddressPrefix: pointer.String(testIP1),
Access: network.SecurityRuleAccessDeny, Access: network.SecurityRuleAccessDeny,
// Direction: network.SecurityRuleDirectionInbound, // Direction: network.SecurityRuleDirectionInbound,
}, },
@ -3550,13 +3550,13 @@ func TestFindSecurityRule(t *testing.T) {
{ {
desc: "false should be returned when Direction doesn't match", desc: "false should be returned when Direction doesn't match",
testRule: network.SecurityRule{ testRule: network.SecurityRule{
Name: to.StringPtr(testRuleName), Name: pointer.String(testRuleName),
SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{ SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{
Protocol: network.SecurityRuleProtocolUDP, Protocol: network.SecurityRuleProtocolUDP,
SourcePortRange: to.StringPtr("*"), SourcePortRange: pointer.String("*"),
SourceAddressPrefix: to.StringPtr("Internet"), SourceAddressPrefix: pointer.String("Internet"),
DestinationPortRange: to.StringPtr("80"), DestinationPortRange: pointer.String("80"),
DestinationAddressPrefix: to.StringPtr(testIP1), DestinationAddressPrefix: pointer.String(testIP1),
Access: network.SecurityRuleAccessAllow, Access: network.SecurityRuleAccessAllow,
Direction: network.SecurityRuleDirectionOutbound, Direction: network.SecurityRuleDirectionOutbound,
}, },
@ -3566,13 +3566,13 @@ func TestFindSecurityRule(t *testing.T) {
{ {
desc: "true should be returned when everything matches but protocol is in different case", desc: "true should be returned when everything matches but protocol is in different case",
testRule: network.SecurityRule{ testRule: network.SecurityRule{
Name: to.StringPtr(testRuleName), Name: pointer.String(testRuleName),
SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{ SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{
Protocol: network.SecurityRuleProtocol("TCP"), Protocol: network.SecurityRuleProtocol("TCP"),
SourcePortRange: to.StringPtr("*"), SourcePortRange: pointer.String("*"),
SourceAddressPrefix: to.StringPtr("Internet"), SourceAddressPrefix: pointer.String("Internet"),
DestinationPortRange: to.StringPtr("80"), DestinationPortRange: pointer.String("80"),
DestinationAddressPrefix: to.StringPtr(testIP1), DestinationAddressPrefix: pointer.String(testIP1),
Access: network.SecurityRuleAccessAllow, Access: network.SecurityRuleAccessAllow,
Direction: network.SecurityRuleDirectionInbound, Direction: network.SecurityRuleDirectionInbound,
}, },

View File

@ -25,9 +25,8 @@ import (
"strings" "strings"
"sync" "sync"
"github.com/Azure/go-autorest/autorest/to"
"k8s.io/klog/v2" "k8s.io/klog/v2"
"k8s.io/utils/pointer"
) )
const ( const (
@ -135,7 +134,7 @@ func parseTags(tags string) map[string]*string {
klog.Warningf("parseTags: error when parsing key-value pair %s-%s, would ignore this one", k, v) klog.Warningf("parseTags: error when parsing key-value pair %s-%s, would ignore this one", k, v)
continue continue
} }
formatted[strings.ToLower(k)] = to.StringPtr(v) formatted[strings.ToLower(k)] = pointer.String(v)
} }
return formatted return formatted
} }
@ -156,7 +155,7 @@ func reconcileTags(currentTagsOnResource, newTags map[string]*string) (reconcile
if !found { if !found {
currentTagsOnResource[k] = v currentTagsOnResource[k] = v
changed = true changed = true
} else if !strings.EqualFold(to.String(v), to.String(currentTagsOnResource[key])) { } else if !strings.EqualFold(pointer.StringDeref(v, ""), pointer.StringDeref(currentTagsOnResource[key], "")) {
currentTagsOnResource[key] = v currentTagsOnResource[key] = v
changed = true changed = true
} }

View File

@ -24,8 +24,8 @@ import (
"testing" "testing"
"time" "time"
"github.com/Azure/go-autorest/autorest/to"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"k8s.io/utils/pointer"
) )
func TestSimpleLockEntry(t *testing.T) { func TestSimpleLockEntry(t *testing.T) {
@ -164,46 +164,46 @@ func TestReconcileTags(t *testing.T) {
{ {
description: "reconcileTags should add missing tags and update existing tags", description: "reconcileTags should add missing tags and update existing tags",
currentTagsOnResource: map[string]*string{ currentTagsOnResource: map[string]*string{
"a": to.StringPtr("b"), "a": pointer.String("b"),
}, },
newTags: map[string]*string{ newTags: map[string]*string{
"a": to.StringPtr("c"), "a": pointer.String("c"),
"b": to.StringPtr("d"), "b": pointer.String("d"),
}, },
expectedTags: map[string]*string{ expectedTags: map[string]*string{
"a": to.StringPtr("c"), "a": pointer.String("c"),
"b": to.StringPtr("d"), "b": pointer.String("d"),
}, },
expectedChanged: true, expectedChanged: true,
}, },
{ {
description: "reconcileTags should ignore the case of keys when comparing", description: "reconcileTags should ignore the case of keys when comparing",
currentTagsOnResource: map[string]*string{ currentTagsOnResource: map[string]*string{
"A": to.StringPtr("b"), "A": pointer.String("b"),
"c": to.StringPtr("d"), "c": pointer.String("d"),
}, },
newTags: map[string]*string{ newTags: map[string]*string{
"a": to.StringPtr("b"), "a": pointer.String("b"),
"C": to.StringPtr("d"), "C": pointer.String("d"),
}, },
expectedTags: map[string]*string{ expectedTags: map[string]*string{
"A": to.StringPtr("b"), "A": pointer.String("b"),
"c": to.StringPtr("d"), "c": pointer.String("d"),
}, },
}, },
{ {
description: "reconcileTags should ignore the case of values when comparing", description: "reconcileTags should ignore the case of values when comparing",
currentTagsOnResource: map[string]*string{ currentTagsOnResource: map[string]*string{
"A": to.StringPtr("b"), "A": pointer.String("b"),
"c": to.StringPtr("d"), "c": pointer.String("d"),
}, },
newTags: map[string]*string{ newTags: map[string]*string{
"a": to.StringPtr("B"), "a": pointer.String("B"),
"C": to.StringPtr("D"), "C": pointer.String("D"),
}, },
expectedTags: map[string]*string{ expectedTags: map[string]*string{
"A": to.StringPtr("b"), "A": pointer.String("b"),
"c": to.StringPtr("d"), "c": pointer.String("d"),
}, },
}, },
} { } {

View File

@ -30,7 +30,6 @@ import (
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute"
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network"
"github.com/Azure/go-autorest/autorest/to"
v1 "k8s.io/api/core/v1" v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/types"
@ -40,6 +39,7 @@ import (
azcache "k8s.io/legacy-cloud-providers/azure/cache" azcache "k8s.io/legacy-cloud-providers/azure/cache"
"k8s.io/legacy-cloud-providers/azure/metrics" "k8s.io/legacy-cloud-providers/azure/metrics"
utilnet "k8s.io/utils/net" utilnet "k8s.io/utils/net"
"k8s.io/utils/pointer"
) )
var ( var (
@ -233,7 +233,7 @@ func (ss *scaleSet) GetPowerStatusByNodeName(name string) (powerState string, er
if vm.InstanceView != nil && vm.InstanceView.Statuses != nil { if vm.InstanceView != nil && vm.InstanceView.Statuses != nil {
statuses := *vm.InstanceView.Statuses statuses := *vm.InstanceView.Statuses
for _, status := range statuses { for _, status := range statuses {
state := to.String(status.Code) state := pointer.StringDeref(status.Code, "")
if strings.HasPrefix(state, vmPowerStatePrefix) { if strings.HasPrefix(state, vmPowerStatePrefix) {
return strings.TrimPrefix(state, vmPowerStatePrefix), nil return strings.TrimPrefix(state, vmPowerStatePrefix), nil
} }
@ -266,7 +266,7 @@ func (ss *scaleSet) GetProvisioningStateByNodeName(name string) (provisioningSta
return provisioningState, nil return provisioningState, nil
} }
return to.String(vm.VirtualMachineScaleSetVMProperties.ProvisioningState), nil return pointer.StringDeref(vm.VirtualMachineScaleSetVMProperties.ProvisioningState, ""), nil
} }
// getCachedVirtualMachineByInstanceID gets scaleSetVMInfo from cache. // getCachedVirtualMachineByInstanceID gets scaleSetVMInfo from cache.
@ -455,7 +455,7 @@ func (ss *scaleSet) GetZoneByNodeName(name string) (cloudprovider.Zone, error) {
return cloudprovider.Zone{}, fmt.Errorf("failed to parse zone %q: %v", zones, err) return cloudprovider.Zone{}, fmt.Errorf("failed to parse zone %q: %v", zones, err)
} }
failureDomain = ss.makeZone(to.String(vm.Location), zoneID) failureDomain = ss.makeZone(pointer.StringDeref(vm.Location, ""), zoneID)
} else if vm.InstanceView != nil && vm.InstanceView.PlatformFaultDomain != nil { } else if vm.InstanceView != nil && vm.InstanceView.PlatformFaultDomain != nil {
// Availability zone is not used for the node, falling back to fault domain. // Availability zone is not used for the node, falling back to fault domain.
failureDomain = strconv.Itoa(int(*vm.InstanceView.PlatformFaultDomain)) failureDomain = strconv.Itoa(int(*vm.InstanceView.PlatformFaultDomain))
@ -468,7 +468,7 @@ func (ss *scaleSet) GetZoneByNodeName(name string) (cloudprovider.Zone, error) {
return cloudprovider.Zone{ return cloudprovider.Zone{
FailureDomain: strings.ToLower(failureDomain), FailureDomain: strings.ToLower(failureDomain),
Region: strings.ToLower(to.String(vm.Location)), Region: strings.ToLower(pointer.StringDeref(vm.Location, "")),
}, nil }, nil
} }
@ -565,7 +565,7 @@ func (ss *scaleSet) GetPrivateIPsByNodeName(nodeName string) ([]string, error) {
// This returns the full identifier of the primary NIC for the given VM. // This returns the full identifier of the primary NIC for the given VM.
func (ss *scaleSet) getPrimaryInterfaceID(machine compute.VirtualMachineScaleSetVM) (string, error) { func (ss *scaleSet) getPrimaryInterfaceID(machine compute.VirtualMachineScaleSetVM) (string, error) {
if machine.NetworkProfile == nil || machine.NetworkProfile.NetworkInterfaces == nil { if machine.NetworkProfile == nil || machine.NetworkProfile.NetworkInterfaces == nil {
return "", fmt.Errorf("failed to find the network interfaces for vm %s", to.String(machine.Name)) return "", fmt.Errorf("failed to find the network interfaces for vm %s", pointer.StringDeref(machine.Name, ""))
} }
if len(*machine.NetworkProfile.NetworkInterfaces) == 1 { if len(*machine.NetworkProfile.NetworkInterfaces) == 1 {
@ -573,12 +573,12 @@ func (ss *scaleSet) getPrimaryInterfaceID(machine compute.VirtualMachineScaleSet
} }
for _, ref := range *machine.NetworkProfile.NetworkInterfaces { for _, ref := range *machine.NetworkProfile.NetworkInterfaces {
if to.Bool(ref.Primary) { if pointer.BoolDeref(ref.Primary, false) {
return *ref.ID, nil return *ref.ID, nil
} }
} }
return "", fmt.Errorf("failed to find a primary nic for the vm. vmname=%q", to.String(machine.Name)) return "", fmt.Errorf("failed to find a primary nic for the vm. vmname=%q", pointer.StringDeref(machine.Name, ""))
} }
// getVmssMachineID returns the full identifier of a vmss virtual machine. // getVmssMachineID returns the full identifier of a vmss virtual machine.
@ -642,7 +642,7 @@ func (ss *scaleSet) listScaleSets(resourceGroup string) ([]string, error) {
ssNames := make([]string, 0) ssNames := make([]string, 0)
for _, vmss := range allScaleSets { for _, vmss := range allScaleSets {
name := *vmss.Name name := *vmss.Name
if vmss.Sku != nil && to.Int64(vmss.Sku.Capacity) == 0 { if vmss.Sku != nil && pointer.Int64Deref(vmss.Sku.Capacity, 0) == 0 {
klog.V(3).Infof("Capacity of VMSS %q is 0, skipping", name) klog.V(3).Infof("Capacity of VMSS %q is 0, skipping", name)
continue continue
} }
@ -1069,7 +1069,7 @@ func (ss *scaleSet) EnsureHostInPool(service *v1.Service, nodeName types.NodeNam
// Compose a new vmssVM with added backendPoolID. // Compose a new vmssVM with added backendPoolID.
newBackendPools = append(newBackendPools, newBackendPools = append(newBackendPools,
compute.SubResource{ compute.SubResource{
ID: to.StringPtr(backendPoolID), ID: pointer.String(backendPoolID),
}) })
primaryIPConfiguration.LoadBalancerBackendAddressPools = &newBackendPools primaryIPConfiguration.LoadBalancerBackendAddressPools = &newBackendPools
newVM := &compute.VirtualMachineScaleSetVM{ newVM := &compute.VirtualMachineScaleSetVM{
@ -1215,7 +1215,7 @@ func (ss *scaleSet) ensureVMSSInPool(service *v1.Service, nodes []*v1.Node, back
// Compose a new vmss with added backendPoolID. // Compose a new vmss with added backendPoolID.
loadBalancerBackendAddressPools = append(loadBalancerBackendAddressPools, loadBalancerBackendAddressPools = append(loadBalancerBackendAddressPools,
compute.SubResource{ compute.SubResource{
ID: to.StringPtr(backendPoolID), ID: pointer.String(backendPoolID),
}) })
primaryIPConfig.LoadBalancerBackendAddressPools = &loadBalancerBackendAddressPools primaryIPConfig.LoadBalancerBackendAddressPools = &loadBalancerBackendAddressPools
newVMSS := compute.VirtualMachineScaleSet{ newVMSS := compute.VirtualMachineScaleSet{

View File

@ -27,11 +27,11 @@ import (
"time" "time"
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute"
"github.com/Azure/go-autorest/autorest/to"
"k8s.io/apimachinery/pkg/util/sets" "k8s.io/apimachinery/pkg/util/sets"
"k8s.io/klog/v2" "k8s.io/klog/v2"
azcache "k8s.io/legacy-cloud-providers/azure/cache" azcache "k8s.io/legacy-cloud-providers/azure/cache"
"k8s.io/utils/pointer"
) )
var ( var (
@ -207,13 +207,13 @@ func (ss *scaleSet) newVMSSVirtualMachinesCache(resourceGroupName, vmssName, cac
vmssVMCacheEntry := &vmssVirtualMachinesEntry{ vmssVMCacheEntry := &vmssVirtualMachinesEntry{
resourceGroup: resourceGroupName, resourceGroup: resourceGroupName,
vmssName: vmssName, vmssName: vmssName,
instanceID: to.String(vm.InstanceID), instanceID: pointer.StringDeref(vm.InstanceID, ""),
virtualMachine: &vm, virtualMachine: &vm,
lastUpdate: time.Now().UTC(), lastUpdate: time.Now().UTC(),
} }
// set cache entry to nil when the VM is under deleting. // set cache entry to nil when the VM is under deleting.
if vm.VirtualMachineScaleSetVMProperties != nil && if vm.VirtualMachineScaleSetVMProperties != nil &&
strings.EqualFold(to.String(vm.VirtualMachineScaleSetVMProperties.ProvisioningState), string(compute.ProvisioningStateDeleting)) { strings.EqualFold(pointer.StringDeref(vm.VirtualMachineScaleSetVMProperties.ProvisioningState, ""), string(compute.ProvisioningStateDeleting)) {
klog.V(4).Infof("VMSS virtualMachine %q is under deleting, setting its cache to nil", computerName) klog.V(4).Infof("VMSS virtualMachine %q is under deleting, setting its cache to nil", computerName)
vmssVMCacheEntry.virtualMachine = nil vmssVMCacheEntry.virtualMachine = nil
} }

View File

@ -24,7 +24,6 @@ import (
"testing" "testing"
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute"
"github.com/Azure/go-autorest/autorest/to"
"github.com/golang/mock/gomock" "github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -32,6 +31,7 @@ import (
azcache "k8s.io/legacy-cloud-providers/azure/cache" azcache "k8s.io/legacy-cloud-providers/azure/cache"
"k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient" "k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient"
"k8s.io/legacy-cloud-providers/azure/clients/vmssvmclient/mockvmssvmclient" "k8s.io/legacy-cloud-providers/azure/clients/vmssvmclient/mockvmssvmclient"
"k8s.io/utils/pointer"
) )
func TestExtractVmssVMName(t *testing.T) { func TestExtractVmssVMName(t *testing.T) {
@ -101,17 +101,17 @@ func TestVMSSVMCache(t *testing.T) {
// validate getting VMSS VM via cache. // validate getting VMSS VM via cache.
for i := range expectedVMs { for i := range expectedVMs {
vm := expectedVMs[i] vm := expectedVMs[i]
vmName := to.String(vm.OsProfile.ComputerName) vmName := pointer.StringDeref(vm.OsProfile.ComputerName, "")
ssName, instanceID, realVM, err := ss.getVmssVM(vmName, azcache.CacheReadTypeDefault) ssName, instanceID, realVM, err := ss.getVmssVM(vmName, azcache.CacheReadTypeDefault)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, "vmss", ssName) assert.Equal(t, "vmss", ssName)
assert.Equal(t, to.String(vm.InstanceID), instanceID) assert.Equal(t, pointer.StringDeref(vm.InstanceID, ""), instanceID)
assert.Equal(t, &vm, realVM) assert.Equal(t, &vm, realVM)
} }
// validate deleteCacheForNode(). // validate deleteCacheForNode().
vm := expectedVMs[0] vm := expectedVMs[0]
vmName := to.String(vm.OsProfile.ComputerName) vmName := pointer.StringDeref(vm.OsProfile.ComputerName, "")
err = ss.deleteCacheForNode(vmName) err = ss.deleteCacheForNode(vmName)
assert.NoError(t, err) assert.NoError(t, err)
@ -128,7 +128,7 @@ func TestVMSSVMCache(t *testing.T) {
ssName, instanceID, realVM, err := ss.getVmssVM(vmName, azcache.CacheReadTypeDefault) ssName, instanceID, realVM, err := ss.getVmssVM(vmName, azcache.CacheReadTypeDefault)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, "vmss", ssName) assert.Equal(t, "vmss", ssName)
assert.Equal(t, to.String(vm.InstanceID), instanceID) assert.Equal(t, pointer.StringDeref(vm.InstanceID, ""), instanceID)
assert.Equal(t, &vm, realVM) assert.Equal(t, &vm, realVM)
} }
@ -157,8 +157,8 @@ func TestVMSSVMCacheWithDeletingNodes(t *testing.T) {
for i := range expectedVMs { for i := range expectedVMs {
vm := expectedVMs[i] vm := expectedVMs[i]
vmName := to.String(vm.OsProfile.ComputerName) vmName := pointer.StringDeref(vm.OsProfile.ComputerName, "")
assert.Equal(t, vm.ProvisioningState, to.StringPtr(string(compute.ProvisioningStateDeleting))) assert.Equal(t, vm.ProvisioningState, pointer.String(string(compute.ProvisioningStateDeleting)))
ssName, instanceID, realVM, err := ss.getVmssVM(vmName, azcache.CacheReadTypeDefault) ssName, instanceID, realVM, err := ss.getVmssVM(vmName, azcache.CacheReadTypeDefault)
assert.Nil(t, realVM) assert.Nil(t, realVM)

View File

@ -37,10 +37,10 @@ import (
"k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient" "k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient"
"k8s.io/legacy-cloud-providers/azure/clients/vmssvmclient/mockvmssvmclient" "k8s.io/legacy-cloud-providers/azure/clients/vmssvmclient/mockvmssvmclient"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute"
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network"
"github.com/Azure/go-autorest/autorest/to"
"github.com/golang/mock/gomock" "github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -72,7 +72,7 @@ func newTestScaleSetWithState(ctrl *gomock.Controller) (*scaleSet, error) {
func buildTestVMSSWithLB(name, namePrefix string, lbBackendpoolIDs []string, ipv6 bool) compute.VirtualMachineScaleSet { func buildTestVMSSWithLB(name, namePrefix string, lbBackendpoolIDs []string, ipv6 bool) compute.VirtualMachineScaleSet {
lbBackendpools := make([]compute.SubResource, 0) lbBackendpools := make([]compute.SubResource, 0)
for _, id := range lbBackendpoolIDs { for _, id := range lbBackendpoolIDs {
lbBackendpools = append(lbBackendpools, compute.SubResource{ID: to.StringPtr(id)}) lbBackendpools = append(lbBackendpools, compute.SubResource{ID: pointer.String(id)})
} }
ipConfig := []compute.VirtualMachineScaleSetIPConfiguration{ ipConfig := []compute.VirtualMachineScaleSetIPConfiguration{
{ {
@ -93,7 +93,7 @@ func buildTestVMSSWithLB(name, namePrefix string, lbBackendpoolIDs []string, ipv
expectedVMSS := compute.VirtualMachineScaleSet{ expectedVMSS := compute.VirtualMachineScaleSet{
Name: &name, Name: &name,
VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{ VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{
ProvisioningState: to.StringPtr("Running"), ProvisioningState: pointer.String("Running"),
VirtualMachineProfile: &compute.VirtualMachineScaleSetVMProfile{ VirtualMachineProfile: &compute.VirtualMachineScaleSetVMProfile{
OsProfile: &compute.VirtualMachineScaleSetOSProfile{ OsProfile: &compute.VirtualMachineScaleSetOSProfile{
ComputerNamePrefix: &namePrefix, ComputerNamePrefix: &namePrefix,
@ -102,7 +102,7 @@ func buildTestVMSSWithLB(name, namePrefix string, lbBackendpoolIDs []string, ipv
NetworkInterfaceConfigurations: &[]compute.VirtualMachineScaleSetNetworkConfiguration{ NetworkInterfaceConfigurations: &[]compute.VirtualMachineScaleSetNetworkConfiguration{
{ {
VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{
Primary: to.BoolPtr(true), Primary: pointer.Bool(true),
IPConfigurations: &ipConfig, IPConfigurations: &ipConfig,
}, },
}, },
@ -146,23 +146,23 @@ func buildTestVirtualMachineEnv(ss *Cloud, scaleSetName, zone string, faultDomai
{ {
ID: &interfaceID, ID: &interfaceID,
NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{ NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{
Primary: to.BoolPtr(true), Primary: pointer.Bool(true),
}, },
}, },
} }
ipConfigurations := []compute.VirtualMachineScaleSetIPConfiguration{ ipConfigurations := []compute.VirtualMachineScaleSetIPConfiguration{
{ {
Name: to.StringPtr("ipconfig1"), Name: pointer.String("ipconfig1"),
VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{
Primary: to.BoolPtr(true), Primary: pointer.Bool(true),
LoadBalancerBackendAddressPools: &[]compute.SubResource{{ID: to.StringPtr(testLBBackendpoolID0)}}, LoadBalancerBackendAddressPools: &[]compute.SubResource{{ID: pointer.String(testLBBackendpoolID0)}},
}, },
}, },
} }
networkConfigurations := []compute.VirtualMachineScaleSetNetworkConfiguration{ networkConfigurations := []compute.VirtualMachineScaleSetNetworkConfiguration{
{ {
Name: to.StringPtr("ipconfig1"), Name: pointer.String("ipconfig1"),
ID: to.StringPtr("fakeNetworkConfiguration"), ID: pointer.String("fakeNetworkConfiguration"),
VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{
IPConfigurations: &ipConfigurations, IPConfigurations: &ipConfigurations,
}, },
@ -170,15 +170,15 @@ func buildTestVirtualMachineEnv(ss *Cloud, scaleSetName, zone string, faultDomai
} }
if isIPv6 { if isIPv6 {
networkConfigurations = append(networkConfigurations, compute.VirtualMachineScaleSetNetworkConfiguration{ networkConfigurations = append(networkConfigurations, compute.VirtualMachineScaleSetNetworkConfiguration{
Name: to.StringPtr("ipconfig1v6"), Name: pointer.String("ipconfig1v6"),
ID: to.StringPtr("fakeNetworkConfigurationIPv6"), ID: pointer.String("fakeNetworkConfigurationIPv6"),
VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{
IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{
{ {
Name: to.StringPtr("ipconfig1"), Name: pointer.String("ipconfig1"),
VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{
Primary: to.BoolPtr(false), Primary: pointer.Bool(false),
LoadBalancerBackendAddressPools: &[]compute.SubResource{{ID: to.StringPtr(testLBBackendpoolID0)}}, LoadBalancerBackendAddressPools: &[]compute.SubResource{{ID: pointer.String(testLBBackendpoolID0)}},
PrivateIPAddressVersion: compute.IPv6, PrivateIPAddressVersion: compute.IPv6,
}, },
}, },
@ -189,7 +189,7 @@ func buildTestVirtualMachineEnv(ss *Cloud, scaleSetName, zone string, faultDomai
vmssVM := compute.VirtualMachineScaleSetVM{ vmssVM := compute.VirtualMachineScaleSetVM{
VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{
ProvisioningState: to.StringPtr(state), ProvisioningState: pointer.String(state),
OsProfile: &compute.OSProfile{ OsProfile: &compute.OSProfile{
ComputerName: &nodeName, ComputerName: &nodeName,
}, },
@ -202,7 +202,7 @@ func buildTestVirtualMachineEnv(ss *Cloud, scaleSetName, zone string, faultDomai
InstanceView: &compute.VirtualMachineScaleSetVMInstanceView{ InstanceView: &compute.VirtualMachineScaleSetVMInstanceView{
PlatformFaultDomain: &faultDomain, PlatformFaultDomain: &faultDomain,
Statuses: &[]compute.InstanceViewStatus{ Statuses: &[]compute.InstanceViewStatus{
{Code: to.StringPtr(testVMPowerState)}, {Code: pointer.String(testVMPowerState)},
}, },
}, },
}, },
@ -210,7 +210,7 @@ func buildTestVirtualMachineEnv(ss *Cloud, scaleSetName, zone string, faultDomai
InstanceID: &instanceID, InstanceID: &instanceID,
Name: &vmName, Name: &vmName,
Location: &ss.Location, Location: &ss.Location,
Sku: &compute.Sku{Name: to.StringPtr("sku")}, Sku: &compute.Sku{Name: pointer.String("sku")},
} }
if zone != "" { if zone != "" {
zones := []string{zone} zones := []string{zone}
@ -219,16 +219,16 @@ func buildTestVirtualMachineEnv(ss *Cloud, scaleSetName, zone string, faultDomai
// set interfaces. // set interfaces.
expectedInterface = network.Interface{ expectedInterface = network.Interface{
Name: to.StringPtr("nic"), Name: pointer.String("nic"),
ID: &interfaceID, ID: &interfaceID,
InterfacePropertiesFormat: &network.InterfacePropertiesFormat{ InterfacePropertiesFormat: &network.InterfacePropertiesFormat{
IPConfigurations: &[]network.InterfaceIPConfiguration{ IPConfigurations: &[]network.InterfaceIPConfiguration{
{ {
InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{
Primary: to.BoolPtr(true), Primary: pointer.Bool(true),
PrivateIPAddress: to.StringPtr(fakePrivateIP), PrivateIPAddress: pointer.String(fakePrivateIP),
PublicIPAddress: &network.PublicIPAddress{ PublicIPAddress: &network.PublicIPAddress{
ID: to.StringPtr(publicAddressID), ID: pointer.String(publicAddressID),
}, },
}, },
}, },
@ -238,9 +238,9 @@ func buildTestVirtualMachineEnv(ss *Cloud, scaleSetName, zone string, faultDomai
// set public IPs. // set public IPs.
expectedPIP = network.PublicIPAddress{ expectedPIP = network.PublicIPAddress{
ID: to.StringPtr(publicAddressID), ID: pointer.String(publicAddressID),
PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{
IPAddress: to.StringPtr(fakePublicIP), IPAddress: pointer.String(fakePublicIP),
}, },
} }
@ -721,7 +721,7 @@ func TestGetVMSS(t *testing.T) {
ss.cloud.VirtualMachineScaleSetsClient = mockVMSSClient ss.cloud.VirtualMachineScaleSetsClient = mockVMSSClient
expected := compute.VirtualMachineScaleSet{ expected := compute.VirtualMachineScaleSet{
Name: to.StringPtr(test.existedVMSSName), Name: pointer.String(test.existedVMSSName),
VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{ VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{
VirtualMachineProfile: &compute.VirtualMachineScaleSetVMProfile{}, VirtualMachineProfile: &compute.VirtualMachineScaleSetVMProfile{},
}, },
@ -873,7 +873,7 @@ func TestGetProvisioningStateByNodeName(t *testing.T) {
expectedVMSSVMs, _, _ := buildTestVirtualMachineEnv(ss.cloud, testVMSSName, "", 0, test.vmList, "", false) expectedVMSSVMs, _, _ := buildTestVirtualMachineEnv(ss.cloud, testVMSSName, "", 0, test.vmList, "", false)
mockVMSSVMClient := ss.cloud.VirtualMachineScaleSetVMsClient.(*mockvmssvmclient.MockInterface) mockVMSSVMClient := ss.cloud.VirtualMachineScaleSetVMsClient.(*mockvmssvmclient.MockInterface)
if test.provisioningState != "" { if test.provisioningState != "" {
expectedVMSSVMs[0].ProvisioningState = to.StringPtr(test.provisioningState) expectedVMSSVMs[0].ProvisioningState = pointer.String(test.provisioningState)
} else { } else {
expectedVMSSVMs[0].ProvisioningState = nil expectedVMSSVMs[0].ProvisioningState = nil
} }
@ -910,7 +910,7 @@ func TestGetVmssVMByInstanceID(t *testing.T) {
assert.NoError(t, err, "unexpected error when creating test VMSS") assert.NoError(t, err, "unexpected error when creating test VMSS")
expectedVMSS := compute.VirtualMachineScaleSet{ expectedVMSS := compute.VirtualMachineScaleSet{
Name: to.StringPtr(testVMSSName), Name: pointer.String(testVMSSName),
VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{ VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{
VirtualMachineProfile: &compute.VirtualMachineScaleSetVMProfile{}, VirtualMachineProfile: &compute.VirtualMachineScaleSetVMProfile{},
}, },
@ -988,12 +988,12 @@ func TestGetPrimaryInterfaceID(t *testing.T) {
description: "GetPrimaryInterfaceID should return the ID of the primary NIC on the VMSS VM", description: "GetPrimaryInterfaceID should return the ID of the primary NIC on the VMSS VM",
existedInterfaces: []compute.NetworkInterfaceReference{ existedInterfaces: []compute.NetworkInterfaceReference{
{ {
ID: to.StringPtr("1"), ID: pointer.String("1"),
NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{ NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{
Primary: to.BoolPtr(true), Primary: pointer.Bool(true),
}, },
}, },
{ID: to.StringPtr("2")}, {ID: pointer.String("2")},
}, },
expectedID: "1", expectedID: "1",
}, },
@ -1001,15 +1001,15 @@ func TestGetPrimaryInterfaceID(t *testing.T) {
description: "GetPrimaryInterfaceID should report an error if there's no primary NIC on the VMSS VM", description: "GetPrimaryInterfaceID should report an error if there's no primary NIC on the VMSS VM",
existedInterfaces: []compute.NetworkInterfaceReference{ existedInterfaces: []compute.NetworkInterfaceReference{
{ {
ID: to.StringPtr("1"), ID: pointer.String("1"),
NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{ NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{
Primary: to.BoolPtr(false), Primary: pointer.Bool(false),
}, },
}, },
{ {
ID: to.StringPtr("2"), ID: pointer.String("2"),
NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{ NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{
Primary: to.BoolPtr(false), Primary: pointer.Bool(false),
}, },
}, },
}, },
@ -1027,7 +1027,7 @@ func TestGetPrimaryInterfaceID(t *testing.T) {
assert.NoError(t, err, "unexpected error when creating test VMSS") assert.NoError(t, err, "unexpected error when creating test VMSS")
vm := compute.VirtualMachineScaleSetVM{ vm := compute.VirtualMachineScaleSetVM{
Name: to.StringPtr("vm"), Name: pointer.String("vm"),
VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{
NetworkProfile: &compute.NetworkProfile{ NetworkProfile: &compute.NetworkProfile{
NetworkInterfaces: &test.existedInterfaces, NetworkInterfaces: &test.existedInterfaces,
@ -1125,15 +1125,15 @@ func TestGetPrimaryInterface(t *testing.T) {
expectedVMSSVMs, expectedInterface, _ := buildTestVirtualMachineEnv(ss.cloud, testVMSSName, "", 0, test.vmList, "", false) expectedVMSSVMs, expectedInterface, _ := buildTestVirtualMachineEnv(ss.cloud, testVMSSName, "", 0, test.vmList, "", false)
if !test.hasPrimaryInterface { if !test.hasPrimaryInterface {
networkInterfaces := *expectedVMSSVMs[0].NetworkProfile.NetworkInterfaces networkInterfaces := *expectedVMSSVMs[0].NetworkProfile.NetworkInterfaces
networkInterfaces[0].Primary = to.BoolPtr(false) networkInterfaces[0].Primary = pointer.Bool(false)
networkInterfaces = append(networkInterfaces, compute.NetworkInterfaceReference{ networkInterfaces = append(networkInterfaces, compute.NetworkInterfaceReference{
NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{Primary: to.BoolPtr(false)}, NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{Primary: pointer.Bool(false)},
}) })
expectedVMSSVMs[0].NetworkProfile.NetworkInterfaces = &networkInterfaces expectedVMSSVMs[0].NetworkProfile.NetworkInterfaces = &networkInterfaces
} }
if test.isInvalidNICID { if test.isInvalidNICID {
networkInterfaces := *expectedVMSSVMs[0].NetworkProfile.NetworkInterfaces networkInterfaces := *expectedVMSSVMs[0].NetworkProfile.NetworkInterfaces
networkInterfaces[0].ID = to.StringPtr("invalid/id/") networkInterfaces[0].ID = pointer.String("invalid/id/")
expectedVMSSVMs[0].NetworkProfile.NetworkInterfaces = &networkInterfaces expectedVMSSVMs[0].NetworkProfile.NetworkInterfaces = &networkInterfaces
} }
mockVMSSVMClient := ss.cloud.VirtualMachineScaleSetVMsClient.(*mockvmssvmclient.MockInterface) mockVMSSVMClient := ss.cloud.VirtualMachineScaleSetVMsClient.(*mockvmssvmclient.MockInterface)
@ -1317,27 +1317,27 @@ func TestListScaleSets(t *testing.T) {
description: "listScaleSets should return the correct scale sets", description: "listScaleSets should return the correct scale sets",
existedScaleSets: []compute.VirtualMachineScaleSet{ existedScaleSets: []compute.VirtualMachineScaleSet{
{ {
Name: to.StringPtr("vmss-0"), Name: pointer.String("vmss-0"),
Sku: &compute.Sku{Capacity: to.Int64Ptr(1)}, Sku: &compute.Sku{Capacity: pointer.Int64(1)},
VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{ VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{
VirtualMachineProfile: &compute.VirtualMachineScaleSetVMProfile{}, VirtualMachineProfile: &compute.VirtualMachineScaleSetVMProfile{},
}, },
}, },
{ {
Name: to.StringPtr("vmss-1"), Name: pointer.String("vmss-1"),
VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{ VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{
VirtualMachineProfile: &compute.VirtualMachineScaleSetVMProfile{}, VirtualMachineProfile: &compute.VirtualMachineScaleSetVMProfile{},
}, },
}, },
{ {
Name: to.StringPtr("vmss-2"), Name: pointer.String("vmss-2"),
Sku: &compute.Sku{Capacity: to.Int64Ptr(0)}, Sku: &compute.Sku{Capacity: pointer.Int64(0)},
VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{ VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{
VirtualMachineProfile: &compute.VirtualMachineScaleSetVMProfile{}, VirtualMachineProfile: &compute.VirtualMachineScaleSetVMProfile{},
}, },
}, },
{ {
Name: to.StringPtr("vmss-3"), Name: pointer.String("vmss-3"),
}, },
}, },
expectedVMSSNames: []string{"vmss-0", "vmss-1"}, expectedVMSSNames: []string{"vmss-0", "vmss-1"},
@ -1375,8 +1375,8 @@ func TestListScaleSetVMs(t *testing.T) {
{ {
description: "listScaleSetVMs should return the correct vmss vms", description: "listScaleSetVMs should return the correct vmss vms",
existedVMSSVMs: []compute.VirtualMachineScaleSetVM{ existedVMSSVMs: []compute.VirtualMachineScaleSetVM{
{Name: to.StringPtr("vmss-vm-000000")}, {Name: pointer.String("vmss-vm-000000")},
{Name: to.StringPtr("vmss-vm-000001")}, {Name: pointer.String("vmss-vm-000001")},
}, },
}, },
{ {
@ -1468,7 +1468,7 @@ func TestGetAgentPoolScaleSets(t *testing.T) {
expectedVMSSVMs := []compute.VirtualMachineScaleSetVM{ expectedVMSSVMs := []compute.VirtualMachineScaleSetVM{
{ {
VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{
OsProfile: &compute.OSProfile{ComputerName: to.StringPtr("vmss-vm-000000")}, OsProfile: &compute.OSProfile{ComputerName: pointer.String("vmss-vm-000000")},
NetworkProfile: &compute.NetworkProfile{ NetworkProfile: &compute.NetworkProfile{
NetworkInterfaces: &[]compute.NetworkInterfaceReference{}, NetworkInterfaces: &[]compute.NetworkInterfaceReference{},
}, },
@ -1476,7 +1476,7 @@ func TestGetAgentPoolScaleSets(t *testing.T) {
}, },
{ {
VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{
OsProfile: &compute.OSProfile{ComputerName: to.StringPtr("vmss-vm-000001")}, OsProfile: &compute.OSProfile{ComputerName: pointer.String("vmss-vm-000001")},
NetworkProfile: &compute.NetworkProfile{ NetworkProfile: &compute.NetworkProfile{
NetworkInterfaces: &[]compute.NetworkInterfaceReference{}, NetworkInterfaces: &[]compute.NetworkInterfaceReference{},
}, },
@ -1484,7 +1484,7 @@ func TestGetAgentPoolScaleSets(t *testing.T) {
}, },
{ {
VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{
OsProfile: &compute.OSProfile{ComputerName: to.StringPtr("vmss-vm-000002")}, OsProfile: &compute.OSProfile{ComputerName: pointer.String("vmss-vm-000002")},
NetworkProfile: &compute.NetworkProfile{ NetworkProfile: &compute.NetworkProfile{
NetworkInterfaces: &[]compute.NetworkInterfaceReference{}, NetworkInterfaces: &[]compute.NetworkInterfaceReference{},
}, },
@ -1602,7 +1602,7 @@ func TestGetVMSetNames(t *testing.T) {
expectedVMSSVMs := []compute.VirtualMachineScaleSetVM{ expectedVMSSVMs := []compute.VirtualMachineScaleSetVM{
{ {
VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{
OsProfile: &compute.OSProfile{ComputerName: to.StringPtr("vmss-vm-000000")}, OsProfile: &compute.OSProfile{ComputerName: pointer.String("vmss-vm-000000")},
NetworkProfile: &compute.NetworkProfile{ NetworkProfile: &compute.NetworkProfile{
NetworkInterfaces: &[]compute.NetworkInterfaceReference{}, NetworkInterfaces: &[]compute.NetworkInterfaceReference{},
}, },
@ -1610,7 +1610,7 @@ func TestGetVMSetNames(t *testing.T) {
}, },
{ {
VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{
OsProfile: &compute.OSProfile{ComputerName: to.StringPtr("vmss-vm-000001")}, OsProfile: &compute.OSProfile{ComputerName: pointer.String("vmss-vm-000001")},
NetworkProfile: &compute.NetworkProfile{ NetworkProfile: &compute.NetworkProfile{
NetworkInterfaces: &[]compute.NetworkInterfaceReference{}, NetworkInterfaces: &[]compute.NetworkInterfaceReference{},
}, },
@ -1618,7 +1618,7 @@ func TestGetVMSetNames(t *testing.T) {
}, },
{ {
VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{
OsProfile: &compute.OSProfile{ComputerName: to.StringPtr("vmss-vm-000002")}, OsProfile: &compute.OSProfile{ComputerName: pointer.String("vmss-vm-000002")},
NetworkProfile: &compute.NetworkProfile{ NetworkProfile: &compute.NetworkProfile{
NetworkInterfaces: &[]compute.NetworkInterfaceReference{}, NetworkInterfaces: &[]compute.NetworkInterfaceReference{},
}, },
@ -1626,7 +1626,7 @@ func TestGetVMSetNames(t *testing.T) {
}, },
{ {
VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{
OsProfile: &compute.OSProfile{ComputerName: to.StringPtr("vmss-vm-000003")}, OsProfile: &compute.OSProfile{ComputerName: pointer.String("vmss-vm-000003")},
}, },
}, },
} }
@ -1650,7 +1650,7 @@ func TestGetPrimaryNetworkInterfaceConfigurationForScaleSet(t *testing.T) {
assert.NoError(t, err, "unexpected error when creating test VMSS") assert.NoError(t, err, "unexpected error when creating test VMSS")
networkConfigs := []compute.VirtualMachineScaleSetNetworkConfiguration{ networkConfigs := []compute.VirtualMachineScaleSetNetworkConfiguration{
{Name: to.StringPtr("config-0")}, {Name: pointer.String("config-0")},
} }
config, err := ss.getPrimaryNetworkInterfaceConfigurationForScaleSet(networkConfigs, testVMSSName) config, err := ss.getPrimaryNetworkInterfaceConfigurationForScaleSet(networkConfigs, testVMSSName)
assert.Nil(t, err, "getPrimaryNetworkInterfaceConfigurationForScaleSet should return the correct network config") assert.Nil(t, err, "getPrimaryNetworkInterfaceConfigurationForScaleSet should return the correct network config")
@ -1658,15 +1658,15 @@ func TestGetPrimaryNetworkInterfaceConfigurationForScaleSet(t *testing.T) {
networkConfigs = []compute.VirtualMachineScaleSetNetworkConfiguration{ networkConfigs = []compute.VirtualMachineScaleSetNetworkConfiguration{
{ {
Name: to.StringPtr("config-0"), Name: pointer.String("config-0"),
VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{
Primary: to.BoolPtr(false), Primary: pointer.Bool(false),
}, },
}, },
{ {
Name: to.StringPtr("config-1"), Name: pointer.String("config-1"),
VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{
Primary: to.BoolPtr(true), Primary: pointer.Bool(true),
}, },
}, },
} }
@ -1676,15 +1676,15 @@ func TestGetPrimaryNetworkInterfaceConfigurationForScaleSet(t *testing.T) {
networkConfigs = []compute.VirtualMachineScaleSetNetworkConfiguration{ networkConfigs = []compute.VirtualMachineScaleSetNetworkConfiguration{
{ {
Name: to.StringPtr("config-0"), Name: pointer.String("config-0"),
VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{
Primary: to.BoolPtr(false), Primary: pointer.Bool(false),
}, },
}, },
{ {
Name: to.StringPtr("config-1"), Name: pointer.String("config-1"),
VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{
Primary: to.BoolPtr(false), Primary: pointer.Bool(false),
}, },
}, },
} }
@ -1698,7 +1698,7 @@ func TestGetPrimaryIPConfigFromVMSSNetworkConfig(t *testing.T) {
VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{
IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{
{ {
Name: to.StringPtr("config-0"), Name: pointer.String("config-0"),
}, },
}, },
}, },
@ -1712,15 +1712,15 @@ func TestGetPrimaryIPConfigFromVMSSNetworkConfig(t *testing.T) {
VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{
IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{
{ {
Name: to.StringPtr("config-0"), Name: pointer.String("config-0"),
VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{
Primary: to.BoolPtr(false), Primary: pointer.Bool(false),
}, },
}, },
{ {
Name: to.StringPtr("config-1"), Name: pointer.String("config-1"),
VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{
Primary: to.BoolPtr(true), Primary: pointer.Bool(true),
}, },
}, },
}, },
@ -1735,15 +1735,15 @@ func TestGetPrimaryIPConfigFromVMSSNetworkConfig(t *testing.T) {
VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{
IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{
{ {
Name: to.StringPtr("config-0"), Name: pointer.String("config-0"),
VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{
Primary: to.BoolPtr(false), Primary: pointer.Bool(false),
}, },
}, },
{ {
Name: to.StringPtr("config-1"), Name: pointer.String("config-1"),
VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{
Primary: to.BoolPtr(false), Primary: pointer.Bool(false),
}, },
}, },
}, },
@ -1766,13 +1766,13 @@ func TestGetConfigForScaleSetByIPFamily(t *testing.T) {
VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{
IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{
{ {
Name: to.StringPtr("config-0"), Name: pointer.String("config-0"),
VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{
PrivateIPAddressVersion: compute.IPv4, PrivateIPAddressVersion: compute.IPv4,
}, },
}, },
{ {
Name: to.StringPtr("config-0"), Name: pointer.String("config-0"),
VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{
PrivateIPAddressVersion: compute.IPv6, PrivateIPAddressVersion: compute.IPv6,
}, },
@ -1853,25 +1853,25 @@ func TestEnsureHostInPool(t *testing.T) {
expectedVMSSName: testVMSSName, expectedVMSSName: testVMSSName,
expectedInstanceID: "0", expectedInstanceID: "0",
expectedVMSSVM: &compute.VirtualMachineScaleSetVM{ expectedVMSSVM: &compute.VirtualMachineScaleSetVM{
Location: to.StringPtr("westus"), Location: pointer.String("westus"),
VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{
NetworkProfileConfiguration: &compute.VirtualMachineScaleSetVMNetworkProfileConfiguration{ NetworkProfileConfiguration: &compute.VirtualMachineScaleSetVMNetworkProfileConfiguration{
NetworkInterfaceConfigurations: &[]compute.VirtualMachineScaleSetNetworkConfiguration{ NetworkInterfaceConfigurations: &[]compute.VirtualMachineScaleSetNetworkConfiguration{
{ {
Name: to.StringPtr("ipconfig1"), Name: pointer.String("ipconfig1"),
ID: to.StringPtr("fakeNetworkConfiguration"), ID: pointer.String("fakeNetworkConfiguration"),
VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{
IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{
{ {
Name: to.StringPtr("ipconfig1"), Name: pointer.String("ipconfig1"),
VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{
Primary: to.BoolPtr(true), Primary: pointer.Bool(true),
LoadBalancerBackendAddressPools: &[]compute.SubResource{ LoadBalancerBackendAddressPools: &[]compute.SubResource{
{ {
ID: to.StringPtr(testLBBackendpoolID0), ID: pointer.String(testLBBackendpoolID0),
}, },
{ {
ID: to.StringPtr("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lb-internal/backendAddressPools/backendpool-1"), ID: pointer.String("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lb-internal/backendAddressPools/backendpool-1"),
}, },
}, },
}, },
@ -2190,7 +2190,7 @@ func TestEnsureHostsInPool(t *testing.T) {
assert.NoError(t, err, test.description) assert.NoError(t, err, test.description)
ss.LoadBalancerSku = loadBalancerSkuStandard ss.LoadBalancerSku = loadBalancerSkuStandard
ss.ExcludeMasterFromStandardLB = to.BoolPtr(true) ss.ExcludeMasterFromStandardLB = pointer.Bool(true)
expectedVMSS := buildTestVMSSWithLB(testVMSSName, "vmss-vm-", []string{testLBBackendpoolID0}, false) expectedVMSS := buildTestVMSSWithLB(testVMSSName, "vmss-vm-", []string{testLBBackendpoolID0}, false)
mockVMSSClient := ss.cloud.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) mockVMSSClient := ss.cloud.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface)
@ -2248,19 +2248,19 @@ func TestEnsureBackendPoolDeletedFromNode(t *testing.T) {
expectedVMSSName: testVMSSName, expectedVMSSName: testVMSSName,
expectedInstanceID: "0", expectedInstanceID: "0",
expectedVMSSVM: &compute.VirtualMachineScaleSetVM{ expectedVMSSVM: &compute.VirtualMachineScaleSetVM{
Location: to.StringPtr("westus"), Location: pointer.String("westus"),
VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{
NetworkProfileConfiguration: &compute.VirtualMachineScaleSetVMNetworkProfileConfiguration{ NetworkProfileConfiguration: &compute.VirtualMachineScaleSetVMNetworkProfileConfiguration{
NetworkInterfaceConfigurations: &[]compute.VirtualMachineScaleSetNetworkConfiguration{ NetworkInterfaceConfigurations: &[]compute.VirtualMachineScaleSetNetworkConfiguration{
{ {
Name: to.StringPtr("ipconfig1"), Name: pointer.String("ipconfig1"),
ID: to.StringPtr("fakeNetworkConfiguration"), ID: pointer.String("fakeNetworkConfiguration"),
VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{
IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{
{ {
Name: to.StringPtr("ipconfig1"), Name: pointer.String("ipconfig1"),
VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{
Primary: to.BoolPtr(true), Primary: pointer.Bool(true),
LoadBalancerBackendAddressPools: &[]compute.SubResource{}, LoadBalancerBackendAddressPools: &[]compute.SubResource{},
}, },
}, },
@ -2409,25 +2409,25 @@ func TestEnsureBackendPoolDeleted(t *testing.T) {
backendpoolID: testLBBackendpoolID0, backendpoolID: testLBBackendpoolID0,
backendAddressPools: &[]network.BackendAddressPool{ backendAddressPools: &[]network.BackendAddressPool{
{ {
ID: to.StringPtr(testLBBackendpoolID0), ID: pointer.String(testLBBackendpoolID0),
BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{
BackendIPConfigurations: &[]network.InterfaceIPConfiguration{ BackendIPConfigurations: &[]network.InterfaceIPConfiguration{
{ {
Name: to.StringPtr("ip-1"), Name: pointer.String("ip-1"),
ID: to.StringPtr("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss/virtualMachines/0/networkInterfaces/nic"), ID: pointer.String("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss/virtualMachines/0/networkInterfaces/nic"),
}, },
{ {
Name: to.StringPtr("ip-2"), Name: pointer.String("ip-2"),
}, },
{ {
Name: to.StringPtr("ip-3"), Name: pointer.String("ip-3"),
ID: to.StringPtr("/invalid/id"), ID: pointer.String("/invalid/id"),
}, },
}, },
}, },
}, },
{ {
ID: to.StringPtr(testLBBackendpoolID1), ID: pointer.String(testLBBackendpoolID1),
}, },
}, },
expectedVMSSVMPutTimes: 1, expectedVMSSVMPutTimes: 1,
@ -2437,18 +2437,18 @@ func TestEnsureBackendPoolDeleted(t *testing.T) {
backendpoolID: testLBBackendpoolID0, backendpoolID: testLBBackendpoolID0,
backendAddressPools: &[]network.BackendAddressPool{ backendAddressPools: &[]network.BackendAddressPool{
{ {
ID: to.StringPtr(testLBBackendpoolID0), ID: pointer.String(testLBBackendpoolID0),
BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{
BackendIPConfigurations: &[]network.InterfaceIPConfiguration{ BackendIPConfigurations: &[]network.InterfaceIPConfiguration{
{ {
Name: to.StringPtr("ip-1"), Name: pointer.String("ip-1"),
ID: to.StringPtr("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss/virtualMachines/0/networkInterfaces/nic"), ID: pointer.String("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss/virtualMachines/0/networkInterfaces/nic"),
}, },
}, },
}, },
}, },
{ {
ID: to.StringPtr(testLBBackendpoolID1), ID: pointer.String(testLBBackendpoolID1),
}, },
}, },
expectedVMSSVMPutTimes: 1, expectedVMSSVMPutTimes: 1,
@ -2460,18 +2460,18 @@ func TestEnsureBackendPoolDeleted(t *testing.T) {
backendpoolID: testLBBackendpoolID0, backendpoolID: testLBBackendpoolID0,
backendAddressPools: &[]network.BackendAddressPool{ backendAddressPools: &[]network.BackendAddressPool{
{ {
ID: to.StringPtr(testLBBackendpoolID0), ID: pointer.String(testLBBackendpoolID0),
BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{
BackendIPConfigurations: &[]network.InterfaceIPConfiguration{ BackendIPConfigurations: &[]network.InterfaceIPConfiguration{
{ {
Name: to.StringPtr("ip-1"), Name: pointer.String("ip-1"),
ID: to.StringPtr("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss/virtualMachines/6/networkInterfaces/nic"), ID: pointer.String("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss/virtualMachines/6/networkInterfaces/nic"),
}, },
}, },
}, },
}, },
{ {
ID: to.StringPtr(testLBBackendpoolID1), ID: pointer.String(testLBBackendpoolID1),
}, },
}, },
}, },
@ -2507,34 +2507,34 @@ func TestEnsureBackendPoolDeletedConcurrently(t *testing.T) {
backendAddressPools := &[]network.BackendAddressPool{ backendAddressPools := &[]network.BackendAddressPool{
{ {
ID: to.StringPtr(testLBBackendpoolID0), ID: pointer.String(testLBBackendpoolID0),
BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{
BackendIPConfigurations: &[]network.InterfaceIPConfiguration{ BackendIPConfigurations: &[]network.InterfaceIPConfiguration{
{ {
Name: to.StringPtr("ip-1"), Name: pointer.String("ip-1"),
ID: to.StringPtr("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss-0/virtualMachines/0/networkInterfaces/nic"), ID: pointer.String("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss-0/virtualMachines/0/networkInterfaces/nic"),
}, },
}, },
}, },
}, },
{ {
ID: to.StringPtr(testLBBackendpoolID1), ID: pointer.String(testLBBackendpoolID1),
BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{
BackendIPConfigurations: &[]network.InterfaceIPConfiguration{ BackendIPConfigurations: &[]network.InterfaceIPConfiguration{
{ {
Name: to.StringPtr("ip-1"), Name: pointer.String("ip-1"),
ID: to.StringPtr("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss-1/virtualMachines/0/networkInterfaces/nic"), ID: pointer.String("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss-1/virtualMachines/0/networkInterfaces/nic"),
}, },
}, },
}, },
}, },
{ {
ID: to.StringPtr(testLBBackendpoolID2), ID: pointer.String(testLBBackendpoolID2),
BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{
BackendIPConfigurations: &[]network.InterfaceIPConfiguration{ BackendIPConfigurations: &[]network.InterfaceIPConfiguration{
{ {
Name: to.StringPtr("ip-1"), Name: pointer.String("ip-1"),
ID: to.StringPtr("/subscriptions/sub/resourceGroups/rg1/providers/Microsoft.Compute/virtualMachineScaleSets/vmss-0/virtualMachines/0/networkInterfaces/nic"), ID: pointer.String("/subscriptions/sub/resourceGroups/rg1/providers/Microsoft.Compute/virtualMachineScaleSets/vmss-0/virtualMachines/0/networkInterfaces/nic"),
}, },
}, },
}, },
@ -2550,7 +2550,7 @@ func TestEnsureBackendPoolDeletedConcurrently(t *testing.T) {
vmssVMNetworkConfigs := expectedVMSSVMs[0].NetworkProfileConfiguration vmssVMNetworkConfigs := expectedVMSSVMs[0].NetworkProfileConfiguration
vmssVMIPConfigs := (*vmssVMNetworkConfigs.NetworkInterfaceConfigurations)[0].VirtualMachineScaleSetNetworkConfigurationProperties.IPConfigurations vmssVMIPConfigs := (*vmssVMNetworkConfigs.NetworkInterfaceConfigurations)[0].VirtualMachineScaleSetNetworkConfigurationProperties.IPConfigurations
lbBackendpools := (*vmssVMIPConfigs)[0].LoadBalancerBackendAddressPools lbBackendpools := (*vmssVMIPConfigs)[0].LoadBalancerBackendAddressPools
*lbBackendpools = append(*lbBackendpools, compute.SubResource{ID: to.StringPtr(testLBBackendpoolID1)}) *lbBackendpools = append(*lbBackendpools, compute.SubResource{ID: pointer.String(testLBBackendpoolID1)})
} }
mockVMSSClient := ss.cloud.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) mockVMSSClient := ss.cloud.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface)

View File

@ -28,13 +28,13 @@ import (
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute"
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network"
"github.com/Azure/go-autorest/autorest/to"
"k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/types"
cloudprovider "k8s.io/cloud-provider" cloudprovider "k8s.io/cloud-provider"
"k8s.io/klog/v2" "k8s.io/klog/v2"
azcache "k8s.io/legacy-cloud-providers/azure/cache" azcache "k8s.io/legacy-cloud-providers/azure/cache"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
) )
var ( var (
@ -197,7 +197,7 @@ func (az *Cloud) newVMCache() (*azcache.TimedCache, error) {
} }
if vm.VirtualMachineProperties != nil && if vm.VirtualMachineProperties != nil &&
strings.EqualFold(to.String(vm.VirtualMachineProperties.ProvisioningState), string(compute.ProvisioningStateDeleting)) { strings.EqualFold(pointer.StringDeref(vm.VirtualMachineProperties.ProvisioningState, ""), string(compute.ProvisioningStateDeleting)) {
klog.V(2).Infof("Virtual machine %q is under deleting", key) klog.V(2).Infof("Virtual machine %q is under deleting", key)
return nil, nil return nil, nil
} }

View File

@ -29,9 +29,9 @@ import (
"k8s.io/apimachinery/pkg/util/sets" "k8s.io/apimachinery/pkg/util/sets"
cloudprovider "k8s.io/cloud-provider" cloudprovider "k8s.io/cloud-provider"
"k8s.io/legacy-cloud-providers/azure/clients/vmclient/mockvmclient" "k8s.io/legacy-cloud-providers/azure/clients/vmclient/mockvmclient"
"k8s.io/utils/pointer"
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute"
"github.com/Azure/go-autorest/autorest/to"
"github.com/golang/mock/gomock" "github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -212,7 +212,7 @@ func TestGetZoneByProviderID(t *testing.T) {
mockVMClient := az.VirtualMachinesClient.(*mockvmclient.MockInterface) mockVMClient := az.VirtualMachinesClient.(*mockvmclient.MockInterface)
mockVMClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, "vm-0", gomock.Any()).Return(compute.VirtualMachine{ mockVMClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, "vm-0", gomock.Any()).Return(compute.VirtualMachine{
Zones: &[]string{"1"}, Zones: &[]string{"1"},
Location: to.StringPtr("eastus"), Location: pointer.String("eastus"),
}, nil) }, nil)
zone, err = az.GetZoneByProviderID(context.Background(), testAvailabilitySetNodeProviderID) zone, err = az.GetZoneByProviderID(context.Background(), testAvailabilitySetNodeProviderID)
assert.NoError(t, err) assert.NoError(t, err)

View File

@ -28,7 +28,6 @@ import (
"github.com/Azure/azure-sdk-for-go/services/containerservice/mgmt/2020-04-01/containerservice" "github.com/Azure/azure-sdk-for-go/services/containerservice/mgmt/2020-04-01/containerservice"
"github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/to"
"k8s.io/client-go/util/flowcontrol" "k8s.io/client-go/util/flowcontrol"
"k8s.io/klog/v2" "k8s.io/klog/v2"
@ -36,6 +35,7 @@ import (
"k8s.io/legacy-cloud-providers/azure/clients/armclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient"
"k8s.io/legacy-cloud-providers/azure/metrics" "k8s.io/legacy-cloud-providers/azure/metrics"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
) )
var _ Interface = &Client{} var _ Interface = &Client{}
@ -197,7 +197,7 @@ func (c *Client) listManagedCluster(ctx context.Context, resourceGroupName strin
result = append(result, page.Values()...) result = append(result, page.Values()...)
// Abort the loop when there's no nextLink in the response. // Abort the loop when there's no nextLink in the response.
if to.String(page.Response().NextLink) == "" { if pointer.StringDeref(page.Response().NextLink, "") == "" {
break break
} }
@ -223,12 +223,12 @@ func (c *Client) listResponder(resp *http.Response) (result containerservice.Man
// managedClusterListResultPreparer prepares a request to retrieve the next set of results. // managedClusterListResultPreparer prepares a request to retrieve the next set of results.
// It returns nil if no more results exist. // It returns nil if no more results exist.
func (c *Client) managedClusterListResultPreparer(ctx context.Context, mclr containerservice.ManagedClusterListResult) (*http.Request, error) { func (c *Client) managedClusterListResultPreparer(ctx context.Context, mclr containerservice.ManagedClusterListResult) (*http.Request, error) {
if mclr.NextLink == nil || len(to.String(mclr.NextLink)) < 1 { if mclr.NextLink == nil || len(pointer.StringDeref(mclr.NextLink, "")) < 1 {
return nil, nil return nil, nil
} }
decorators := []autorest.PrepareDecorator{ decorators := []autorest.PrepareDecorator{
autorest.WithBaseURL(to.String(mclr.NextLink)), autorest.WithBaseURL(pointer.StringDeref(mclr.NextLink, "")),
} }
return c.armClient.PrepareGetRequest(ctx, decorators...) return c.armClient.PrepareGetRequest(ctx, decorators...)
} }

View File

@ -31,7 +31,6 @@ import (
"github.com/Azure/azure-sdk-for-go/services/containerservice/mgmt/2020-04-01/containerservice" "github.com/Azure/azure-sdk-for-go/services/containerservice/mgmt/2020-04-01/containerservice"
"github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/to"
"github.com/golang/mock/gomock" "github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -40,6 +39,7 @@ import (
"k8s.io/legacy-cloud-providers/azure/clients/armclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient"
"k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
) )
// 2065-01-24 05:20:00 +0000 UTC // 2065-01-24 05:20:00 +0000 UTC
@ -83,9 +83,9 @@ func getTestManagedClusterClientWithRetryAfterReader(armClient armclient.Interfa
func getTestManagedCluster(name string) containerservice.ManagedCluster { func getTestManagedCluster(name string) containerservice.ManagedCluster {
return containerservice.ManagedCluster{ return containerservice.ManagedCluster{
ID: to.StringPtr(fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.ContainerService/managedClusters/%s", name)), ID: pointer.String(fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.ContainerService/managedClusters/%s", name)),
Name: to.StringPtr(name), Name: pointer.String(name),
Location: to.StringPtr("eastus"), Location: pointer.String("eastus"),
} }
} }
@ -280,7 +280,7 @@ func TestListNextResultsMultiPages(t *testing.T) {
} }
lastResult := containerservice.ManagedClusterListResult{ lastResult := containerservice.ManagedClusterListResult{
NextLink: to.StringPtr("next"), NextLink: pointer.String("next"),
} }
for _, test := range tests { for _, test := range tests {
@ -325,7 +325,7 @@ func TestListNextResultsMultiPagesWithListResponderError(t *testing.T) {
} }
lastResult := containerservice.ManagedClusterListResult{ lastResult := containerservice.ManagedClusterListResult{
NextLink: to.StringPtr("next"), NextLink: pointer.String("next"),
} }
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
@ -476,7 +476,7 @@ func TestCreateOrUpdate(t *testing.T) {
StatusCode: http.StatusOK, StatusCode: http.StatusOK,
Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), Body: ioutil.NopCloser(bytes.NewReader([]byte(""))),
} }
armClient.EXPECT().PutResourceWithDecorators(gomock.Any(), to.String(mc.ID), mc, gomock.Any()).Return(response, nil).Times(1) armClient.EXPECT().PutResourceWithDecorators(gomock.Any(), pointer.StringDeref(mc.ID, ""), mc, gomock.Any()).Return(response, nil).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
mcClient := getTestManagedClusterClient(armClient) mcClient := getTestManagedClusterClient(armClient)
@ -493,7 +493,7 @@ func TestCreateOrUpdateWithCreateOrUpdateResponderError(t *testing.T) {
StatusCode: http.StatusNotFound, StatusCode: http.StatusNotFound,
Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), Body: ioutil.NopCloser(bytes.NewReader([]byte(""))),
} }
armClient.EXPECT().PutResourceWithDecorators(gomock.Any(), to.String(mc.ID), mc, gomock.Any()).Return(response, nil).Times(1) armClient.EXPECT().PutResourceWithDecorators(gomock.Any(), pointer.StringDeref(mc.ID, ""), mc, gomock.Any()).Return(response, nil).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
mcClient := getTestManagedClusterClient(armClient) mcClient := getTestManagedClusterClient(armClient)
@ -555,7 +555,7 @@ func TestCreateOrUpdateThrottle(t *testing.T) {
mc := getTestManagedCluster("cluster") mc := getTestManagedCluster("cluster")
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
armClient.EXPECT().PutResourceWithDecorators(gomock.Any(), to.String(mc.ID), mc, gomock.Any()).Return(response, throttleErr).Times(1) armClient.EXPECT().PutResourceWithDecorators(gomock.Any(), pointer.StringDeref(mc.ID, ""), mc, gomock.Any()).Return(response, throttleErr).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
mcClient := getTestManagedClusterClient(armClient) mcClient := getTestManagedClusterClient(armClient)
@ -570,7 +570,7 @@ func TestDelete(t *testing.T) {
mc := getTestManagedCluster("cluster") mc := getTestManagedCluster("cluster")
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
armClient.EXPECT().DeleteResource(gomock.Any(), to.String(mc.ID), "").Return(nil).Times(1) armClient.EXPECT().DeleteResource(gomock.Any(), pointer.StringDeref(mc.ID, ""), "").Return(nil).Times(1)
mcClient := getTestManagedClusterClient(armClient) mcClient := getTestManagedClusterClient(armClient)
rerr := mcClient.Delete(context.TODO(), "rg", "cluster") rerr := mcClient.Delete(context.TODO(), "rg", "cluster")
@ -625,7 +625,7 @@ func TestDeleteThrottle(t *testing.T) {
mc := getTestManagedCluster("cluster") mc := getTestManagedCluster("cluster")
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
armClient.EXPECT().DeleteResource(gomock.Any(), to.String(mc.ID), "").Return(throttleErr).Times(1) armClient.EXPECT().DeleteResource(gomock.Any(), pointer.StringDeref(mc.ID, ""), "").Return(throttleErr).Times(1)
mcClient := getTestManagedClusterClient(armClient) mcClient := getTestManagedClusterClient(armClient)
rerr := mcClient.Delete(context.TODO(), "rg", "cluster") rerr := mcClient.Delete(context.TODO(), "rg", "cluster")

View File

@ -28,7 +28,6 @@ import (
"github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2017-05-10/resources" "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2017-05-10/resources"
"github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/to"
"k8s.io/client-go/util/flowcontrol" "k8s.io/client-go/util/flowcontrol"
"k8s.io/klog/v2" "k8s.io/klog/v2"
@ -36,6 +35,7 @@ import (
"k8s.io/legacy-cloud-providers/azure/clients/armclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient"
"k8s.io/legacy-cloud-providers/azure/metrics" "k8s.io/legacy-cloud-providers/azure/metrics"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
) )
var _ Interface = &Client{} var _ Interface = &Client{}
@ -197,7 +197,7 @@ func (c *Client) listDeployment(ctx context.Context, resourceGroupName string) (
result = append(result, page.Values()...) result = append(result, page.Values()...)
// Abort the loop when there's no nextLink in the response. // Abort the loop when there's no nextLink in the response.
if to.String(page.Response().NextLink) == "" { if pointer.StringDeref(page.Response().NextLink, "") == "" {
break break
} }
@ -223,12 +223,12 @@ func (c *Client) listResponder(resp *http.Response) (result resources.Deployment
// deploymentListResultPreparer prepares a request to retrieve the next set of results. // deploymentListResultPreparer prepares a request to retrieve the next set of results.
// It returns nil if no more results exist. // It returns nil if no more results exist.
func (c *Client) deploymentListResultPreparer(ctx context.Context, dplr resources.DeploymentListResult) (*http.Request, error) { func (c *Client) deploymentListResultPreparer(ctx context.Context, dplr resources.DeploymentListResult) (*http.Request, error) {
if dplr.NextLink == nil || len(to.String(dplr.NextLink)) < 1 { if dplr.NextLink == nil || len(pointer.StringDeref(dplr.NextLink, "")) < 1 {
return nil, nil return nil, nil
} }
decorators := []autorest.PrepareDecorator{ decorators := []autorest.PrepareDecorator{
autorest.WithBaseURL(to.String(dplr.NextLink)), autorest.WithBaseURL(pointer.StringDeref(dplr.NextLink, "")),
} }
return c.armClient.PrepareGetRequest(ctx, decorators...) return c.armClient.PrepareGetRequest(ctx, decorators...)
} }

View File

@ -31,7 +31,6 @@ import (
"github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2017-05-10/resources" "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2017-05-10/resources"
"github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/to"
"github.com/golang/mock/gomock" "github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -40,6 +39,7 @@ import (
"k8s.io/legacy-cloud-providers/azure/clients/armclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient"
"k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
) )
// 2065-01-24 05:20:00 +0000 UTC // 2065-01-24 05:20:00 +0000 UTC
@ -83,8 +83,8 @@ func getTestDeploymentClientWithRetryAfterReader(armClient armclient.Interface)
func getTestDeploymentExtended(name string) resources.DeploymentExtended { func getTestDeploymentExtended(name string) resources.DeploymentExtended {
return resources.DeploymentExtended{ return resources.DeploymentExtended{
ID: to.StringPtr(fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Resources/deployments/%s", name)), ID: pointer.String(fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Resources/deployments/%s", name)),
Name: to.StringPtr(name), Name: pointer.String(name),
} }
} }
@ -278,7 +278,7 @@ func TestListNextResultsMultiPages(t *testing.T) {
} }
lastResult := resources.DeploymentListResult{ lastResult := resources.DeploymentListResult{
NextLink: to.StringPtr("next"), NextLink: pointer.String("next"),
} }
for _, test := range tests { for _, test := range tests {
@ -323,7 +323,7 @@ func TestListNextResultsMultiPagesWithListResponderError(t *testing.T) {
} }
lastResult := resources.DeploymentListResult{ lastResult := resources.DeploymentListResult{
NextLink: to.StringPtr("next"), NextLink: pointer.String("next"),
} }
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
@ -474,7 +474,7 @@ func TestCreateOrUpdate(t *testing.T) {
StatusCode: http.StatusOK, StatusCode: http.StatusOK,
Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), Body: ioutil.NopCloser(bytes.NewReader([]byte(""))),
} }
armClient.EXPECT().PutResourceWithDecorators(gomock.Any(), to.String(dpExtended.ID), dp, gomock.Any()).Return(response, nil).Times(1) armClient.EXPECT().PutResourceWithDecorators(gomock.Any(), pointer.StringDeref(dpExtended.ID, ""), dp, gomock.Any()).Return(response, nil).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
dpClient := getTestDeploymentClient(armClient) dpClient := getTestDeploymentClient(armClient)
@ -493,7 +493,7 @@ func TestCreateOrUpdateWithCreateOrUpdateResponderError(t *testing.T) {
StatusCode: http.StatusNotFound, StatusCode: http.StatusNotFound,
Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), Body: ioutil.NopCloser(bytes.NewReader([]byte(""))),
} }
armClient.EXPECT().PutResourceWithDecorators(gomock.Any(), to.String(dpExtended.ID), dp, gomock.Any()).Return(response, nil).Times(1) armClient.EXPECT().PutResourceWithDecorators(gomock.Any(), pointer.StringDeref(dpExtended.ID, ""), dp, gomock.Any()).Return(response, nil).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
dpClient := getTestDeploymentClient(armClient) dpClient := getTestDeploymentClient(armClient)
@ -556,7 +556,7 @@ func TestCreateOrUpdateThrottle(t *testing.T) {
dp := resources.Deployment{} dp := resources.Deployment{}
dpExtended := getTestDeploymentExtended("dep") dpExtended := getTestDeploymentExtended("dep")
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
armClient.EXPECT().PutResourceWithDecorators(gomock.Any(), to.String(dpExtended.ID), dp, gomock.Any()).Return(response, throttleErr).Times(1) armClient.EXPECT().PutResourceWithDecorators(gomock.Any(), pointer.StringDeref(dpExtended.ID, ""), dp, gomock.Any()).Return(response, throttleErr).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
dpClient := getTestDeploymentClient(armClient) dpClient := getTestDeploymentClient(armClient)
@ -571,7 +571,7 @@ func TestDelete(t *testing.T) {
dp := getTestDeploymentExtended("dep") dp := getTestDeploymentExtended("dep")
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
armClient.EXPECT().DeleteResource(gomock.Any(), to.String(dp.ID), "").Return(nil).Times(1) armClient.EXPECT().DeleteResource(gomock.Any(), pointer.StringDeref(dp.ID, ""), "").Return(nil).Times(1)
dpClient := getTestDeploymentClient(armClient) dpClient := getTestDeploymentClient(armClient)
rerr := dpClient.Delete(context.TODO(), "rg", "dep") rerr := dpClient.Delete(context.TODO(), "rg", "dep")
@ -626,7 +626,7 @@ func TestDeleteThrottle(t *testing.T) {
dp := getTestDeploymentExtended("dep") dp := getTestDeploymentExtended("dep")
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
armClient.EXPECT().DeleteResource(gomock.Any(), to.String(dp.ID), "").Return(throttleErr).Times(1) armClient.EXPECT().DeleteResource(gomock.Any(), pointer.StringDeref(dp.ID, ""), "").Return(throttleErr).Times(1)
dpClient := getTestDeploymentClient(armClient) dpClient := getTestDeploymentClient(armClient)
rerr := dpClient.Delete(context.TODO(), "rg", "dep") rerr := dpClient.Delete(context.TODO(), "rg", "dep")

View File

@ -29,7 +29,6 @@ import (
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute"
"github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/to"
"k8s.io/client-go/util/flowcontrol" "k8s.io/client-go/util/flowcontrol"
"k8s.io/klog/v2" "k8s.io/klog/v2"
@ -37,6 +36,7 @@ import (
"k8s.io/legacy-cloud-providers/azure/clients/armclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient"
"k8s.io/legacy-cloud-providers/azure/metrics" "k8s.io/legacy-cloud-providers/azure/metrics"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
) )
var _ Interface = &Client{} var _ Interface = &Client{}
@ -351,7 +351,7 @@ func (c *Client) ListByResourceGroup(ctx context.Context, resourceGroupName stri
result = append(result, page.Values()...) result = append(result, page.Values()...)
// Abort the loop when there's no nextLink in the response. // Abort the loop when there's no nextLink in the response.
if to.String(page.Response().NextLink) == "" { if pointer.StringDeref(page.Response().NextLink, "") == "" {
break break
} }
@ -401,13 +401,13 @@ func (c *Client) listResponder(resp *http.Response) (result compute.DiskList, er
} }
func (c *Client) diskListPreparer(ctx context.Context, lr compute.DiskList) (*http.Request, error) { func (c *Client) diskListPreparer(ctx context.Context, lr compute.DiskList) (*http.Request, error) {
if lr.NextLink == nil || len(to.String(lr.NextLink)) < 1 { if lr.NextLink == nil || len(pointer.StringDeref(lr.NextLink, "")) < 1 {
return nil, nil return nil, nil
} }
return autorest.Prepare((&http.Request{}).WithContext(ctx), return autorest.Prepare((&http.Request{}).WithContext(ctx),
autorest.AsJSON(), autorest.AsJSON(),
autorest.AsGet(), autorest.AsGet(),
autorest.WithBaseURL(to.String(lr.NextLink))) autorest.WithBaseURL(pointer.StringDeref(lr.NextLink, "")))
} }
// DiskListPage contains a page of Disk values. // DiskListPage contains a page of Disk values.

View File

@ -30,7 +30,6 @@ import (
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute"
"github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/to"
"github.com/golang/mock/gomock" "github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -38,6 +37,7 @@ import (
"k8s.io/legacy-cloud-providers/azure/clients/armclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient"
"k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
) )
func TestNew(t *testing.T) { func TestNew(t *testing.T) {
@ -138,7 +138,7 @@ func TestCreateOrUpdate(t *testing.T) {
StatusCode: http.StatusOK, StatusCode: http.StatusOK,
Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), Body: ioutil.NopCloser(bytes.NewReader([]byte(""))),
} }
armClient.EXPECT().PutResource(gomock.Any(), to.String(disk.ID), disk).Return(response, nil).Times(1) armClient.EXPECT().PutResource(gomock.Any(), pointer.StringDeref(disk.ID, ""), disk).Return(response, nil).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
diskClient := getTestDiskClient(armClient) diskClient := getTestDiskClient(armClient)
@ -156,7 +156,7 @@ func TestCreateOrUpdate(t *testing.T) {
RetryAfter: time.Unix(100, 0), RetryAfter: time.Unix(100, 0),
} }
armClient.EXPECT().PutResource(gomock.Any(), to.String(disk.ID), disk).Return(response, throttleErr).Times(1) armClient.EXPECT().PutResource(gomock.Any(), pointer.StringDeref(disk.ID, ""), disk).Return(response, throttleErr).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
rerr = diskClient.CreateOrUpdate(context.TODO(), "rg", "disk1", disk) rerr = diskClient.CreateOrUpdate(context.TODO(), "rg", "disk1", disk)
assert.Equal(t, throttleErr, rerr) assert.Equal(t, throttleErr, rerr)
@ -200,7 +200,7 @@ func TestUpdate(t *testing.T) {
func getTestDiskUpdate() compute.DiskUpdate { func getTestDiskUpdate() compute.DiskUpdate {
return compute.DiskUpdate{ return compute.DiskUpdate{
DiskUpdateProperties: &compute.DiskUpdateProperties{ DiskUpdateProperties: &compute.DiskUpdateProperties{
DiskSizeGB: to.Int32Ptr(100), DiskSizeGB: pointer.Int32(100),
}, },
} }
} }
@ -211,7 +211,7 @@ func TestDelete(t *testing.T) {
r := getTestDisk("disk1") r := getTestDisk("disk1")
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
armClient.EXPECT().DeleteResource(gomock.Any(), to.String(r.ID), "").Return(nil).Times(1) armClient.EXPECT().DeleteResource(gomock.Any(), pointer.StringDeref(r.ID, ""), "").Return(nil).Times(1)
diskClient := getTestDiskClient(armClient) diskClient := getTestDiskClient(armClient)
rerr := diskClient.Delete(context.TODO(), "rg", "disk1") rerr := diskClient.Delete(context.TODO(), "rg", "disk1")
@ -223,16 +223,16 @@ func TestDelete(t *testing.T) {
Retriable: true, Retriable: true,
RetryAfter: time.Unix(100, 0), RetryAfter: time.Unix(100, 0),
} }
armClient.EXPECT().DeleteResource(gomock.Any(), to.String(r.ID), "").Return(throttleErr).Times(1) armClient.EXPECT().DeleteResource(gomock.Any(), pointer.StringDeref(r.ID, ""), "").Return(throttleErr).Times(1)
rerr = diskClient.Delete(context.TODO(), "rg", "disk1") rerr = diskClient.Delete(context.TODO(), "rg", "disk1")
assert.Equal(t, throttleErr, rerr) assert.Equal(t, throttleErr, rerr)
} }
func getTestDisk(name string) compute.Disk { func getTestDisk(name string) compute.Disk {
return compute.Disk{ return compute.Disk{
ID: to.StringPtr(fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/disks/%s", name)), ID: pointer.String(fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/disks/%s", name)),
Name: to.StringPtr(name), Name: pointer.String(name),
Location: to.StringPtr("eastus"), Location: pointer.String("eastus"),
} }
} }

View File

@ -30,7 +30,6 @@ import (
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network"
"github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/to"
"github.com/golang/mock/gomock" "github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -38,6 +37,7 @@ import (
"k8s.io/legacy-cloud-providers/azure/clients/armclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient"
"k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
) )
func TestNew(t *testing.T) { func TestNew(t *testing.T) {
@ -179,7 +179,7 @@ func TestCreateOrUpdate(t *testing.T) {
StatusCode: http.StatusOK, StatusCode: http.StatusOK,
Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), Body: ioutil.NopCloser(bytes.NewReader([]byte(""))),
} }
armClient.EXPECT().PutResource(gomock.Any(), to.String(testInterface.ID), testInterface).Return(response, nil).Times(1) armClient.EXPECT().PutResource(gomock.Any(), pointer.StringDeref(testInterface.ID, ""), testInterface).Return(response, nil).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
nicClient := getTestInterfaceClient(armClient) nicClient := getTestInterfaceClient(armClient)
@ -197,7 +197,7 @@ func TestCreateOrUpdate(t *testing.T) {
RetryAfter: time.Unix(100, 0), RetryAfter: time.Unix(100, 0),
} }
armClient.EXPECT().PutResource(gomock.Any(), to.String(testInterface.ID), testInterface).Return(response, noContentErr).Times(1) armClient.EXPECT().PutResource(gomock.Any(), pointer.StringDeref(testInterface.ID, ""), testInterface).Return(response, noContentErr).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
rerr = nicClient.CreateOrUpdate(context.TODO(), "rg", "nic1", testInterface) rerr = nicClient.CreateOrUpdate(context.TODO(), "rg", "nic1", testInterface)
assert.Equal(t, noContentErr, rerr) assert.Equal(t, noContentErr, rerr)
@ -209,7 +209,7 @@ func TestDelete(t *testing.T) {
r := getTestInterface("interface1") r := getTestInterface("interface1")
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
armClient.EXPECT().DeleteResource(gomock.Any(), to.String(r.ID), "").Return(nil).Times(1) armClient.EXPECT().DeleteResource(gomock.Any(), pointer.StringDeref(r.ID, ""), "").Return(nil).Times(1)
nicClient := getTestInterfaceClient(armClient) nicClient := getTestInterfaceClient(armClient)
rerr := nicClient.Delete(context.TODO(), "rg", "interface1") rerr := nicClient.Delete(context.TODO(), "rg", "interface1")
@ -221,7 +221,7 @@ func TestDelete(t *testing.T) {
Retriable: true, Retriable: true,
RetryAfter: time.Unix(100, 0), RetryAfter: time.Unix(100, 0),
} }
armClient.EXPECT().DeleteResource(gomock.Any(), to.String(r.ID), "").Return(noContentErr).Times(1) armClient.EXPECT().DeleteResource(gomock.Any(), pointer.StringDeref(r.ID, ""), "").Return(noContentErr).Times(1)
rerr = nicClient.Delete(context.TODO(), "rg", "interface1") rerr = nicClient.Delete(context.TODO(), "rg", "interface1")
assert.Equal(t, noContentErr, rerr) assert.Equal(t, noContentErr, rerr)
@ -230,19 +230,19 @@ func TestDelete(t *testing.T) {
func getTestInterface(name string) network.Interface { func getTestInterface(name string) network.Interface {
resourceID := fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/%s", name) resourceID := fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/%s", name)
return network.Interface{ return network.Interface{
ID: to.StringPtr(resourceID), ID: pointer.String(resourceID),
Name: to.StringPtr(name), Name: pointer.String(name),
Location: to.StringPtr("eastus"), Location: pointer.String("eastus"),
} }
} }
func getTestVMSSInterface(name string) network.Interface { func getTestVMSSInterface(name string) network.Interface {
resourceID := fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss/virtualMachines/0/networkInterfaces/%s", name) resourceID := fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss/virtualMachines/0/networkInterfaces/%s", name)
return network.Interface{ return network.Interface{
ID: to.StringPtr(resourceID), ID: pointer.String(resourceID),
Location: to.StringPtr("eastus"), Location: pointer.String("eastus"),
InterfacePropertiesFormat: &network.InterfacePropertiesFormat{ InterfacePropertiesFormat: &network.InterfacePropertiesFormat{
Primary: to.BoolPtr(true), Primary: pointer.Bool(true),
}, },
} }
} }

View File

@ -28,7 +28,6 @@ import (
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network"
"github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/to"
"k8s.io/client-go/util/flowcontrol" "k8s.io/client-go/util/flowcontrol"
"k8s.io/klog/v2" "k8s.io/klog/v2"
@ -36,6 +35,7 @@ import (
"k8s.io/legacy-cloud-providers/azure/clients/armclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient"
"k8s.io/legacy-cloud-providers/azure/metrics" "k8s.io/legacy-cloud-providers/azure/metrics"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
) )
var _ Interface = &Client{} var _ Interface = &Client{}
@ -197,7 +197,7 @@ func (c *Client) listLB(ctx context.Context, resourceGroupName string) ([]networ
result = append(result, page.Values()...) result = append(result, page.Values()...)
// Abort the loop when there's no nextLink in the response. // Abort the loop when there's no nextLink in the response.
if to.String(page.Response().NextLink) == "" { if pointer.StringDeref(page.Response().NextLink, "") == "" {
break break
} }
@ -341,12 +341,12 @@ func (c *Client) listResponder(resp *http.Response) (result network.LoadBalancer
// loadBalancerListResultPreparer prepares a request to retrieve the next set of results. // loadBalancerListResultPreparer prepares a request to retrieve the next set of results.
// It returns nil if no more results exist. // It returns nil if no more results exist.
func (c *Client) loadBalancerListResultPreparer(ctx context.Context, lblr network.LoadBalancerListResult) (*http.Request, error) { func (c *Client) loadBalancerListResultPreparer(ctx context.Context, lblr network.LoadBalancerListResult) (*http.Request, error) {
if lblr.NextLink == nil || len(to.String(lblr.NextLink)) < 1 { if lblr.NextLink == nil || len(pointer.StringDeref(lblr.NextLink, "")) < 1 {
return nil, nil return nil, nil
} }
decorators := []autorest.PrepareDecorator{ decorators := []autorest.PrepareDecorator{
autorest.WithBaseURL(to.String(lblr.NextLink)), autorest.WithBaseURL(pointer.StringDeref(lblr.NextLink, "")),
} }
return c.armClient.PrepareGetRequest(ctx, decorators...) return c.armClient.PrepareGetRequest(ctx, decorators...)
} }

View File

@ -31,7 +31,6 @@ import (
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network"
"github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/to"
"github.com/golang/mock/gomock" "github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -39,6 +38,7 @@ import (
"k8s.io/legacy-cloud-providers/azure/clients/armclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient"
"k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
) )
func TestNew(t *testing.T) { func TestNew(t *testing.T) {
@ -218,7 +218,7 @@ func TestListNextResultsMultiPages(t *testing.T) {
} }
lastResult := network.LoadBalancerListResult{ lastResult := network.LoadBalancerListResult{
NextLink: to.StringPtr("next"), NextLink: pointer.String("next"),
} }
for _, test := range tests { for _, test := range tests {
@ -260,7 +260,7 @@ func TestCreateOrUpdate(t *testing.T) {
StatusCode: http.StatusOK, StatusCode: http.StatusOK,
Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), Body: ioutil.NopCloser(bytes.NewReader([]byte(""))),
} }
armClient.EXPECT().PutResourceWithDecorators(gomock.Any(), to.String(lb.ID), lb, gomock.Any()).Return(response, nil).Times(1) armClient.EXPECT().PutResourceWithDecorators(gomock.Any(), pointer.StringDeref(lb.ID, ""), lb, gomock.Any()).Return(response, nil).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
lbClient := getTestLoadBalancerClient(armClient) lbClient := getTestLoadBalancerClient(armClient)
@ -291,7 +291,7 @@ func TestDelete(t *testing.T) {
for _, test := range tests { for _, test := range tests {
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
armClient.EXPECT().DeleteResource(gomock.Any(), to.String(lb.ID), "").Return(test.armClientErr) armClient.EXPECT().DeleteResource(gomock.Any(), pointer.StringDeref(lb.ID, ""), "").Return(test.armClientErr)
lbClient := getTestLoadBalancerClient(armClient) lbClient := getTestLoadBalancerClient(armClient)
rerr := lbClient.Delete(context.TODO(), "rg", "lb1") rerr := lbClient.Delete(context.TODO(), "rg", "lb1")
@ -301,9 +301,9 @@ func TestDelete(t *testing.T) {
func getTestLoadBalancer(name string) network.LoadBalancer { func getTestLoadBalancer(name string) network.LoadBalancer {
return network.LoadBalancer{ return network.LoadBalancer{
ID: to.StringPtr(fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/%s", name)), ID: pointer.String(fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/%s", name)),
Name: to.StringPtr(name), Name: pointer.String(name),
Location: to.StringPtr("eastus"), Location: pointer.String("eastus"),
} }
} }

View File

@ -28,7 +28,6 @@ import (
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network"
"github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/to"
"k8s.io/client-go/util/flowcontrol" "k8s.io/client-go/util/flowcontrol"
"k8s.io/klog/v2" "k8s.io/klog/v2"
@ -36,6 +35,7 @@ import (
"k8s.io/legacy-cloud-providers/azure/clients/armclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient"
"k8s.io/legacy-cloud-providers/azure/metrics" "k8s.io/legacy-cloud-providers/azure/metrics"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
) )
var _ Interface = &Client{} var _ Interface = &Client{}
@ -270,7 +270,7 @@ func (c *Client) listPublicIPAddress(ctx context.Context, resourceGroupName stri
result = append(result, page.Values()...) result = append(result, page.Values()...)
// Abort the loop when there's no nextLink in the response. // Abort the loop when there's no nextLink in the response.
if to.String(page.Response().NextLink) == "" { if pointer.StringDeref(page.Response().NextLink, "") == "" {
break break
} }
@ -407,12 +407,12 @@ func (c *Client) listResponder(resp *http.Response) (result network.PublicIPAddr
// publicIPAddressListResultPreparer prepares a request to retrieve the next set of results. // publicIPAddressListResultPreparer prepares a request to retrieve the next set of results.
// It returns nil if no more results exist. // It returns nil if no more results exist.
func (c *Client) publicIPAddressListResultPreparer(ctx context.Context, lr network.PublicIPAddressListResult) (*http.Request, error) { func (c *Client) publicIPAddressListResultPreparer(ctx context.Context, lr network.PublicIPAddressListResult) (*http.Request, error) {
if lr.NextLink == nil || len(to.String(lr.NextLink)) < 1 { if lr.NextLink == nil || len(pointer.StringDeref(lr.NextLink, "")) < 1 {
return nil, nil return nil, nil
} }
decorators := []autorest.PrepareDecorator{ decorators := []autorest.PrepareDecorator{
autorest.WithBaseURL(to.String(lr.NextLink)), autorest.WithBaseURL(pointer.StringDeref(lr.NextLink, "")),
} }
return c.armClient.PrepareGetRequest(ctx, decorators...) return c.armClient.PrepareGetRequest(ctx, decorators...)
} }

View File

@ -31,7 +31,6 @@ import (
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network"
"github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/to"
"github.com/golang/mock/gomock" "github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -40,6 +39,7 @@ import (
"k8s.io/legacy-cloud-providers/azure/clients/armclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient"
"k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
) )
func TestNew(t *testing.T) { func TestNew(t *testing.T) {
@ -193,7 +193,7 @@ func TestGetVMSSPublicIPAddress(t *testing.T) {
resourceID := "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss/virtualMachines/0/networkInterfaces/nic/ipconfigurations/ipConfig/publicipaddresses/pip1" resourceID := "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss/virtualMachines/0/networkInterfaces/nic/ipconfigurations/ipConfig/publicipaddresses/pip1"
testPip := network.PublicIPAddress{ testPip := network.PublicIPAddress{
PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{
IPAddress: to.StringPtr("10.10.10.10"), IPAddress: pointer.String("10.10.10.10"),
}, },
} }
pip, err := testPip.MarshalJSON() pip, err := testPip.MarshalJSON()
@ -211,7 +211,7 @@ func TestGetVMSSPublicIPAddress(t *testing.T) {
expected := network.PublicIPAddress{ expected := network.PublicIPAddress{
Response: autorest.Response{Response: response}, Response: autorest.Response{Response: response},
PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{
IPAddress: to.StringPtr("10.10.10.10"), IPAddress: pointer.String("10.10.10.10"),
}, },
} }
result, rerr := pipClient.GetVirtualMachineScaleSetPublicIPAddress(context.TODO(), "rg", "vmss", "0", "nic", "ipConfig", "pip1", "") result, rerr := pipClient.GetVirtualMachineScaleSetPublicIPAddress(context.TODO(), "rg", "vmss", "0", "nic", "ipConfig", "pip1", "")
@ -439,7 +439,7 @@ func TestListWithNextPage(t *testing.T) {
resourceID := "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses" resourceID := "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses"
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
pipList := []network.PublicIPAddress{getTestPublicIPAddress("pip1"), getTestPublicIPAddress("pip2"), getTestPublicIPAddress("pip3")} pipList := []network.PublicIPAddress{getTestPublicIPAddress("pip1"), getTestPublicIPAddress("pip2"), getTestPublicIPAddress("pip3")}
partialResponse, err := json.Marshal(network.PublicIPAddressListResult{Value: &pipList, NextLink: to.StringPtr("nextLink")}) partialResponse, err := json.Marshal(network.PublicIPAddressListResult{Value: &pipList, NextLink: pointer.String("nextLink")})
assert.NoError(t, err) assert.NoError(t, err)
pagedResponse, err := json.Marshal(network.PublicIPAddressListResult{Value: &pipList}) pagedResponse, err := json.Marshal(network.PublicIPAddressListResult{Value: &pipList})
assert.NoError(t, err) assert.NoError(t, err)
@ -517,7 +517,7 @@ func TestListNextResultsMultiPages(t *testing.T) {
} }
lastResult := network.PublicIPAddressListResult{ lastResult := network.PublicIPAddressListResult{
NextLink: to.StringPtr("next"), NextLink: pointer.String("next"),
} }
for _, test := range tests { for _, test := range tests {
@ -562,7 +562,7 @@ func TestListNextResultsMultiPagesWithListResponderError(t *testing.T) {
} }
lastResult := network.PublicIPAddressListResult{ lastResult := network.PublicIPAddressListResult{
NextLink: to.StringPtr("next"), NextLink: pointer.String("next"),
} }
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
@ -600,7 +600,7 @@ func TestCreateOrUpdate(t *testing.T) {
StatusCode: http.StatusOK, StatusCode: http.StatusOK,
Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), Body: ioutil.NopCloser(bytes.NewReader([]byte(""))),
} }
armClient.EXPECT().PutResource(gomock.Any(), to.String(pip.ID), pip).Return(response, nil).Times(1) armClient.EXPECT().PutResource(gomock.Any(), pointer.StringDeref(pip.ID, ""), pip).Return(response, nil).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
pipClient := getTestPublicIPAddressClient(armClient) pipClient := getTestPublicIPAddressClient(armClient)
@ -617,7 +617,7 @@ func TestCreateOrUpdateWithCreateOrUpdateResponderError(t *testing.T) {
StatusCode: http.StatusNotFound, StatusCode: http.StatusNotFound,
Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), Body: ioutil.NopCloser(bytes.NewReader([]byte(""))),
} }
armClient.EXPECT().PutResource(gomock.Any(), to.String(pip.ID), pip).Return(response, nil).Times(1) armClient.EXPECT().PutResource(gomock.Any(), pointer.StringDeref(pip.ID, ""), pip).Return(response, nil).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
pipClient := getTestPublicIPAddressClient(armClient) pipClient := getTestPublicIPAddressClient(armClient)
@ -677,7 +677,7 @@ func TestCreateOrUpdateThrottle(t *testing.T) {
pip := getTestPublicIPAddress("pip1") pip := getTestPublicIPAddress("pip1")
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
armClient.EXPECT().PutResource(gomock.Any(), to.String(pip.ID), pip).Return(response, throttleErr).Times(1) armClient.EXPECT().PutResource(gomock.Any(), pointer.StringDeref(pip.ID, ""), pip).Return(response, throttleErr).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
pipClient := getTestPublicIPAddressClient(armClient) pipClient := getTestPublicIPAddressClient(armClient)
@ -692,7 +692,7 @@ func TestDelete(t *testing.T) {
pip := getTestPublicIPAddress("pip1") pip := getTestPublicIPAddress("pip1")
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
armClient.EXPECT().DeleteResource(gomock.Any(), to.String(pip.ID), "").Return(nil).Times(1) armClient.EXPECT().DeleteResource(gomock.Any(), pointer.StringDeref(pip.ID, ""), "").Return(nil).Times(1)
pipClient := getTestPublicIPAddressClient(armClient) pipClient := getTestPublicIPAddressClient(armClient)
rerr := pipClient.Delete(context.TODO(), "rg", "pip1") rerr := pipClient.Delete(context.TODO(), "rg", "pip1")
@ -745,7 +745,7 @@ func TestDeleteThrottle(t *testing.T) {
pip := getTestPublicIPAddress("pip1") pip := getTestPublicIPAddress("pip1")
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
armClient.EXPECT().DeleteResource(gomock.Any(), to.String(pip.ID), "").Return(throttleErr).Times(1) armClient.EXPECT().DeleteResource(gomock.Any(), pointer.StringDeref(pip.ID, ""), "").Return(throttleErr).Times(1)
pipClient := getTestPublicIPAddressClient(armClient) pipClient := getTestPublicIPAddressClient(armClient)
rerr := pipClient.Delete(context.TODO(), "rg", "pip1") rerr := pipClient.Delete(context.TODO(), "rg", "pip1")
@ -760,9 +760,9 @@ func getFutureTime() time.Time {
func getTestPublicIPAddress(name string) network.PublicIPAddress { func getTestPublicIPAddress(name string) network.PublicIPAddress {
return network.PublicIPAddress{ return network.PublicIPAddress{
ID: to.StringPtr(fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/%s", name)), ID: pointer.String(fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/%s", name)),
Name: to.StringPtr(name), Name: pointer.String(name),
Location: to.StringPtr("eastus"), Location: pointer.String("eastus"),
} }
} }

View File

@ -29,7 +29,6 @@ import (
"time" "time"
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network"
"github.com/Azure/go-autorest/autorest/to"
"github.com/golang/mock/gomock" "github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -38,6 +37,7 @@ import (
"k8s.io/legacy-cloud-providers/azure/clients/armclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient"
"k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
) )
// 2065-01-24 05:20:00 +0000 UTC // 2065-01-24 05:20:00 +0000 UTC
@ -76,7 +76,7 @@ func TestCreateOrUpdate(t *testing.T) {
StatusCode: http.StatusOK, StatusCode: http.StatusOK,
Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), Body: ioutil.NopCloser(bytes.NewReader([]byte(""))),
} }
armClient.EXPECT().PutResourceWithDecorators(gomock.Any(), to.String(r.ID), r, gomock.Any()).Return(response, nil).Times(1) armClient.EXPECT().PutResourceWithDecorators(gomock.Any(), pointer.StringDeref(r.ID, ""), r, gomock.Any()).Return(response, nil).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
routeClient := getTestRouteClient(armClient) routeClient := getTestRouteClient(armClient)
@ -137,7 +137,7 @@ func TestCreateOrUpdateThrottle(t *testing.T) {
r := getTestRoute("r1") r := getTestRoute("r1")
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
armClient.EXPECT().PutResourceWithDecorators(gomock.Any(), to.String(r.ID), r, gomock.Any()).Return(response, throttleErr).Times(1) armClient.EXPECT().PutResourceWithDecorators(gomock.Any(), pointer.StringDeref(r.ID, ""), r, gomock.Any()).Return(response, throttleErr).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
routeClient := getTestRouteClient(armClient) routeClient := getTestRouteClient(armClient)
@ -156,7 +156,7 @@ func TestCreateOrUpdateWithCreateOrUpdateResponderError(t *testing.T) {
Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), Body: ioutil.NopCloser(bytes.NewReader([]byte(""))),
} }
armClient.EXPECT().PutResourceWithDecorators(gomock.Any(), to.String(r.ID), r, gomock.Any()).Return(response, nil).Times(1) armClient.EXPECT().PutResourceWithDecorators(gomock.Any(), pointer.StringDeref(r.ID, ""), r, gomock.Any()).Return(response, nil).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
routeClient := getTestRouteClient(armClient) routeClient := getTestRouteClient(armClient)
@ -170,7 +170,7 @@ func TestDelete(t *testing.T) {
r := getTestRoute("r1") r := getTestRoute("r1")
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
armClient.EXPECT().DeleteResource(gomock.Any(), to.String(r.ID), "").Return(nil).Times(1) armClient.EXPECT().DeleteResource(gomock.Any(), pointer.StringDeref(r.ID, ""), "").Return(nil).Times(1)
routeClient := getTestRouteClient(armClient) routeClient := getTestRouteClient(armClient)
rerr := routeClient.Delete(context.TODO(), "rg", "rt", "r1") rerr := routeClient.Delete(context.TODO(), "rg", "rt", "r1")
@ -223,7 +223,7 @@ func TestDeleteThrottle(t *testing.T) {
r := getTestRoute("r1") r := getTestRoute("r1")
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
armClient.EXPECT().DeleteResource(gomock.Any(), to.String(r.ID), "").Return(throttleErr).Times(1) armClient.EXPECT().DeleteResource(gomock.Any(), pointer.StringDeref(r.ID, ""), "").Return(throttleErr).Times(1)
routeClient := getTestRouteClient(armClient) routeClient := getTestRouteClient(armClient)
rerr := routeClient.Delete(context.TODO(), "rg", "rt", "r1") rerr := routeClient.Delete(context.TODO(), "rg", "rt", "r1")
@ -232,8 +232,8 @@ func TestDeleteThrottle(t *testing.T) {
func getTestRoute(name string) network.Route { func getTestRoute(name string) network.Route {
return network.Route{ return network.Route{
ID: to.StringPtr(fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/routeTables/rt/routes/%s", name)), ID: pointer.String(fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/routeTables/rt/routes/%s", name)),
Name: to.StringPtr(name), Name: pointer.String(name),
} }
} }

View File

@ -30,7 +30,6 @@ import (
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network"
"github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/to"
"github.com/golang/mock/gomock" "github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -39,6 +38,7 @@ import (
"k8s.io/legacy-cloud-providers/azure/clients/armclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient"
"k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
) )
// 2065-01-24 05:20:00 +0000 UTC // 2065-01-24 05:20:00 +0000 UTC
@ -203,7 +203,7 @@ func TestCreateOrUpdate(t *testing.T) {
StatusCode: http.StatusOK, StatusCode: http.StatusOK,
Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), Body: ioutil.NopCloser(bytes.NewReader([]byte(""))),
} }
armClient.EXPECT().PutResourceWithDecorators(gomock.Any(), to.String(rt1.ID), rt1, gomock.Any()).Return(response, nil).Times(1) armClient.EXPECT().PutResourceWithDecorators(gomock.Any(), pointer.StringDeref(rt1.ID, ""), rt1, gomock.Any()).Return(response, nil).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
rtClient := getTestRouteTableClient(armClient) rtClient := getTestRouteTableClient(armClient)
@ -264,7 +264,7 @@ func TestCreateOrUpdateThrottle(t *testing.T) {
rt1 := getTestRouteTable("rt1") rt1 := getTestRouteTable("rt1")
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
armClient.EXPECT().PutResourceWithDecorators(gomock.Any(), to.String(rt1.ID), rt1, gomock.Any()).Return(response, throttleErr).Times(1) armClient.EXPECT().PutResourceWithDecorators(gomock.Any(), pointer.StringDeref(rt1.ID, ""), rt1, gomock.Any()).Return(response, throttleErr).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
routetableClient := getTestRouteTableClient(armClient) routetableClient := getTestRouteTableClient(armClient)
@ -283,7 +283,7 @@ func TestCreateOrUpdateWithCreateOrUpdateResponderError(t *testing.T) {
Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), Body: ioutil.NopCloser(bytes.NewReader([]byte(""))),
} }
armClient.EXPECT().PutResourceWithDecorators(gomock.Any(), to.String(rt1.ID), rt1, gomock.Any()).Return(response, nil).Times(1) armClient.EXPECT().PutResourceWithDecorators(gomock.Any(), pointer.StringDeref(rt1.ID, ""), rt1, gomock.Any()).Return(response, nil).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
routetableClient := getTestRouteTableClient(armClient) routetableClient := getTestRouteTableClient(armClient)
@ -293,9 +293,9 @@ func TestCreateOrUpdateWithCreateOrUpdateResponderError(t *testing.T) {
func getTestRouteTable(name string) network.RouteTable { func getTestRouteTable(name string) network.RouteTable {
return network.RouteTable{ return network.RouteTable{
ID: to.StringPtr(fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/routeTables/%s", name)), ID: pointer.String(fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/routeTables/%s", name)),
Name: to.StringPtr(name), Name: pointer.String(name),
Location: to.StringPtr("eastus"), Location: pointer.String("eastus"),
} }
} }

View File

@ -28,7 +28,6 @@ import (
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network"
"github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/to"
"k8s.io/client-go/util/flowcontrol" "k8s.io/client-go/util/flowcontrol"
"k8s.io/klog/v2" "k8s.io/klog/v2"
@ -36,6 +35,7 @@ import (
"k8s.io/legacy-cloud-providers/azure/clients/armclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient"
"k8s.io/legacy-cloud-providers/azure/metrics" "k8s.io/legacy-cloud-providers/azure/metrics"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
) )
var _ Interface = &Client{} var _ Interface = &Client{}
@ -197,7 +197,7 @@ func (c *Client) listSecurityGroup(ctx context.Context, resourceGroupName string
result = append(result, page.Values()...) result = append(result, page.Values()...)
// Abort the loop when there's no nextLink in the response. // Abort the loop when there's no nextLink in the response.
if to.String(page.Response().NextLink) == "" { if pointer.StringDeref(page.Response().NextLink, "") == "" {
break break
} }
@ -341,12 +341,12 @@ func (c *Client) listResponder(resp *http.Response) (result network.SecurityGrou
// securityGroupListResultPreparer prepares a request to retrieve the next set of results. // securityGroupListResultPreparer prepares a request to retrieve the next set of results.
// It returns nil if no more results exist. // It returns nil if no more results exist.
func (c *Client) securityGroupListResultPreparer(ctx context.Context, sglr network.SecurityGroupListResult) (*http.Request, error) { func (c *Client) securityGroupListResultPreparer(ctx context.Context, sglr network.SecurityGroupListResult) (*http.Request, error) {
if sglr.NextLink == nil || len(to.String(sglr.NextLink)) < 1 { if sglr.NextLink == nil || len(pointer.StringDeref(sglr.NextLink, "")) < 1 {
return nil, nil return nil, nil
} }
decorators := []autorest.PrepareDecorator{ decorators := []autorest.PrepareDecorator{
autorest.WithBaseURL(to.String(sglr.NextLink)), autorest.WithBaseURL(pointer.StringDeref(sglr.NextLink, "")),
} }
return c.armClient.PrepareGetRequest(ctx, decorators...) return c.armClient.PrepareGetRequest(ctx, decorators...)
} }

View File

@ -31,7 +31,6 @@ import (
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network"
"github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/to"
"github.com/golang/mock/gomock" "github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -40,6 +39,7 @@ import (
"k8s.io/legacy-cloud-providers/azure/clients/armclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient"
"k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
) )
// 2065-01-24 05:20:00 +0000 UTC // 2065-01-24 05:20:00 +0000 UTC
@ -238,7 +238,7 @@ func TestListNextResultsMultiPages(t *testing.T) {
} }
lastResult := network.SecurityGroupListResult{ lastResult := network.SecurityGroupListResult{
NextLink: to.StringPtr("next"), NextLink: pointer.String("next"),
} }
for _, test := range tests { for _, test := range tests {
@ -283,7 +283,7 @@ func TestListNextResultsMultiPagesWithListResponderError(t *testing.T) {
} }
lastResult := network.SecurityGroupListResult{ lastResult := network.SecurityGroupListResult{
NextLink: to.StringPtr("next"), NextLink: pointer.String("next"),
} }
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
@ -339,7 +339,7 @@ func TestListWithNextPage(t *testing.T) {
resourceID := "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/networkSecurityGroups" resourceID := "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/networkSecurityGroups"
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
nsgList := []network.SecurityGroup{getTestSecurityGroup("nsg1"), getTestSecurityGroup("nsg2"), getTestSecurityGroup("nsg3")} nsgList := []network.SecurityGroup{getTestSecurityGroup("nsg1"), getTestSecurityGroup("nsg2"), getTestSecurityGroup("nsg3")}
partialResponse, err := json.Marshal(network.SecurityGroupListResult{Value: &nsgList, NextLink: to.StringPtr("nextLink")}) partialResponse, err := json.Marshal(network.SecurityGroupListResult{Value: &nsgList, NextLink: pointer.String("nextLink")})
assert.NoError(t, err) assert.NoError(t, err)
pagedResponse, err := json.Marshal(network.SecurityGroupListResult{Value: &nsgList}) pagedResponse, err := json.Marshal(network.SecurityGroupListResult{Value: &nsgList})
assert.NoError(t, err) assert.NoError(t, err)
@ -432,7 +432,7 @@ func TestCreateOrUpdate(t *testing.T) {
StatusCode: http.StatusOK, StatusCode: http.StatusOK,
Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), Body: ioutil.NopCloser(bytes.NewReader([]byte(""))),
} }
armClient.EXPECT().PutResourceWithDecorators(gomock.Any(), to.String(nsg.ID), nsg, gomock.Any()).Return(response, nil).Times(1) armClient.EXPECT().PutResourceWithDecorators(gomock.Any(), pointer.StringDeref(nsg.ID, ""), nsg, gomock.Any()).Return(response, nil).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
nsgClient := getTestSecurityGroupClient(armClient) nsgClient := getTestSecurityGroupClient(armClient)
@ -449,7 +449,7 @@ func TestCreateOrUpdateWithCreateOrUpdateResponderError(t *testing.T) {
StatusCode: http.StatusNotFound, StatusCode: http.StatusNotFound,
Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), Body: ioutil.NopCloser(bytes.NewReader([]byte(""))),
} }
armClient.EXPECT().PutResourceWithDecorators(gomock.Any(), to.String(nsg.ID), nsg, gomock.Any()).Return(response, nil).Times(1) armClient.EXPECT().PutResourceWithDecorators(gomock.Any(), pointer.StringDeref(nsg.ID, ""), nsg, gomock.Any()).Return(response, nil).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
nsgClient := getTestSecurityGroupClient(armClient) nsgClient := getTestSecurityGroupClient(armClient)
@ -511,7 +511,7 @@ func TestCreateOrUpdateThrottle(t *testing.T) {
nsg := getTestSecurityGroup("nsg1") nsg := getTestSecurityGroup("nsg1")
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
armClient.EXPECT().PutResourceWithDecorators(gomock.Any(), to.String(nsg.ID), nsg, gomock.Any()).Return(response, throttleErr).Times(1) armClient.EXPECT().PutResourceWithDecorators(gomock.Any(), pointer.StringDeref(nsg.ID, ""), nsg, gomock.Any()).Return(response, throttleErr).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
nsgClient := getTestSecurityGroupClient(armClient) nsgClient := getTestSecurityGroupClient(armClient)
@ -526,7 +526,7 @@ func TestDelete(t *testing.T) {
r := getTestSecurityGroup("nsg1") r := getTestSecurityGroup("nsg1")
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
armClient.EXPECT().DeleteResource(gomock.Any(), to.String(r.ID), "").Return(nil).Times(1) armClient.EXPECT().DeleteResource(gomock.Any(), pointer.StringDeref(r.ID, ""), "").Return(nil).Times(1)
rtClient := getTestSecurityGroupClient(armClient) rtClient := getTestSecurityGroupClient(armClient)
rerr := rtClient.Delete(context.TODO(), "rg", "nsg1") rerr := rtClient.Delete(context.TODO(), "rg", "nsg1")
@ -581,7 +581,7 @@ func TestDeleteThrottle(t *testing.T) {
nsg := getTestSecurityGroup("nsg1") nsg := getTestSecurityGroup("nsg1")
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
armClient.EXPECT().DeleteResource(gomock.Any(), to.String(nsg.ID), "").Return(throttleErr).Times(1) armClient.EXPECT().DeleteResource(gomock.Any(), pointer.StringDeref(nsg.ID, ""), "").Return(throttleErr).Times(1)
nsgClient := getTestSecurityGroupClient(armClient) nsgClient := getTestSecurityGroupClient(armClient)
rerr := nsgClient.Delete(context.TODO(), "rg", "nsg1") rerr := nsgClient.Delete(context.TODO(), "rg", "nsg1")
@ -591,9 +591,9 @@ func TestDeleteThrottle(t *testing.T) {
func getTestSecurityGroup(name string) network.SecurityGroup { func getTestSecurityGroup(name string) network.SecurityGroup {
return network.SecurityGroup{ return network.SecurityGroup{
ID: to.StringPtr(fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/networkSecurityGroups/%s", name)), ID: pointer.String(fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/networkSecurityGroups/%s", name)),
Name: to.StringPtr(name), Name: pointer.String(name),
Location: to.StringPtr("eastus"), Location: pointer.String("eastus"),
} }
} }

View File

@ -28,7 +28,6 @@ import (
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute"
"github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/to"
"k8s.io/client-go/util/flowcontrol" "k8s.io/client-go/util/flowcontrol"
"k8s.io/klog/v2" "k8s.io/klog/v2"
@ -36,6 +35,7 @@ import (
"k8s.io/legacy-cloud-providers/azure/clients/armclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient"
"k8s.io/legacy-cloud-providers/azure/metrics" "k8s.io/legacy-cloud-providers/azure/metrics"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
) )
var _ Interface = &Client{} var _ Interface = &Client{}
@ -308,7 +308,7 @@ func (c *Client) listSnapshotsByResourceGroup(ctx context.Context, resourceGroup
result = append(result, page.Values()...) result = append(result, page.Values()...)
// Abort the loop when there's no nextLink in the response. // Abort the loop when there's no nextLink in the response.
if to.String(page.Response().NextLink) == "" { if pointer.StringDeref(page.Response().NextLink, "") == "" {
break break
} }
@ -334,12 +334,12 @@ func (c *Client) listResponder(resp *http.Response) (result compute.SnapshotList
// SnapshotListResultPreparer prepares a request to retrieve the next set of results. // SnapshotListResultPreparer prepares a request to retrieve the next set of results.
// It returns nil if no more results exist. // It returns nil if no more results exist.
func (c *Client) SnapshotListResultPreparer(ctx context.Context, lr compute.SnapshotList) (*http.Request, error) { func (c *Client) SnapshotListResultPreparer(ctx context.Context, lr compute.SnapshotList) (*http.Request, error) {
if lr.NextLink == nil || len(to.String(lr.NextLink)) < 1 { if lr.NextLink == nil || len(pointer.StringDeref(lr.NextLink, "")) < 1 {
return nil, nil return nil, nil
} }
decorators := []autorest.PrepareDecorator{ decorators := []autorest.PrepareDecorator{
autorest.WithBaseURL(to.String(lr.NextLink)), autorest.WithBaseURL(pointer.StringDeref(lr.NextLink, "")),
} }
return c.armClient.PrepareGetRequest(ctx, decorators...) return c.armClient.PrepareGetRequest(ctx, decorators...)
} }

View File

@ -31,7 +31,6 @@ import (
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute"
"github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/to"
"github.com/golang/mock/gomock" "github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -40,6 +39,7 @@ import (
"k8s.io/legacy-cloud-providers/azure/clients/armclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient"
"k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
) )
func TestNew(t *testing.T) { func TestNew(t *testing.T) {
@ -303,7 +303,7 @@ func TestListWithNextPage(t *testing.T) {
resourceID := "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/snapshots" resourceID := "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/snapshots"
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
snList := []compute.Snapshot{getTestSnapshot("sn1"), getTestSnapshot("sn2"), getTestSnapshot("sn3")} snList := []compute.Snapshot{getTestSnapshot("sn1"), getTestSnapshot("sn2"), getTestSnapshot("sn3")}
partialResponse, err := json.Marshal(compute.SnapshotList{Value: &snList, NextLink: to.StringPtr("nextLink")}) partialResponse, err := json.Marshal(compute.SnapshotList{Value: &snList, NextLink: pointer.String("nextLink")})
assert.NoError(t, err) assert.NoError(t, err)
pagedResponse, err := json.Marshal(compute.SnapshotList{Value: &snList}) pagedResponse, err := json.Marshal(compute.SnapshotList{Value: &snList})
assert.NoError(t, err) assert.NoError(t, err)
@ -381,7 +381,7 @@ func TestListNextResultsMultiPages(t *testing.T) {
} }
lastResult := compute.SnapshotList{ lastResult := compute.SnapshotList{
NextLink: to.StringPtr("next"), NextLink: pointer.String("next"),
} }
for _, test := range tests { for _, test := range tests {
@ -426,7 +426,7 @@ func TestListNextResultsMultiPagesWithListResponderError(t *testing.T) {
} }
lastResult := compute.SnapshotList{ lastResult := compute.SnapshotList{
NextLink: to.StringPtr("next"), NextLink: pointer.String("next"),
} }
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
@ -464,7 +464,7 @@ func TestCreateOrUpdate(t *testing.T) {
StatusCode: http.StatusOK, StatusCode: http.StatusOK,
Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), Body: ioutil.NopCloser(bytes.NewReader([]byte(""))),
} }
armClient.EXPECT().PutResource(gomock.Any(), to.String(sn.ID), sn).Return(response, nil).Times(1) armClient.EXPECT().PutResource(gomock.Any(), pointer.StringDeref(sn.ID, ""), sn).Return(response, nil).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
snClient := getTestSnapshotClient(armClient) snClient := getTestSnapshotClient(armClient)
@ -481,7 +481,7 @@ func TestCreateOrUpdateWithCreateOrUpdateResponderError(t *testing.T) {
StatusCode: http.StatusNotFound, StatusCode: http.StatusNotFound,
Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), Body: ioutil.NopCloser(bytes.NewReader([]byte(""))),
} }
armClient.EXPECT().PutResource(gomock.Any(), to.String(sn.ID), sn).Return(response, nil).Times(1) armClient.EXPECT().PutResource(gomock.Any(), pointer.StringDeref(sn.ID, ""), sn).Return(response, nil).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
snClient := getTestSnapshotClient(armClient) snClient := getTestSnapshotClient(armClient)
@ -541,7 +541,7 @@ func TestCreateOrUpdateThrottle(t *testing.T) {
sn := getTestSnapshot("sn1") sn := getTestSnapshot("sn1")
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
armClient.EXPECT().PutResource(gomock.Any(), to.String(sn.ID), sn).Return(response, throttleErr).Times(1) armClient.EXPECT().PutResource(gomock.Any(), pointer.StringDeref(sn.ID, ""), sn).Return(response, throttleErr).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
snClient := getTestSnapshotClient(armClient) snClient := getTestSnapshotClient(armClient)
@ -556,7 +556,7 @@ func TestDelete(t *testing.T) {
r := getTestSnapshot("sn1") r := getTestSnapshot("sn1")
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
armClient.EXPECT().DeleteResource(gomock.Any(), to.String(r.ID), "").Return(nil).Times(1) armClient.EXPECT().DeleteResource(gomock.Any(), pointer.StringDeref(r.ID, ""), "").Return(nil).Times(1)
rtClient := getTestSnapshotClient(armClient) rtClient := getTestSnapshotClient(armClient)
rerr := rtClient.Delete(context.TODO(), "rg", "sn1") rerr := rtClient.Delete(context.TODO(), "rg", "sn1")
@ -609,7 +609,7 @@ func TestDeleteThrottle(t *testing.T) {
sn := getTestSnapshot("sn1") sn := getTestSnapshot("sn1")
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
armClient.EXPECT().DeleteResource(gomock.Any(), to.String(sn.ID), "").Return(throttleErr).Times(1) armClient.EXPECT().DeleteResource(gomock.Any(), pointer.StringDeref(sn.ID, ""), "").Return(throttleErr).Times(1)
snClient := getTestSnapshotClient(armClient) snClient := getTestSnapshotClient(armClient)
rerr := snClient.Delete(context.TODO(), "rg", "sn1") rerr := snClient.Delete(context.TODO(), "rg", "sn1")
@ -619,9 +619,9 @@ func TestDeleteThrottle(t *testing.T) {
func getTestSnapshot(name string) compute.Snapshot { func getTestSnapshot(name string) compute.Snapshot {
return compute.Snapshot{ return compute.Snapshot{
ID: to.StringPtr(fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/snapshots/%s", name)), ID: pointer.String(fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/snapshots/%s", name)),
Name: to.StringPtr(name), Name: pointer.String(name),
Location: to.StringPtr("eastus"), Location: pointer.String("eastus"),
} }
} }

View File

@ -29,7 +29,6 @@ import (
"github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2019-06-01/storage" "github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2019-06-01/storage"
"github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/to"
"k8s.io/client-go/util/flowcontrol" "k8s.io/client-go/util/flowcontrol"
"k8s.io/klog/v2" "k8s.io/klog/v2"
@ -37,6 +36,7 @@ import (
"k8s.io/legacy-cloud-providers/azure/clients/armclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient"
"k8s.io/legacy-cloud-providers/azure/metrics" "k8s.io/legacy-cloud-providers/azure/metrics"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
) )
var _ Interface = &Client{} var _ Interface = &Client{}
@ -374,7 +374,7 @@ func (c *Client) ListStorageAccountByResourceGroup(ctx context.Context, resource
result = append(result, page.Values()...) result = append(result, page.Values()...)
// Abort the loop when there's no nextLink in the response. // Abort the loop when there's no nextLink in the response.
if to.String(page.Response().NextLink) == "" { if pointer.StringDeref(page.Response().NextLink, "") == "" {
break break
} }
@ -400,12 +400,12 @@ func (c *Client) listResponder(resp *http.Response) (result storage.AccountListR
// StorageAccountResultPreparer prepares a request to retrieve the next set of results. // StorageAccountResultPreparer prepares a request to retrieve the next set of results.
// It returns nil if no more results exist. // It returns nil if no more results exist.
func (c *Client) StorageAccountResultPreparer(ctx context.Context, lr storage.AccountListResult) (*http.Request, error) { func (c *Client) StorageAccountResultPreparer(ctx context.Context, lr storage.AccountListResult) (*http.Request, error) {
if lr.NextLink == nil || len(to.String(lr.NextLink)) < 1 { if lr.NextLink == nil || len(pointer.StringDeref(lr.NextLink, "")) < 1 {
return nil, nil return nil, nil
} }
decorators := []autorest.PrepareDecorator{ decorators := []autorest.PrepareDecorator{
autorest.WithBaseURL(to.String(lr.NextLink)), autorest.WithBaseURL(pointer.StringDeref(lr.NextLink, "")),
} }
return c.armClient.PrepareGetRequest(ctx, decorators...) return c.armClient.PrepareGetRequest(ctx, decorators...)
} }

View File

@ -31,7 +31,6 @@ import (
"github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2019-06-01/storage" "github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2019-06-01/storage"
"github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/to"
"github.com/golang/mock/gomock" "github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"k8s.io/client-go/util/flowcontrol" "k8s.io/client-go/util/flowcontrol"
@ -39,6 +38,7 @@ import (
"k8s.io/legacy-cloud-providers/azure/clients/armclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient"
"k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
) )
// 2065-01-24 05:20:00 +0000 UTC // 2065-01-24 05:20:00 +0000 UTC
@ -134,7 +134,7 @@ func TestAllNeverRateLimiter(t *testing.T) {
assert.Equal(t, saErr3, rerr3) assert.Equal(t, saErr3, rerr3)
sa := storage.AccountCreateParameters{ sa := storage.AccountCreateParameters{
Location: to.StringPtr("eastus"), Location: pointer.String("eastus"),
} }
rerr4 := saClient.Create(context.TODO(), "rg", "sa1", sa) rerr4 := saClient.Create(context.TODO(), "rg", "sa1", sa)
@ -194,7 +194,7 @@ func TestAllRetryAfterReader(t *testing.T) {
assert.Equal(t, saErr3, rerr3) assert.Equal(t, saErr3, rerr3)
sa := storage.AccountCreateParameters{ sa := storage.AccountCreateParameters{
Location: to.StringPtr("eastus"), Location: pointer.String("eastus"),
} }
rerr4 := saClient.Create(context.TODO(), "rg", "sa1", sa) rerr4 := saClient.Create(context.TODO(), "rg", "sa1", sa)
@ -221,7 +221,7 @@ func TestAllThrottle(t *testing.T) {
} }
sa := storage.AccountCreateParameters{ sa := storage.AccountCreateParameters{
Location: to.StringPtr("eastus"), Location: pointer.String("eastus"),
} }
r := getTestStorageAccount("sa1") r := getTestStorageAccount("sa1")
@ -230,7 +230,7 @@ func TestAllThrottle(t *testing.T) {
armClient.EXPECT().PostResource(gomock.Any(), resourceID, "listKeys", struct{}{}).Return(response, throttleErr).Times(1) armClient.EXPECT().PostResource(gomock.Any(), resourceID, "listKeys", struct{}{}).Return(response, throttleErr).Times(1)
armClient.EXPECT().GetResource(gomock.Any(), resourceID, "").Return(response, throttleErr).Times(1) armClient.EXPECT().GetResource(gomock.Any(), resourceID, "").Return(response, throttleErr).Times(1)
armClient.EXPECT().PutResource(gomock.Any(), resourceID, sa).Return(response, throttleErr).Times(1) armClient.EXPECT().PutResource(gomock.Any(), resourceID, sa).Return(response, throttleErr).Times(1)
armClient.EXPECT().DeleteResource(gomock.Any(), to.String(r.ID), "").Return(throttleErr).Times(1) armClient.EXPECT().DeleteResource(gomock.Any(), pointer.StringDeref(r.ID, ""), "").Return(throttleErr).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(3) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(3)
saClient := getTestStorageAccountClient(armClient) saClient := getTestStorageAccountClient(armClient)
@ -361,7 +361,7 @@ func TestListNextResultsMultiPages(t *testing.T) {
} }
lastResult := storage.AccountListResult{ lastResult := storage.AccountListResult{
NextLink: to.StringPtr("next"), NextLink: pointer.String("next"),
} }
for _, test := range tests { for _, test := range tests {
@ -406,7 +406,7 @@ func TestListNextResultsMultiPagesWithListResponderError(t *testing.T) {
} }
lastResult := storage.AccountListResult{ lastResult := storage.AccountListResult{
NextLink: to.StringPtr("next"), NextLink: pointer.String("next"),
} }
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
@ -483,7 +483,7 @@ func TestCreate(t *testing.T) {
resourceID := "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Storage/storageAccounts/sa1" resourceID := "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Storage/storageAccounts/sa1"
sa := storage.AccountCreateParameters{ sa := storage.AccountCreateParameters{
Location: to.StringPtr("eastus"), Location: pointer.String("eastus"),
} }
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
response := &http.Response{ response := &http.Response{
@ -504,7 +504,7 @@ func TestCreateResponderError(t *testing.T) {
resourceID := "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Storage/storageAccounts/sa1" resourceID := "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Storage/storageAccounts/sa1"
sa := storage.AccountCreateParameters{ sa := storage.AccountCreateParameters{
Location: to.StringPtr("eastus"), Location: pointer.String("eastus"),
} }
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
response := &http.Response{ response := &http.Response{
@ -525,7 +525,7 @@ func TestDelete(t *testing.T) {
r := getTestStorageAccount("sa1") r := getTestStorageAccount("sa1")
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
armClient.EXPECT().DeleteResource(gomock.Any(), to.String(r.ID), "").Return(nil).Times(1) armClient.EXPECT().DeleteResource(gomock.Any(), pointer.StringDeref(r.ID, ""), "").Return(nil).Times(1)
rtClient := getTestStorageAccountClient(armClient) rtClient := getTestStorageAccountClient(armClient)
rerr := rtClient.Delete(context.TODO(), "rg", "sa1") rerr := rtClient.Delete(context.TODO(), "rg", "sa1")
@ -534,9 +534,9 @@ func TestDelete(t *testing.T) {
func getTestStorageAccount(name string) storage.Account { func getTestStorageAccount(name string) storage.Account {
return storage.Account{ return storage.Account{
ID: to.StringPtr(fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Storage/storageAccounts/%s", name)), ID: pointer.String(fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Storage/storageAccounts/%s", name)),
Name: to.StringPtr(name), Name: pointer.String(name),
Location: to.StringPtr("eastus"), Location: pointer.String("eastus"),
} }
} }

View File

@ -27,7 +27,6 @@ import (
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network"
"github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/to"
"k8s.io/client-go/util/flowcontrol" "k8s.io/client-go/util/flowcontrol"
"k8s.io/klog/v2" "k8s.io/klog/v2"
@ -35,6 +34,7 @@ import (
"k8s.io/legacy-cloud-providers/azure/clients/armclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient"
"k8s.io/legacy-cloud-providers/azure/metrics" "k8s.io/legacy-cloud-providers/azure/metrics"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
) )
var _ Interface = &Client{} var _ Interface = &Client{}
@ -202,7 +202,7 @@ func (c *Client) listSubnet(ctx context.Context, resourceGroupName string, virtu
result = append(result, page.Values()...) result = append(result, page.Values()...)
// Abort the loop when there's no nextLink in the response. // Abort the loop when there's no nextLink in the response.
if to.String(page.Response().NextLink) == "" { if pointer.StringDeref(page.Response().NextLink, "") == "" {
break break
} }
@ -341,12 +341,12 @@ func (c *Client) listResponder(resp *http.Response) (result network.SubnetListRe
// subnetListResultPreparer prepares a request to retrieve the next set of results. // subnetListResultPreparer prepares a request to retrieve the next set of results.
// It returns nil if no more results exist. // It returns nil if no more results exist.
func (c *Client) subnetListResultPreparer(ctx context.Context, lblr network.SubnetListResult) (*http.Request, error) { func (c *Client) subnetListResultPreparer(ctx context.Context, lblr network.SubnetListResult) (*http.Request, error) {
if lblr.NextLink == nil || len(to.String(lblr.NextLink)) < 1 { if lblr.NextLink == nil || len(pointer.StringDeref(lblr.NextLink, "")) < 1 {
return nil, nil return nil, nil
} }
decorators := []autorest.PrepareDecorator{ decorators := []autorest.PrepareDecorator{
autorest.WithBaseURL(to.String(lblr.NextLink)), autorest.WithBaseURL(pointer.StringDeref(lblr.NextLink, "")),
} }
return c.armClient.PrepareGetRequest(ctx, decorators...) return c.armClient.PrepareGetRequest(ctx, decorators...)
} }

View File

@ -31,7 +31,6 @@ import (
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network"
"github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/to"
"github.com/golang/mock/gomock" "github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -40,6 +39,7 @@ import (
"k8s.io/legacy-cloud-providers/azure/clients/armclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient"
"k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
) )
func TestNew(t *testing.T) { func TestNew(t *testing.T) {
@ -69,7 +69,7 @@ func TestGet(t *testing.T) {
resourceID := "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks/vnet/subnets/subnet1" resourceID := "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks/vnet/subnets/subnet1"
testSubnet := network.Subnet{ testSubnet := network.Subnet{
Name: to.StringPtr("subnet1"), Name: pointer.String("subnet1"),
} }
subnet, err := testSubnet.MarshalJSON() subnet, err := testSubnet.MarshalJSON()
assert.NoError(t, err) assert.NoError(t, err)
@ -84,7 +84,7 @@ func TestGet(t *testing.T) {
expected := network.Subnet{ expected := network.Subnet{
Response: autorest.Response{Response: response}, Response: autorest.Response{Response: response},
Name: to.StringPtr("subnet1"), Name: pointer.String("subnet1"),
} }
subnetClient := getTestSubnetClient(armClient) subnetClient := getTestSubnetClient(armClient)
result, rerr := subnetClient.Get(context.TODO(), "rg", "vnet", "subnet1", "") result, rerr := subnetClient.Get(context.TODO(), "rg", "vnet", "subnet1", "")
@ -313,7 +313,7 @@ func TestListWithNextPage(t *testing.T) {
resourceID := "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks/vnet/subnets" resourceID := "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks/vnet/subnets"
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
subnetList := []network.Subnet{getTestSubnet("subnet1"), getTestSubnet("subnet2"), getTestSubnet("subnet3")} subnetList := []network.Subnet{getTestSubnet("subnet1"), getTestSubnet("subnet2"), getTestSubnet("subnet3")}
partialResponse, err := json.Marshal(network.SubnetListResult{Value: &subnetList, NextLink: to.StringPtr("nextLink")}) partialResponse, err := json.Marshal(network.SubnetListResult{Value: &subnetList, NextLink: pointer.String("nextLink")})
assert.NoError(t, err) assert.NoError(t, err)
pagedResponse, err := json.Marshal(network.SubnetListResult{Value: &subnetList}) pagedResponse, err := json.Marshal(network.SubnetListResult{Value: &subnetList})
assert.NoError(t, err) assert.NoError(t, err)
@ -391,7 +391,7 @@ func TestListNextResultsMultiPages(t *testing.T) {
} }
lastResult := network.SubnetListResult{ lastResult := network.SubnetListResult{
NextLink: to.StringPtr("next"), NextLink: pointer.String("next"),
} }
for _, test := range tests { for _, test := range tests {
@ -436,7 +436,7 @@ func TestListNextResultsMultiPagesWithListResponderError(t *testing.T) {
} }
lastResult := network.SubnetListResult{ lastResult := network.SubnetListResult{
NextLink: to.StringPtr("next"), NextLink: pointer.String("next"),
} }
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
@ -474,7 +474,7 @@ func TestCreateOrUpdate(t *testing.T) {
StatusCode: http.StatusOK, StatusCode: http.StatusOK,
Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), Body: ioutil.NopCloser(bytes.NewReader([]byte(""))),
} }
armClient.EXPECT().PutResource(gomock.Any(), to.String(subnet.ID), subnet).Return(response, nil).Times(1) armClient.EXPECT().PutResource(gomock.Any(), pointer.StringDeref(subnet.ID, ""), subnet).Return(response, nil).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
subnetClient := getTestSubnetClient(armClient) subnetClient := getTestSubnetClient(armClient)
@ -491,7 +491,7 @@ func TestCreateOrUpdateWithCreateOrUpdateResponderError(t *testing.T) {
StatusCode: http.StatusNotFound, StatusCode: http.StatusNotFound,
Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), Body: ioutil.NopCloser(bytes.NewReader([]byte(""))),
} }
armClient.EXPECT().PutResource(gomock.Any(), to.String(subnet.ID), subnet).Return(response, nil).Times(1) armClient.EXPECT().PutResource(gomock.Any(), pointer.StringDeref(subnet.ID, ""), subnet).Return(response, nil).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
subnetClient := getTestSubnetClient(armClient) subnetClient := getTestSubnetClient(armClient)
@ -551,7 +551,7 @@ func TestCreateOrUpdateThrottle(t *testing.T) {
subnet := getTestSubnet("subnet1") subnet := getTestSubnet("subnet1")
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
armClient.EXPECT().PutResource(gomock.Any(), to.String(subnet.ID), subnet).Return(response, throttleErr).Times(1) armClient.EXPECT().PutResource(gomock.Any(), pointer.StringDeref(subnet.ID, ""), subnet).Return(response, throttleErr).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
subnetClient := getTestSubnetClient(armClient) subnetClient := getTestSubnetClient(armClient)
@ -566,7 +566,7 @@ func TestDelete(t *testing.T) {
r := getTestSubnet("subnet1") r := getTestSubnet("subnet1")
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
armClient.EXPECT().DeleteResource(gomock.Any(), to.String(r.ID), "").Return(nil).Times(1) armClient.EXPECT().DeleteResource(gomock.Any(), pointer.StringDeref(r.ID, ""), "").Return(nil).Times(1)
subnetClient := getTestSubnetClient(armClient) subnetClient := getTestSubnetClient(armClient)
rerr := subnetClient.Delete(context.TODO(), "rg", "vnet", "subnet1") rerr := subnetClient.Delete(context.TODO(), "rg", "vnet", "subnet1")
@ -619,7 +619,7 @@ func TestDeleteThrottle(t *testing.T) {
subnet := getTestSubnet("subnet1") subnet := getTestSubnet("subnet1")
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
armClient.EXPECT().DeleteResource(gomock.Any(), to.String(subnet.ID), "").Return(throttleErr).Times(1) armClient.EXPECT().DeleteResource(gomock.Any(), pointer.StringDeref(subnet.ID, ""), "").Return(throttleErr).Times(1)
subnetClient := getTestSubnetClient(armClient) subnetClient := getTestSubnetClient(armClient)
rerr := subnetClient.Delete(context.TODO(), "rg", "vnet", "subnet1") rerr := subnetClient.Delete(context.TODO(), "rg", "vnet", "subnet1")
@ -629,8 +629,8 @@ func TestDeleteThrottle(t *testing.T) {
func getTestSubnet(name string) network.Subnet { func getTestSubnet(name string) network.Subnet {
return network.Subnet{ return network.Subnet{
ID: to.StringPtr(fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks/vnet/subnets/%s", name)), ID: pointer.String(fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks/vnet/subnets/%s", name)),
Name: to.StringPtr(name), Name: pointer.String(name),
} }
} }

View File

@ -28,7 +28,6 @@ import (
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute"
"github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/to"
"k8s.io/client-go/util/flowcontrol" "k8s.io/client-go/util/flowcontrol"
"k8s.io/klog/v2" "k8s.io/klog/v2"
@ -36,6 +35,7 @@ import (
"k8s.io/legacy-cloud-providers/azure/clients/armclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient"
"k8s.io/legacy-cloud-providers/azure/metrics" "k8s.io/legacy-cloud-providers/azure/metrics"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
) )
var _ Interface = &Client{} var _ Interface = &Client{}
@ -199,7 +199,7 @@ func (c *Client) listVM(ctx context.Context, resourceGroupName string) ([]comput
result = append(result, page.Values()...) result = append(result, page.Values()...)
// Abort the loop when there's no nextLink in the response. // Abort the loop when there's no nextLink in the response.
if to.String(page.Response().NextLink) == "" { if pointer.StringDeref(page.Response().NextLink, "") == "" {
break break
} }
@ -296,12 +296,12 @@ func (c *Client) listResponder(resp *http.Response) (result compute.VirtualMachi
// vmListResultPreparer prepares a request to retrieve the next set of results. // vmListResultPreparer prepares a request to retrieve the next set of results.
// It returns nil if no more results exist. // It returns nil if no more results exist.
func (c *Client) vmListResultPreparer(ctx context.Context, vmlr compute.VirtualMachineListResult) (*http.Request, error) { func (c *Client) vmListResultPreparer(ctx context.Context, vmlr compute.VirtualMachineListResult) (*http.Request, error) {
if vmlr.NextLink == nil || len(to.String(vmlr.NextLink)) < 1 { if vmlr.NextLink == nil || len(pointer.StringDeref(vmlr.NextLink, "")) < 1 {
return nil, nil return nil, nil
} }
decorators := []autorest.PrepareDecorator{ decorators := []autorest.PrepareDecorator{
autorest.WithBaseURL(to.String(vmlr.NextLink)), autorest.WithBaseURL(pointer.StringDeref(vmlr.NextLink, "")),
} }
return c.armClient.PrepareGetRequest(ctx, decorators...) return c.armClient.PrepareGetRequest(ctx, decorators...)
} }

View File

@ -31,7 +31,6 @@ import (
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute"
"github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/to"
"github.com/golang/mock/gomock" "github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -40,6 +39,7 @@ import (
"k8s.io/legacy-cloud-providers/azure/clients/armclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient"
"k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
) )
func TestNew(t *testing.T) { func TestNew(t *testing.T) {
@ -303,7 +303,7 @@ func TestListWithNextPage(t *testing.T) {
resourceID := "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines" resourceID := "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines"
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
vmList := []compute.VirtualMachine{getTestVM("vm1"), getTestVM("vm2"), getTestVM("vm3")} vmList := []compute.VirtualMachine{getTestVM("vm1"), getTestVM("vm2"), getTestVM("vm3")}
partialResponse, err := json.Marshal(compute.VirtualMachineListResult{Value: &vmList, NextLink: to.StringPtr("nextLink")}) partialResponse, err := json.Marshal(compute.VirtualMachineListResult{Value: &vmList, NextLink: pointer.String("nextLink")})
assert.NoError(t, err) assert.NoError(t, err)
pagedResponse, err := json.Marshal(compute.VirtualMachineListResult{Value: &vmList}) pagedResponse, err := json.Marshal(compute.VirtualMachineListResult{Value: &vmList})
assert.NoError(t, err) assert.NoError(t, err)
@ -388,7 +388,7 @@ func TestListNextResultsMultiPages(t *testing.T) {
} }
lastResult := compute.VirtualMachineListResult{ lastResult := compute.VirtualMachineListResult{
NextLink: to.StringPtr("next"), NextLink: pointer.String("next"),
} }
for _, test := range tests { for _, test := range tests {
@ -442,7 +442,7 @@ func TestListNextResultsMultiPagesWithListResponderError(t *testing.T) {
} }
lastResult := compute.VirtualMachineListResult{ lastResult := compute.VirtualMachineListResult{
NextLink: to.StringPtr("next"), NextLink: pointer.String("next"),
} }
for _, test := range tests { for _, test := range tests {
@ -586,7 +586,7 @@ func TestCreateOrUpdate(t *testing.T) {
StatusCode: http.StatusOK, StatusCode: http.StatusOK,
Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), Body: ioutil.NopCloser(bytes.NewReader([]byte(""))),
} }
armClient.EXPECT().PutResource(gomock.Any(), to.String(testVM.ID), testVM).Return(response, nil).Times(1) armClient.EXPECT().PutResource(gomock.Any(), pointer.StringDeref(testVM.ID, ""), testVM).Return(response, nil).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
vmClient := getTestVMClient(armClient) vmClient := getTestVMClient(armClient)
@ -603,7 +603,7 @@ func TestCreateOrUpdateWithCreateOrUpdateResponderError(t *testing.T) {
StatusCode: http.StatusNotFound, StatusCode: http.StatusNotFound,
Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), Body: ioutil.NopCloser(bytes.NewReader([]byte(""))),
} }
armClient.EXPECT().PutResource(gomock.Any(), to.String(testVM.ID), testVM).Return(response, nil).Times(1) armClient.EXPECT().PutResource(gomock.Any(), pointer.StringDeref(testVM.ID, ""), testVM).Return(response, nil).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
vmClient := getTestVMClient(armClient) vmClient := getTestVMClient(armClient)
@ -663,7 +663,7 @@ func TestCreateOrUpdateThrottle(t *testing.T) {
testVM := getTestVM("vm1") testVM := getTestVM("vm1")
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
armClient.EXPECT().PutResource(gomock.Any(), to.String(testVM.ID), testVM).Return(response, throttleErr).Times(1) armClient.EXPECT().PutResource(gomock.Any(), pointer.StringDeref(testVM.ID, ""), testVM).Return(response, throttleErr).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
vmClient := getTestVMClient(armClient) vmClient := getTestVMClient(armClient)
@ -678,7 +678,7 @@ func TestDelete(t *testing.T) {
r := getTestVM("vm1") r := getTestVM("vm1")
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
armClient.EXPECT().DeleteResource(gomock.Any(), to.String(r.ID), "").Return(nil).Times(1) armClient.EXPECT().DeleteResource(gomock.Any(), pointer.StringDeref(r.ID, ""), "").Return(nil).Times(1)
client := getTestVMClient(armClient) client := getTestVMClient(armClient)
rerr := client.Delete(context.TODO(), "rg", "vm1") rerr := client.Delete(context.TODO(), "rg", "vm1")
@ -731,7 +731,7 @@ func TestDeleteThrottle(t *testing.T) {
testVM := getTestVM("vm1") testVM := getTestVM("vm1")
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
armClient.EXPECT().DeleteResource(gomock.Any(), to.String(testVM.ID), "").Return(throttleErr).Times(1) armClient.EXPECT().DeleteResource(gomock.Any(), pointer.StringDeref(testVM.ID, ""), "").Return(throttleErr).Times(1)
vmClient := getTestVMClient(armClient) vmClient := getTestVMClient(armClient)
rerr := vmClient.Delete(context.TODO(), "rg", "vm1") rerr := vmClient.Delete(context.TODO(), "rg", "vm1")
@ -742,9 +742,9 @@ func TestDeleteThrottle(t *testing.T) {
func getTestVM(vmName string) compute.VirtualMachine { func getTestVM(vmName string) compute.VirtualMachine {
resourceID := fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/%s", vmName) resourceID := fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/%s", vmName)
return compute.VirtualMachine{ return compute.VirtualMachine{
ID: to.StringPtr(resourceID), ID: pointer.String(resourceID),
Name: to.StringPtr(vmName), Name: pointer.String(vmName),
Location: to.StringPtr("eastus"), Location: pointer.String("eastus"),
} }
} }

View File

@ -31,7 +31,6 @@ import (
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute"
"github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/to"
"github.com/golang/mock/gomock" "github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -40,6 +39,7 @@ import (
"k8s.io/legacy-cloud-providers/azure/clients/armclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient"
"k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
) )
func TestNew(t *testing.T) { func TestNew(t *testing.T) {
@ -201,7 +201,7 @@ func getTestVMSizeClient(armClient armclient.Interface) *Client {
func getTestVMSize(name string) compute.VirtualMachineSize { func getTestVMSize(name string) compute.VirtualMachineSize {
return compute.VirtualMachineSize{ return compute.VirtualMachineSize{
Name: to.StringPtr(name), Name: pointer.String(name),
} }
} }

View File

@ -28,7 +28,6 @@ import (
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute"
"github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/to"
"k8s.io/client-go/util/flowcontrol" "k8s.io/client-go/util/flowcontrol"
"k8s.io/klog/v2" "k8s.io/klog/v2"
@ -36,6 +35,7 @@ import (
"k8s.io/legacy-cloud-providers/azure/clients/armclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient"
"k8s.io/legacy-cloud-providers/azure/metrics" "k8s.io/legacy-cloud-providers/azure/metrics"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
) )
var _ Interface = &Client{} var _ Interface = &Client{}
@ -197,7 +197,7 @@ func (c *Client) listVMSS(ctx context.Context, resourceGroupName string) ([]comp
result = append(result, page.Values()...) result = append(result, page.Values()...)
// Abort the loop when there's no nextLink in the response. // Abort the loop when there's no nextLink in the response.
if to.String(page.Response().NextLink) == "" { if pointer.StringDeref(page.Response().NextLink, "") == "" {
break break
} }
@ -365,12 +365,12 @@ func (c *Client) listResponder(resp *http.Response) (result compute.VirtualMachi
// virtualMachineScaleSetListResultPreparer prepares a request to retrieve the next set of results. // virtualMachineScaleSetListResultPreparer prepares a request to retrieve the next set of results.
// It returns nil if no more results exist. // It returns nil if no more results exist.
func (c *Client) virtualMachineScaleSetListResultPreparer(ctx context.Context, vmsslr compute.VirtualMachineScaleSetListResult) (*http.Request, error) { func (c *Client) virtualMachineScaleSetListResultPreparer(ctx context.Context, vmsslr compute.VirtualMachineScaleSetListResult) (*http.Request, error) {
if vmsslr.NextLink == nil || len(to.String(vmsslr.NextLink)) < 1 { if vmsslr.NextLink == nil || len(pointer.StringDeref(vmsslr.NextLink, "")) < 1 {
return nil, nil return nil, nil
} }
decorators := []autorest.PrepareDecorator{ decorators := []autorest.PrepareDecorator{
autorest.WithBaseURL(to.String(vmsslr.NextLink)), autorest.WithBaseURL(pointer.StringDeref(vmsslr.NextLink, "")),
} }
return c.armClient.PrepareGetRequest(ctx, decorators...) return c.armClient.PrepareGetRequest(ctx, decorators...)
} }

View File

@ -32,7 +32,6 @@ import (
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute"
"github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/to"
"github.com/golang/mock/gomock" "github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -41,6 +40,7 @@ import (
"k8s.io/legacy-cloud-providers/azure/clients/armclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient"
"k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
) )
func TestNew(t *testing.T) { func TestNew(t *testing.T) {
@ -304,7 +304,7 @@ func TestListWithNextPage(t *testing.T) {
resourceID := "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets" resourceID := "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets"
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
vmssList := []compute.VirtualMachineScaleSet{getTestVMSS("vmss1"), getTestVMSS("vmss2"), getTestVMSS("vmss3")} vmssList := []compute.VirtualMachineScaleSet{getTestVMSS("vmss1"), getTestVMSS("vmss2"), getTestVMSS("vmss3")}
partialResponse, err := json.Marshal(compute.VirtualMachineScaleSetListResult{Value: &vmssList, NextLink: to.StringPtr("nextLink")}) partialResponse, err := json.Marshal(compute.VirtualMachineScaleSetListResult{Value: &vmssList, NextLink: pointer.String("nextLink")})
assert.NoError(t, err) assert.NoError(t, err)
pagedResponse, err := json.Marshal(compute.VirtualMachineScaleSetListResult{Value: &vmssList}) pagedResponse, err := json.Marshal(compute.VirtualMachineScaleSetListResult{Value: &vmssList})
assert.NoError(t, err) assert.NoError(t, err)
@ -389,7 +389,7 @@ func TestListNextResultsMultiPages(t *testing.T) {
} }
lastResult := compute.VirtualMachineScaleSetListResult{ lastResult := compute.VirtualMachineScaleSetListResult{
NextLink: to.StringPtr("next"), NextLink: pointer.String("next"),
} }
for _, test := range tests { for _, test := range tests {
@ -443,7 +443,7 @@ func TestListNextResultsMultiPagesWithListResponderError(t *testing.T) {
} }
lastResult := compute.VirtualMachineScaleSetListResult{ lastResult := compute.VirtualMachineScaleSetListResult{
NextLink: to.StringPtr("next"), NextLink: pointer.String("next"),
} }
for _, test := range tests { for _, test := range tests {
@ -487,7 +487,7 @@ func TestCreateOrUpdate(t *testing.T) {
StatusCode: http.StatusOK, StatusCode: http.StatusOK,
Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), Body: ioutil.NopCloser(bytes.NewReader([]byte(""))),
} }
armClient.EXPECT().PutResource(gomock.Any(), to.String(vmss.ID), vmss).Return(response, nil).Times(1) armClient.EXPECT().PutResource(gomock.Any(), pointer.StringDeref(vmss.ID, ""), vmss).Return(response, nil).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
vmssClient := getTestVMSSClient(armClient) vmssClient := getTestVMSSClient(armClient)
@ -504,7 +504,7 @@ func TestCreateOrUpdateWithCreateOrUpdateResponderError(t *testing.T) {
StatusCode: http.StatusNotFound, StatusCode: http.StatusNotFound,
Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), Body: ioutil.NopCloser(bytes.NewReader([]byte(""))),
} }
armClient.EXPECT().PutResource(gomock.Any(), to.String(vmss.ID), vmss).Return(response, nil).Times(1) armClient.EXPECT().PutResource(gomock.Any(), pointer.StringDeref(vmss.ID, ""), vmss).Return(response, nil).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
vmssClient := getTestVMSSClient(armClient) vmssClient := getTestVMSSClient(armClient)
@ -564,7 +564,7 @@ func TestCreateOrUpdateThrottle(t *testing.T) {
vmss := getTestVMSS("vmss1") vmss := getTestVMSS("vmss1")
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
armClient.EXPECT().PutResource(gomock.Any(), to.String(vmss.ID), vmss).Return(response, throttleErr).Times(1) armClient.EXPECT().PutResource(gomock.Any(), pointer.StringDeref(vmss.ID, ""), vmss).Return(response, throttleErr).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
vmssClient := getTestVMSSClient(armClient) vmssClient := getTestVMSSClient(armClient)
@ -581,13 +581,13 @@ func TestCreateOrUpdateAsync(t *testing.T) {
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
future := &azure.Future{} future := &azure.Future{}
armClient.EXPECT().PutResourceAsync(gomock.Any(), to.String(vmss.ID), vmss).Return(future, nil).Times(1) armClient.EXPECT().PutResourceAsync(gomock.Any(), pointer.StringDeref(vmss.ID, ""), vmss).Return(future, nil).Times(1)
vmssClient := getTestVMSSClient(armClient) vmssClient := getTestVMSSClient(armClient)
_, rerr := vmssClient.CreateOrUpdateAsync(context.TODO(), "rg", "vmss1", vmss) _, rerr := vmssClient.CreateOrUpdateAsync(context.TODO(), "rg", "vmss1", vmss)
assert.Nil(t, rerr) assert.Nil(t, rerr)
retryErr := &retry.Error{RawError: fmt.Errorf("error")} retryErr := &retry.Error{RawError: fmt.Errorf("error")}
armClient.EXPECT().PutResourceAsync(gomock.Any(), to.String(vmss.ID), vmss).Return(future, retryErr).Times(1) armClient.EXPECT().PutResourceAsync(gomock.Any(), pointer.StringDeref(vmss.ID, ""), vmss).Return(future, retryErr).Times(1)
_, rerr = vmssClient.CreateOrUpdateAsync(context.TODO(), "rg", "vmss1", vmss) _, rerr = vmssClient.CreateOrUpdateAsync(context.TODO(), "rg", "vmss1", vmss)
assert.Equal(t, retryErr, rerr) assert.Equal(t, retryErr, rerr)
} }
@ -641,7 +641,7 @@ func TestCreateOrUpdateAsyncThrottle(t *testing.T) {
vmss := getTestVMSS("vmss1") vmss := getTestVMSS("vmss1")
future := &azure.Future{} future := &azure.Future{}
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
armClient.EXPECT().PutResourceAsync(gomock.Any(), to.String(vmss.ID), vmss).Return(future, throttleErr).Times(1) armClient.EXPECT().PutResourceAsync(gomock.Any(), pointer.StringDeref(vmss.ID, ""), vmss).Return(future, throttleErr).Times(1)
vmssClient := getTestVMSSClient(armClient) vmssClient := getTestVMSSClient(armClient)
_, rerr := vmssClient.CreateOrUpdateAsync(context.TODO(), "rg", "vmss1", vmss) _, rerr := vmssClient.CreateOrUpdateAsync(context.TODO(), "rg", "vmss1", vmss)
@ -679,7 +679,7 @@ func TestDeleteInstances(t *testing.T) {
Body: ioutil.NopCloser(bytes.NewReader([]byte("{}"))), Body: ioutil.NopCloser(bytes.NewReader([]byte("{}"))),
} }
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
armClient.EXPECT().PostResource(gomock.Any(), to.String(r.ID), "delete", vmInstanceIDs).Return(response, nil).Times(1) armClient.EXPECT().PostResource(gomock.Any(), pointer.StringDeref(r.ID, ""), "delete", vmInstanceIDs).Return(response, nil).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
armClient.EXPECT().WaitForAsyncOperationCompletion(gomock.Any(), gomock.Any(), "vmssclient.DeleteInstances").Return(nil).Times(1) armClient.EXPECT().WaitForAsyncOperationCompletion(gomock.Any(), gomock.Any(), "vmssclient.DeleteInstances").Return(nil).Times(1)
@ -747,7 +747,7 @@ func TestDeleteInstancesThrottle(t *testing.T) {
} }
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
armClient.EXPECT().PostResource(gomock.Any(), to.String(vmss.ID), "delete", vmInstanceIDs).Return(response, throttleErr).Times(1) armClient.EXPECT().PostResource(gomock.Any(), pointer.StringDeref(vmss.ID, ""), "delete", vmInstanceIDs).Return(response, throttleErr).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
vmssClient := getTestVMSSClient(armClient) vmssClient := getTestVMSSClient(armClient)
@ -776,7 +776,7 @@ func TestDeleteInstancesWaitError(t *testing.T) {
} }
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
armClient.EXPECT().PostResource(gomock.Any(), to.String(vmss.ID), "delete", vmInstanceIDs).Return(response, nil).Times(1) armClient.EXPECT().PostResource(gomock.Any(), pointer.StringDeref(vmss.ID, ""), "delete", vmInstanceIDs).Return(response, nil).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
armClient.EXPECT().WaitForAsyncOperationCompletion(gomock.Any(), gomock.Any(), "vmssclient.DeleteInstances").Return(err).Times(1) armClient.EXPECT().WaitForAsyncOperationCompletion(gomock.Any(), gomock.Any(), "vmssclient.DeleteInstances").Return(err).Times(1)
@ -799,7 +799,7 @@ func TestDeleteInstancesAsync(t *testing.T) {
Body: ioutil.NopCloser(bytes.NewReader([]byte("{}"))), Body: ioutil.NopCloser(bytes.NewReader([]byte("{}"))),
} }
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
armClient.EXPECT().PostResource(gomock.Any(), to.String(vmss.ID), "delete", vmInstanceIDs).Return(response, nil).Times(1) armClient.EXPECT().PostResource(gomock.Any(), pointer.StringDeref(vmss.ID, ""), "delete", vmInstanceIDs).Return(response, nil).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
vmssClient := getTestVMSSClient(armClient) vmssClient := getTestVMSSClient(armClient)
@ -809,7 +809,7 @@ func TestDeleteInstancesAsync(t *testing.T) {
// on error // on error
retryErr := &retry.Error{RawError: fmt.Errorf("error")} retryErr := &retry.Error{RawError: fmt.Errorf("error")}
armClient.EXPECT().PostResource(gomock.Any(), to.String(vmss.ID), "delete", vmInstanceIDs).Return(&http.Response{StatusCode: http.StatusBadRequest}, retryErr).Times(1) armClient.EXPECT().PostResource(gomock.Any(), pointer.StringDeref(vmss.ID, ""), "delete", vmInstanceIDs).Return(&http.Response{StatusCode: http.StatusBadRequest}, retryErr).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
_, rerr = vmssClient.DeleteInstancesAsync(context.TODO(), "rg", "vmss1", vmInstanceIDs) _, rerr = vmssClient.DeleteInstancesAsync(context.TODO(), "rg", "vmss1", vmInstanceIDs)
assert.Equal(t, retryErr, rerr) assert.Equal(t, retryErr, rerr)
@ -817,12 +817,12 @@ func TestDeleteInstancesAsync(t *testing.T) {
func getTestVMSS(name string) compute.VirtualMachineScaleSet { func getTestVMSS(name string) compute.VirtualMachineScaleSet {
return compute.VirtualMachineScaleSet{ return compute.VirtualMachineScaleSet{
ID: to.StringPtr("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss1"), ID: pointer.String("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss1"),
Name: to.StringPtr(name), Name: pointer.String(name),
Location: to.StringPtr("eastus"), Location: pointer.String("eastus"),
Sku: &compute.Sku{ Sku: &compute.Sku{
Name: to.StringPtr("Standard"), Name: pointer.String("Standard"),
Capacity: to.Int64Ptr(3), Capacity: pointer.Int64(3),
}, },
} }
} }

View File

@ -28,7 +28,6 @@ import (
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute"
"github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/to"
utilerrors "k8s.io/apimachinery/pkg/util/errors" utilerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/client-go/util/flowcontrol" "k8s.io/client-go/util/flowcontrol"
@ -37,6 +36,7 @@ import (
"k8s.io/legacy-cloud-providers/azure/clients/armclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient"
"k8s.io/legacy-cloud-providers/azure/metrics" "k8s.io/legacy-cloud-providers/azure/metrics"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
) )
var _ Interface = &Client{} var _ Interface = &Client{}
@ -203,7 +203,7 @@ func (c *Client) listVMSSVM(ctx context.Context, resourceGroupName string, virtu
result = append(result, page.Values()...) result = append(result, page.Values()...)
// Abort the loop when there's no nextLink in the response. // Abort the loop when there's no nextLink in the response.
if to.String(page.Response().NextLink) == "" { if pointer.StringDeref(page.Response().NextLink, "") == "" {
break break
} }
@ -299,12 +299,12 @@ func (c *Client) listResponder(resp *http.Response) (result compute.VirtualMachi
// virtualMachineScaleSetListResultPreparer prepares a request to retrieve the next set of results. // virtualMachineScaleSetListResultPreparer prepares a request to retrieve the next set of results.
// It returns nil if no more results exist. // It returns nil if no more results exist.
func (c *Client) virtualMachineScaleSetVMListResultPreparer(ctx context.Context, vmssvmlr compute.VirtualMachineScaleSetVMListResult) (*http.Request, error) { func (c *Client) virtualMachineScaleSetVMListResultPreparer(ctx context.Context, vmssvmlr compute.VirtualMachineScaleSetVMListResult) (*http.Request, error) {
if vmssvmlr.NextLink == nil || len(to.String(vmssvmlr.NextLink)) < 1 { if vmssvmlr.NextLink == nil || len(pointer.StringDeref(vmssvmlr.NextLink, "")) < 1 {
return nil, nil return nil, nil
} }
decorators := []autorest.PrepareDecorator{ decorators := []autorest.PrepareDecorator{
autorest.WithBaseURL(to.String(vmssvmlr.NextLink)), autorest.WithBaseURL(pointer.StringDeref(vmssvmlr.NextLink, "")),
} }
return c.armClient.PrepareGetRequest(ctx, decorators...) return c.armClient.PrepareGetRequest(ctx, decorators...)
} }

View File

@ -31,7 +31,6 @@ import (
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute"
"github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/to"
"github.com/golang/mock/gomock" "github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -40,6 +39,7 @@ import (
"k8s.io/legacy-cloud-providers/azure/clients/armclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient"
"k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient" "k8s.io/legacy-cloud-providers/azure/clients/armclient/mockarmclient"
"k8s.io/legacy-cloud-providers/azure/retry" "k8s.io/legacy-cloud-providers/azure/retry"
"k8s.io/utils/pointer"
) )
func TestNew(t *testing.T) { func TestNew(t *testing.T) {
@ -303,7 +303,7 @@ func TestListWithNextPage(t *testing.T) {
resourceID := "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss1/virtualMachines" resourceID := "/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss1/virtualMachines"
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
vmssvmList := []compute.VirtualMachineScaleSetVM{getTestVMSSVM("vmss1", "1"), getTestVMSSVM("vmss1", "2"), getTestVMSSVM("vmss1", "3")} vmssvmList := []compute.VirtualMachineScaleSetVM{getTestVMSSVM("vmss1", "1"), getTestVMSSVM("vmss1", "2"), getTestVMSSVM("vmss1", "3")}
partialResponse, err := json.Marshal(compute.VirtualMachineScaleSetVMListResult{Value: &vmssvmList, NextLink: to.StringPtr("nextLink")}) partialResponse, err := json.Marshal(compute.VirtualMachineScaleSetVMListResult{Value: &vmssvmList, NextLink: pointer.String("nextLink")})
assert.NoError(t, err) assert.NoError(t, err)
pagedResponse, err := json.Marshal(compute.VirtualMachineScaleSetVMListResult{Value: &vmssvmList}) pagedResponse, err := json.Marshal(compute.VirtualMachineScaleSetVMListResult{Value: &vmssvmList})
assert.NoError(t, err) assert.NoError(t, err)
@ -388,7 +388,7 @@ func TestListNextResultsMultiPages(t *testing.T) {
} }
lastResult := compute.VirtualMachineScaleSetVMListResult{ lastResult := compute.VirtualMachineScaleSetVMListResult{
NextLink: to.StringPtr("next"), NextLink: pointer.String("next"),
} }
for _, test := range tests { for _, test := range tests {
@ -442,7 +442,7 @@ func TestListNextResultsMultiPagesWithListResponderError(t *testing.T) {
} }
lastResult := compute.VirtualMachineScaleSetVMListResult{ lastResult := compute.VirtualMachineScaleSetVMListResult{
NextLink: to.StringPtr("next"), NextLink: pointer.String("next"),
} }
for _, test := range tests { for _, test := range tests {
@ -486,7 +486,7 @@ func TestUpdate(t *testing.T) {
StatusCode: http.StatusOK, StatusCode: http.StatusOK,
Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), Body: ioutil.NopCloser(bytes.NewReader([]byte(""))),
} }
armClient.EXPECT().PutResource(gomock.Any(), to.String(vmssVM.ID), vmssVM).Return(response, nil).Times(1) armClient.EXPECT().PutResource(gomock.Any(), pointer.StringDeref(vmssVM.ID, ""), vmssVM).Return(response, nil).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
vmssClient := getTestVMSSVMClient(armClient) vmssClient := getTestVMSSVMClient(armClient)
@ -504,7 +504,7 @@ func TestUpdateWithUpdateResponderError(t *testing.T) {
StatusCode: http.StatusNotFound, StatusCode: http.StatusNotFound,
Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), Body: ioutil.NopCloser(bytes.NewReader([]byte(""))),
} }
armClient.EXPECT().PutResource(gomock.Any(), to.String(vmssVM.ID), vmssVM).Return(response, nil).Times(1) armClient.EXPECT().PutResource(gomock.Any(), pointer.StringDeref(vmssVM.ID, ""), vmssVM).Return(response, nil).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
vmssvmClient := getTestVMSSVMClient(armClient) vmssvmClient := getTestVMSSVMClient(armClient)
@ -564,7 +564,7 @@ func TestUpdateThrottle(t *testing.T) {
vmssVM := getTestVMSSVM("vmss1", "0") vmssVM := getTestVMSSVM("vmss1", "0")
armClient := mockarmclient.NewMockInterface(ctrl) armClient := mockarmclient.NewMockInterface(ctrl)
armClient.EXPECT().PutResource(gomock.Any(), to.String(vmssVM.ID), vmssVM).Return(response, throttleErr).Times(1) armClient.EXPECT().PutResource(gomock.Any(), pointer.StringDeref(vmssVM.ID, ""), vmssVM).Return(response, throttleErr).Times(1)
armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1)
vmssvmClient := getTestVMSSVMClient(armClient) vmssvmClient := getTestVMSSVMClient(armClient)
@ -584,18 +584,18 @@ func TestUpdateVMs(t *testing.T) {
"2": vmssVM2, "2": vmssVM2,
} }
testvmssVMs := map[string]interface{}{ testvmssVMs := map[string]interface{}{
to.String(vmssVM1.ID): vmssVM1, pointer.StringDeref(vmssVM1.ID, ""): vmssVM1,
to.String(vmssVM2.ID): vmssVM2, pointer.StringDeref(vmssVM2.ID, ""): vmssVM2,
} }
response := &http.Response{ response := &http.Response{
StatusCode: http.StatusOK, StatusCode: http.StatusOK,
Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), Body: ioutil.NopCloser(bytes.NewReader([]byte(""))),
} }
responses := map[string]*armclient.PutResourcesResponse{ responses := map[string]*armclient.PutResourcesResponse{
to.String(vmssVM1.ID): { pointer.StringDeref(vmssVM1.ID, ""): {
Response: response, Response: response,
}, },
to.String(vmssVM2.ID): { pointer.StringDeref(vmssVM2.ID, ""): {
Response: response, Response: response,
}, },
} }
@ -618,14 +618,14 @@ func TestUpdateVMsWithUpdateVMsResponderError(t *testing.T) {
"1": vmssVM, "1": vmssVM,
} }
testvmssVMs := map[string]interface{}{ testvmssVMs := map[string]interface{}{
to.String(vmssVM.ID): vmssVM, pointer.StringDeref(vmssVM.ID, ""): vmssVM,
} }
response := &http.Response{ response := &http.Response{
StatusCode: http.StatusNotFound, StatusCode: http.StatusNotFound,
Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), Body: ioutil.NopCloser(bytes.NewReader([]byte(""))),
} }
responses := map[string]*armclient.PutResourcesResponse{ responses := map[string]*armclient.PutResourcesResponse{
to.String(vmssVM.ID): { pointer.StringDeref(vmssVM.ID, ""): {
Response: response, Response: response,
}, },
} }
@ -682,7 +682,7 @@ func TestUpdateVMsThrottle(t *testing.T) {
"1": vmssVM, "1": vmssVM,
} }
testvmssVMs := map[string]interface{}{ testvmssVMs := map[string]interface{}{
to.String(vmssVM.ID): vmssVM, pointer.StringDeref(vmssVM.ID, ""): vmssVM,
} }
throttleErr := retry.Error{ throttleErr := retry.Error{
HTTPStatusCode: http.StatusTooManyRequests, HTTPStatusCode: http.StatusTooManyRequests,
@ -691,7 +691,7 @@ func TestUpdateVMsThrottle(t *testing.T) {
RetryAfter: time.Unix(100, 0), RetryAfter: time.Unix(100, 0),
} }
responses := map[string]*armclient.PutResourcesResponse{ responses := map[string]*armclient.PutResourcesResponse{
to.String(vmssVM.ID): { pointer.StringDeref(vmssVM.ID, ""): {
Response: &http.Response{ Response: &http.Response{
StatusCode: http.StatusTooManyRequests, StatusCode: http.StatusTooManyRequests,
Body: ioutil.NopCloser(bytes.NewReader([]byte("{}"))), Body: ioutil.NopCloser(bytes.NewReader([]byte("{}"))),
@ -713,9 +713,9 @@ func TestUpdateVMsThrottle(t *testing.T) {
func getTestVMSSVM(vmssName, instanceID string) compute.VirtualMachineScaleSetVM { func getTestVMSSVM(vmssName, instanceID string) compute.VirtualMachineScaleSetVM {
resourceID := fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/%s/virtualMachines/%s", vmssName, instanceID) resourceID := fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/%s/virtualMachines/%s", vmssName, instanceID)
return compute.VirtualMachineScaleSetVM{ return compute.VirtualMachineScaleSetVM{
ID: to.StringPtr(resourceID), ID: pointer.String(resourceID),
InstanceID: to.StringPtr(instanceID), InstanceID: pointer.String(instanceID),
Location: to.StringPtr("eastus"), Location: pointer.String("eastus"),
} }
} }

View File

@ -10,7 +10,6 @@ require (
github.com/Azure/go-autorest/autorest v0.11.27 github.com/Azure/go-autorest/autorest v0.11.27
github.com/Azure/go-autorest/autorest/adal v0.9.20 github.com/Azure/go-autorest/autorest/adal v0.9.20
github.com/Azure/go-autorest/autorest/mocks v0.4.2 github.com/Azure/go-autorest/autorest/mocks v0.4.2
github.com/Azure/go-autorest/autorest/to v0.4.0
github.com/GoogleCloudPlatform/k8s-cloud-provider v1.18.1-0.20220218231025-f11817397a1b github.com/GoogleCloudPlatform/k8s-cloud-provider v1.18.1-0.20220218231025-f11817397a1b
github.com/aws/aws-sdk-go v1.44.116 github.com/aws/aws-sdk-go v1.44.116
github.com/golang/mock v1.6.0 github.com/golang/mock v1.6.0
@ -36,6 +35,7 @@ require (
require ( require (
github.com/Azure/go-autorest v14.2.0+incompatible // indirect github.com/Azure/go-autorest v14.2.0+incompatible // indirect
github.com/Azure/go-autorest/autorest/date v0.3.0 // indirect github.com/Azure/go-autorest/autorest/date v0.3.0 // indirect
github.com/Azure/go-autorest/autorest/to v0.4.0 // indirect
github.com/Azure/go-autorest/autorest/validation v0.1.0 // indirect github.com/Azure/go-autorest/autorest/validation v0.1.0 // indirect
github.com/Azure/go-autorest/logger v0.2.1 // indirect github.com/Azure/go-autorest/logger v0.2.1 // indirect
github.com/Azure/go-autorest/tracing v0.6.0 // indirect github.com/Azure/go-autorest/tracing v0.6.0 // indirect