From 60671083efcba472e3a43589a9c13233ea499a75 Mon Sep 17 00:00:00 2001 From: MartinForReal Date: Wed, 4 Dec 2024 12:49:55 +0800 Subject: [PATCH] replace collectionutil with samber/lo --- go.mod | 2 +- go.sum | 4 +- .../testutil/fixture/azure_loadbalancer.go | 5 +- internal/testutil/fixture/azure_publicip.go | 11 +- .../testutil/fixture/azure_securitygroup.go | 44 +- internal/testutil/fixture/fixture.go | 10 +- kubetest2-aks/deployer/deployer.go | 1 + kubetest2-aks/deployer/up.go | 9 +- kubetest2-aks/go.mod | 2 +- pkg/consts/helpers_test.go | 12 +- .../ipam/cloud_cidr_allocator_test.go | 21 +- pkg/provider/azure_controller_standard.go | 10 +- .../azure_controller_standard_test.go | 36 +- pkg/provider/azure_controller_vmss.go | 10 +- pkg/provider/azure_controller_vmss_test.go | 60 +- pkg/provider/azure_controller_vmssflex.go | 10 +- .../azure_controller_vmssflex_test.go | 16 +- pkg/provider/azure_instances_test.go | 52 +- pkg/provider/azure_interface_repo_test.go | 6 +- pkg/provider/azure_loadbalancer.go | 211 +- .../azure_loadbalancer_accesscontrol.go | 18 +- .../azure_loadbalancer_accesscontrol_test.go | 93 +- .../azure_loadbalancer_backendpool.go | 108 +- .../azure_loadbalancer_backendpool_test.go | 144 +- .../azure_loadbalancer_healthprobe.go | 40 +- .../azure_loadbalancer_healthprobe_test.go | 102 +- pkg/provider/azure_loadbalancer_repo.go | 27 +- pkg/provider/azure_loadbalancer_repo_test.go | 82 +- pkg/provider/azure_loadbalancer_test.go | 2206 ++++++++--------- pkg/provider/azure_local_services.go | 19 +- pkg/provider/azure_local_services_test.go | 18 +- pkg/provider/azure_lock.go | 17 +- pkg/provider/azure_privatelinkservice.go | 72 +- pkg/provider/azure_privatelinkservice_test.go | 390 +-- pkg/provider/azure_publicip_repo.go | 19 +- pkg/provider/azure_publicip_repo_test.go | 41 +- pkg/provider/azure_routes.go | 31 +- pkg/provider/azure_routes_test.go | 75 +- pkg/provider/azure_standard.go | 63 +- pkg/provider/azure_standard_test.go | 176 +- pkg/provider/azure_storageaccount.go | 78 +- pkg/provider/azure_storageaccount_test.go | 221 +- pkg/provider/azure_test.go | 152 +- pkg/provider/azure_utils.go | 23 +- pkg/provider/azure_utils_test.go | 85 +- pkg/provider/azure_vmsets_repo.go | 4 +- pkg/provider/azure_vmss.go | 60 +- pkg/provider/azure_vmss_cache.go | 19 +- pkg/provider/azure_vmss_cache_test.go | 27 +- pkg/provider/azure_vmss_repo_test.go | 28 +- pkg/provider/azure_vmss_test.go | 368 +-- pkg/provider/azure_vmssflex.go | 44 +- pkg/provider/azure_vmssflex_cache.go | 7 +- pkg/provider/azure_vmssflex_cache_test.go | 58 +- pkg/provider/azure_vmssflex_test.go | 30 +- pkg/provider/azure_zones_test.go | 6 +- pkg/provider/loadbalancer/accesscontrol.go | 9 +- .../loadbalancer/accesscontrol_test.go | 143 +- pkg/provider/routetable/repo_test.go | 3 +- .../securitygroup/azure_securitygroup_repo.go | 5 +- .../azure_securitygroup_repo_test.go | 6 +- pkg/provider/securitygroup/securitygroup.go | 37 +- .../securitygroup/securitygroup_test.go | 295 ++- pkg/provider/securitygroup/securityrule.go | 10 +- pkg/provider/virtualmachine/virtualmachine.go | 21 +- pkg/provider/zone/repo.go | 5 +- pkg/util/collectionutil/map.go | 33 - pkg/util/collectionutil/slice.go | 107 - pkg/util/deepcopy/deepcopy_test.go | 17 +- pkg/util/iputil/family.go | 10 +- pkg/util/iputil/prefix_test.go | 11 +- pkg/util/vm/vm.go | 5 +- pkg/util/vm/vm_test.go | 9 +- tests/e2e/network/ensureloadbalancer.go | 60 +- tests/e2e/network/multiple_standard_lb.go | 26 +- tests/e2e/network/network_security_group.go | 57 +- tests/e2e/network/node.go | 5 +- tests/e2e/network/private_link_service.go | 13 +- tests/e2e/network/service_annotations.go | 58 +- tests/e2e/network/sharedhealthprobe.go | 13 +- tests/e2e/utils/container_registry_utils.go | 9 +- tests/e2e/utils/network_utils.go | 13 +- tests/e2e/utils/network_utils_test.go | 14 +- tests/e2e/utils/resource_group_utils.go | 6 +- tests/e2e/utils/route_table_utils.go | 5 +- tests/e2e/utils/vmss_utils.go | 3 +- vendor/github.com/samber/lo/CHANGELOG.md | 7 +- vendor/github.com/samber/lo/Dockerfile | 2 +- vendor/github.com/samber/lo/Makefile | 26 +- vendor/github.com/samber/lo/README.md | 727 +++++- vendor/github.com/samber/lo/channel.go | 19 +- vendor/github.com/samber/lo/concurrency.go | 53 +- vendor/github.com/samber/lo/errors.go | 30 +- vendor/github.com/samber/lo/find.go | 263 +- .../lo/internal/constraints/constraints.go | 42 + .../lo/internal/constraints/ordered_go118.go | 11 + .../lo/internal/constraints/ordered_go121.go | 9 + .../samber/lo/internal/rand/ordered_go118.go | 14 + .../samber/lo/internal/rand/ordered_go122.go | 13 + vendor/github.com/samber/lo/intersect.go | 117 +- vendor/github.com/samber/lo/map.go | 189 +- vendor/github.com/samber/lo/math.go | 32 +- vendor/github.com/samber/lo/retry.go | 10 +- vendor/github.com/samber/lo/slice.go | 287 ++- vendor/github.com/samber/lo/string.go | 90 +- vendor/github.com/samber/lo/time.go | 85 + vendor/github.com/samber/lo/tuples.go | 524 +++- .../github.com/samber/lo/type_manipulation.go | 61 +- vendor/github.com/samber/lo/types.go | 16 +- vendor/modules.txt | 4 +- 110 files changed, 5288 insertions(+), 3834 deletions(-) delete mode 100644 pkg/util/collectionutil/map.go delete mode 100644 pkg/util/collectionutil/slice.go create mode 100644 vendor/github.com/samber/lo/internal/constraints/constraints.go create mode 100644 vendor/github.com/samber/lo/internal/constraints/ordered_go118.go create mode 100644 vendor/github.com/samber/lo/internal/constraints/ordered_go121.go create mode 100644 vendor/github.com/samber/lo/internal/rand/ordered_go118.go create mode 100644 vendor/github.com/samber/lo/internal/rand/ordered_go122.go create mode 100644 vendor/github.com/samber/lo/time.go diff --git a/go.mod b/go.mod index 9b9048cc99..05ef4b0d8a 100644 --- a/go.mod +++ b/go.mod @@ -25,6 +25,7 @@ require ( github.com/onsi/ginkgo/v2 v2.22.0 github.com/onsi/gomega v1.36.0 github.com/prometheus/client_golang v1.20.5 + github.com/samber/lo v1.47.0 github.com/spf13/cobra v1.8.1 github.com/spf13/pflag v1.0.5 github.com/stretchr/testify v1.10.0 @@ -121,7 +122,6 @@ require ( github.com/prometheus/client_model v0.6.1 // indirect github.com/prometheus/common v0.60.1 // indirect github.com/prometheus/procfs v0.15.1 // indirect - github.com/samber/lo v1.38.1 // indirect github.com/shopspring/decimal v1.3.1 // indirect github.com/stoewer/go-strcase v1.2.0 // indirect github.com/x448/float16 v0.8.4 // indirect diff --git a/go.sum b/go.sum index f882b1727b..1612d7a8a8 100644 --- a/go.sum +++ b/go.sum @@ -234,8 +234,8 @@ github.com/redis/go-redis/v9 v9.6.1/go.mod h1:0C0c6ycQsdpVNQpxb1njEQIqkx5UcsM8FJ github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/samber/lo v1.38.1 h1:j2XEAqXKb09Am4ebOg31SpvzUTTs6EN3VfgeLUhPdXM= -github.com/samber/lo v1.38.1/go.mod h1:+m/ZKRl6ClXCE2Lgf3MsQlWfh4bn1bz6CXEOxnEXnEA= +github.com/samber/lo v1.47.0 h1:z7RynLwP5nbyRscyvcD043DWYoOcYRv3mV8lBeqOCLc= +github.com/samber/lo v1.47.0/go.mod h1:RmDH9Ct32Qy3gduHQuKJ3gW1fMHAnE/fAzQuf6He5cU= github.com/shopspring/decimal v1.3.1 h1:2Usl1nmF/WZucqkFZhnfFYxxxu8LG21F6nPQBE5gKV8= github.com/shopspring/decimal v1.3.1/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= diff --git a/internal/testutil/fixture/azure_loadbalancer.go b/internal/testutil/fixture/azure_loadbalancer.go index 866b127609..4f50b146c2 100644 --- a/internal/testutil/fixture/azure_loadbalancer.go +++ b/internal/testutil/fixture/azure_loadbalancer.go @@ -17,15 +17,14 @@ limitations under the License. package fixture import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - - "k8s.io/utils/ptr" ) func (f *AzureFixture) LoadBalancer() *AzureLoadBalancerFixture { return &AzureLoadBalancerFixture{ lb: &network.LoadBalancer{ - Name: ptr.To("lb"), + Name: to.Ptr("lb"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ // TODO }, diff --git a/internal/testutil/fixture/azure_publicip.go b/internal/testutil/fixture/azure_publicip.go index a444dc1774..0f69c7ba3c 100644 --- a/internal/testutil/fixture/azure_publicip.go +++ b/internal/testutil/fixture/azure_publicip.go @@ -19,9 +19,8 @@ package fixture import ( "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - - "k8s.io/utils/ptr" ) func (f *AzureFixture) PublicIPAddress(name string) *AzurePublicIPAddressFixture { @@ -32,8 +31,8 @@ func (f *AzureFixture) PublicIPAddress(name string) *AzurePublicIPAddressFixture return &AzurePublicIPAddressFixture{ pip: &network.PublicIPAddress{ - ID: ptr.To(fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/publicIPAddresses/%s", SubscriptionID, ResourceGroup, name)), - Name: ptr.To(name), + ID: to.Ptr(fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/publicIPAddresses/%s", SubscriptionID, ResourceGroup, name)), + Name: to.Ptr(name), Tags: make(map[string]*string), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{}, }, @@ -49,11 +48,11 @@ func (f *AzurePublicIPAddressFixture) Build() network.PublicIPAddress { } func (f *AzurePublicIPAddressFixture) WithTag(key, value string) *AzurePublicIPAddressFixture { - f.pip.Tags[key] = ptr.To(value) + f.pip.Tags[key] = to.Ptr(value) return f } func (f *AzurePublicIPAddressFixture) WithAddress(address string) *AzurePublicIPAddressFixture { - f.pip.PublicIPAddressPropertiesFormat.IPAddress = ptr.To(address) + f.pip.PublicIPAddressPropertiesFormat.IPAddress = to.Ptr(address) return f } diff --git a/internal/testutil/fixture/azure_securitygroup.go b/internal/testutil/fixture/azure_securitygroup.go index a979fa3646..d17b21b9f4 100644 --- a/internal/testutil/fixture/azure_securitygroup.go +++ b/internal/testutil/fixture/azure_securitygroup.go @@ -23,12 +23,10 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" - "k8s.io/utils/ptr" - + "github.com/samber/lo" "sigs.k8s.io/cloud-provider-azure/internal/testutil" "sigs.k8s.io/cloud-provider-azure/pkg/consts" "sigs.k8s.io/cloud-provider-azure/pkg/provider/securitygroup" - fnutil "sigs.k8s.io/cloud-provider-azure/pkg/util/collectionutil" "sigs.k8s.io/cloud-provider-azure/pkg/util/iputil" ) @@ -58,9 +56,9 @@ func (f *AzureFixture) NNoiseSecurityRules(nRules int) []*armnetwork.SecurityRul initPriority := int32(100) for i := 0; i < nRules; i++ { rule := &armnetwork.SecurityRule{ - Name: ptr.To(fmt.Sprintf("test-security-rule_%d", i)), + Name: to.Ptr(fmt.Sprintf("test-security-rule_%d", i)), Properties: &armnetwork.SecurityRulePropertiesFormat{ - Priority: ptr.To(initPriority), + Priority: to.Ptr(initPriority), Protocol: protocolByID(i), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), @@ -68,7 +66,7 @@ func (f *AzureFixture) NNoiseSecurityRules(nRules int) []*armnetwork.SecurityRul fmt.Sprintf("140.0.0.%d", i), // NOTE: keep the source IP / destination IP unique to LB ips. fmt.Sprintf("130.0.50.%d", i), ), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), DestinationPortRanges: to.SliceOfPtrs( fmt.Sprintf("4000%d", i), fmt.Sprintf("5000%d", i), @@ -83,11 +81,11 @@ func (f *AzureFixture) NNoiseSecurityRules(nRules int) []*armnetwork.SecurityRul fmt.Sprintf("200.0.50.%d", i), ) case 1: - rule.Properties.DestinationAddressPrefix = ptr.To(fmt.Sprintf("222.111.0.%d", i)) + rule.Properties.DestinationAddressPrefix = to.Ptr(fmt.Sprintf("222.111.0.%d", i)) case 2: rule.Properties.DestinationApplicationSecurityGroups = []*armnetwork.ApplicationSecurityGroup{ { - ID: ptr.To(fmt.Sprintf("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/the-rg/providers/Microsoft.Network/applicationSecurityGroups/the-asg-%d", i)), + ID: to.Ptr(fmt.Sprintf("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/the-rg/providers/Microsoft.Network/applicationSecurityGroups/the-asg-%d", i)), }, } } @@ -106,7 +104,7 @@ func (f *AzureFixture) NNoiseSecurityRules(nRules int) []*armnetwork.SecurityRul func (f *AzureFixture) SecurityGroup() *AzureSecurityGroupFixture { return &AzureSecurityGroupFixture{ sg: &armnetwork.SecurityGroup{ - Name: ptr.To("nsg"), + Name: to.Ptr("nsg"), Properties: &armnetwork.SecurityGroupPropertiesFormat{ SecurityRules: []*armnetwork.SecurityRule{}, }, @@ -120,25 +118,25 @@ func (f *AzureFixture) AllowSecurityRule( srcPrefixes []string, dstPorts []int32, ) *AzureAllowSecurityRuleFixture { - dstPortRanges := fnutil.Map(func(p int32) string { return strconv.FormatInt(int64(p), 10) }, dstPorts) + dstPortRanges := lo.Map(dstPorts, func(p int32, _ int) string { return strconv.FormatInt(int64(p), 10) }) sort.Strings(dstPortRanges) rv := &AzureAllowSecurityRuleFixture{ rule: &armnetwork.SecurityRule{ - Name: ptr.To(securitygroup.GenerateAllowSecurityRuleName(protocol, ipFamily, srcPrefixes, dstPorts)), + Name: to.Ptr(securitygroup.GenerateAllowSecurityRuleName(protocol, ipFamily, srcPrefixes, dstPorts)), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(protocol), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), DestinationPortRanges: to.SliceOfPtrs(dstPortRanges...), - Priority: ptr.To(int32(consts.LoadBalancerMinimumPriority)), + Priority: to.Ptr(int32(consts.LoadBalancerMinimumPriority)), }, }, } if len(srcPrefixes) == 1 { - rv.rule.Properties.SourceAddressPrefix = ptr.To(srcPrefixes[0]) + rv.rule.Properties.SourceAddressPrefix = to.Ptr(srcPrefixes[0]) } else { rv.rule.Properties.SourceAddressPrefixes = to.SliceOfPtrs(srcPrefixes...) } @@ -149,15 +147,15 @@ func (f *AzureFixture) AllowSecurityRule( func (f *AzureFixture) DenyAllSecurityRule(ipFamily iputil.Family) *AzureDenyAllSecurityRuleFixture { return &AzureDenyAllSecurityRuleFixture{ rule: &armnetwork.SecurityRule{ - Name: ptr.To(securitygroup.GenerateDenyAllSecurityRuleName(ipFamily)), + Name: to.Ptr(securitygroup.GenerateDenyAllSecurityRuleName(ipFamily)), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolAsterisk), Access: to.Ptr(armnetwork.SecurityRuleAccessDeny), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), - SourcePortRange: ptr.To("*"), - SourceAddressPrefix: ptr.To("*"), - DestinationPortRange: ptr.To("*"), - Priority: ptr.To(int32(consts.LoadBalancerMaximumPriority)), + SourcePortRange: to.Ptr("*"), + SourceAddressPrefix: to.Ptr("*"), + DestinationPortRange: to.Ptr("*"), + Priority: to.Ptr(int32(consts.LoadBalancerMaximumPriority)), }, }, } @@ -187,13 +185,13 @@ type AzureAllowSecurityRuleFixture struct { } func (f *AzureAllowSecurityRuleFixture) WithPriority(p int32) *AzureAllowSecurityRuleFixture { - f.rule.Properties.Priority = ptr.To(p) + f.rule.Properties.Priority = to.Ptr(p) return f } func (f *AzureAllowSecurityRuleFixture) WithDestination(prefixes ...string) *AzureAllowSecurityRuleFixture { if len(prefixes) == 1 { - f.rule.Properties.DestinationAddressPrefix = ptr.To(prefixes[0]) + f.rule.Properties.DestinationAddressPrefix = to.Ptr(prefixes[0]) f.rule.Properties.DestinationAddressPrefixes = nil } else { f.rule.Properties.DestinationAddressPrefix = nil @@ -213,13 +211,13 @@ type AzureDenyAllSecurityRuleFixture struct { } func (f *AzureDenyAllSecurityRuleFixture) WithPriority(p int32) *AzureDenyAllSecurityRuleFixture { - f.rule.Properties.Priority = ptr.To(p) + f.rule.Properties.Priority = to.Ptr(p) return f } func (f *AzureDenyAllSecurityRuleFixture) WithDestination(prefixes ...string) *AzureDenyAllSecurityRuleFixture { if len(prefixes) == 1 { - f.rule.Properties.DestinationAddressPrefix = ptr.To(prefixes[0]) + f.rule.Properties.DestinationAddressPrefix = to.Ptr(prefixes[0]) f.rule.Properties.DestinationAddressPrefixes = nil } else { f.rule.Properties.DestinationAddressPrefix = nil diff --git a/internal/testutil/fixture/fixture.go b/internal/testutil/fixture/fixture.go index 92aeba488f..567ddec34a 100644 --- a/internal/testutil/fixture/fixture.go +++ b/internal/testutil/fixture/fixture.go @@ -24,7 +24,7 @@ import ( "math/big" "net/netip" - fnutil "sigs.k8s.io/cloud-provider-azure/pkg/util/collectionutil" + "github.com/samber/lo" ) type Fixture struct{} @@ -69,7 +69,7 @@ func (f *Fixture) RandomIPv4Addresses(n int) []netip.Addr { } func (f *Fixture) RandomIPv4AddressStrings(n int) []string { - return fnutil.Map(func(p netip.Addr) string { return p.String() }, f.RandomIPv4Addresses(n)) + return lo.Map(f.RandomIPv4Addresses(n), func(p netip.Addr, _ int) string { return p.String() }) } func (f *Fixture) RandomIPv4Prefixes(n int) []netip.Prefix { @@ -91,7 +91,7 @@ func (f *Fixture) RandomIPv4Prefixes(n int) []netip.Prefix { } func (f *Fixture) RandomIPv4PrefixStrings(n int) []string { - return fnutil.Map(func(p netip.Prefix) string { return p.String() }, f.RandomIPv4Prefixes(n)) + return lo.Map(f.RandomIPv4Prefixes(n), func(p netip.Prefix, _ int) string { return p.String() }) } func (f *Fixture) RandomIPv6Addresses(n int) []netip.Addr { @@ -108,7 +108,7 @@ func (f *Fixture) RandomIPv6Addresses(n int) []netip.Addr { } func (f *Fixture) RandomIPv6AddressStrings(n int) []string { - return fnutil.Map(func(p netip.Addr) string { return p.String() }, f.RandomIPv6Addresses(n)) + return lo.Map(f.RandomIPv6Addresses(n), func(p netip.Addr, _ int) string { return p.String() }) } func (f *Fixture) RandomIPv6Prefixes(n int) []netip.Prefix { @@ -130,5 +130,5 @@ func (f *Fixture) RandomIPv6Prefixes(n int) []netip.Prefix { } func (f *Fixture) RandomIPv6PrefixStrings(n int) []string { - return fnutil.Map(func(p netip.Prefix) string { return p.String() }, f.RandomIPv6Prefixes(n)) + return lo.Map(f.RandomIPv6Prefixes(n), func(p netip.Prefix, _ int) string { return p.String() }) } diff --git a/kubetest2-aks/deployer/deployer.go b/kubetest2-aks/deployer/deployer.go index 849a82e94e..d018b397a3 100644 --- a/kubetest2-aks/deployer/deployer.go +++ b/kubetest2-aks/deployer/deployer.go @@ -24,6 +24,7 @@ import ( "github.com/octago/sflags/gen/gpflag" "github.com/spf13/pflag" + "k8s.io/klog" "sigs.k8s.io/kubetest2/pkg/types" ) diff --git a/kubetest2-aks/deployer/up.go b/kubetest2-aks/deployer/up.go index 18ef6630d1..3df93c3637 100644 --- a/kubetest2-aks/deployer/up.go +++ b/kubetest2-aks/deployer/up.go @@ -32,12 +32,13 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" "github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" armcontainerservicev2 "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerservice/armcontainerservice/v2" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources" "k8s.io/apimachinery/pkg/util/wait" + "k8s.io/klog" - "k8s.io/utils/ptr" "sigs.k8s.io/kubetest2/pkg/exec" ) @@ -152,10 +153,10 @@ func (d *deployer) createResourceGroup(subscriptionID string) (armresources.Reso now := time.Now() timestamp := now.Unix() param := armresources.ResourceGroup{ - Location: ptr.To(d.Location), + Location: to.Ptr(d.Location), Tags: map[string]*string{ - "creation_date": ptr.To(fmt.Sprintf("%d", timestamp)), - "usage": ptr.To(usageTag), + "creation_date": to.Ptr(fmt.Sprintf("%d", timestamp)), + "usage": to.Ptr(usageTag), }, } diff --git a/kubetest2-aks/go.mod b/kubetest2-aks/go.mod index 9dc4993c27..26481ea33c 100644 --- a/kubetest2-aks/go.mod +++ b/kubetest2-aks/go.mod @@ -13,7 +13,6 @@ require ( github.com/spf13/pflag v1.0.5 k8s.io/apimachinery v0.31.3 k8s.io/klog v1.0.0 - k8s.io/utils v0.0.0-20240711033017-18e509b52bc8 sigs.k8s.io/kubetest2 v0.0.0-20220728001911-c76fb417aa01 ) @@ -52,4 +51,5 @@ require ( golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d // indirect gopkg.in/warnings.v0 v0.1.2 // indirect k8s.io/klog/v2 v2.130.1 // indirect + k8s.io/utils v0.0.0-20240711033017-18e509b52bc8 // indirect ) diff --git a/pkg/consts/helpers_test.go b/pkg/consts/helpers_test.go index 5c11c6cae1..7a15a45526 100644 --- a/pkg/consts/helpers_test.go +++ b/pkg/consts/helpers_test.go @@ -23,9 +23,9 @@ import ( "strings" "testing" + "github.com/samber/lo" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/utils/ptr" ) func TestIsK8sServiceHasHAModeEnabled(t *testing.T) { @@ -184,13 +184,13 @@ func Test_extractInt32FromString(t *testing.T) { wantErr bool }{ {name: "value is not a number", args: args{val: "cookies"}, wantErr: true}, - {name: "value is zero", args: args{val: "0"}, wantErr: false, want: ptr.To(int32(0))}, + {name: "value is zero", args: args{val: "0"}, wantErr: false, want: lo.ToPtr(int32(0))}, {name: "value is a float number", args: args{val: "0.1"}, wantErr: true}, - {name: "value is a positive integer", args: args{val: "24"}, want: ptr.To(int32(24)), wantErr: false}, - {name: "value negative integer", args: args{val: "-6"}, want: ptr.To(int32(-6)), wantErr: false}, + {name: "value is a positive integer", args: args{val: "24"}, want: lo.ToPtr(int32(24)), wantErr: false}, + {name: "value negative integer", args: args{val: "-6"}, want: lo.ToPtr(int32(-6)), wantErr: false}, {name: "validator is nil", args: args{val: "-6", businessValidator: []Int32BusinessValidator{ nil, - }}, want: ptr.To(int32(-6)), wantErr: false}, + }}, want: lo.ToPtr(int32(-6)), wantErr: false}, {name: "validation failed", args: args{val: "-6", businessValidator: []Int32BusinessValidator{ func(_ *int32) error { return fmt.Errorf("validator failed") @@ -349,7 +349,7 @@ func TestGetInt32HealthProbeConfigOfPortFromK8sSvcAnnotation(t *testing.T) { port: 80, key: HealthProbeParamsNumOfProbe, }, - want: ptr.To(int32(2)), + want: lo.ToPtr(int32(2)), wantErr: false, }, { diff --git a/pkg/nodeipam/ipam/cloud_cidr_allocator_test.go b/pkg/nodeipam/ipam/cloud_cidr_allocator_test.go index c1556966c1..49c9706f90 100644 --- a/pkg/nodeipam/ipam/cloud_cidr_allocator_test.go +++ b/pkg/nodeipam/ipam/cloud_cidr_allocator_test.go @@ -24,14 +24,13 @@ import ( "time" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" + "github.com/samber/lo" "github.com/stretchr/testify/assert" "go.uber.org/mock/gomock" - v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/informers" "k8s.io/client-go/kubernetes/fake" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmclient/mockvmclient" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssclient/mockvmssclient" @@ -168,8 +167,8 @@ func TestUpdateNodeSubnetMaskSizes(t *testing.T) { description: "updateNodeSubnetMaskSizes should put the correct mask sizes on the map", providerID: "azure:///subscriptions/sub/resourceGroups/rg1/providers/Microsoft.Compute/virtualMachineScaleSets/vmss/virtualMachines/0", tags: map[string]*string{ - consts.VMSetCIDRIPV4TagKey: ptr.To("25"), - consts.VMSetCIDRIPV6TagKey: ptr.To("65"), + consts.VMSetCIDRIPV4TagKey: lo.ToPtr("25"), + consts.VMSetCIDRIPV6TagKey: lo.ToPtr("65"), }, expectedNodeNameSubnetMaskSizesMap: map[string][]int{"vmss-0": {25, 65}}, }, @@ -177,8 +176,8 @@ func TestUpdateNodeSubnetMaskSizes(t *testing.T) { description: "updateNodeSubnetMaskSizes should put the default mask sizes on the map if the providerID is invalid", providerID: "invalid", tags: map[string]*string{ - consts.VMSetCIDRIPV4TagKey: ptr.To("24"), - consts.VMSetCIDRIPV6TagKey: ptr.To("64"), + consts.VMSetCIDRIPV4TagKey: lo.ToPtr("24"), + consts.VMSetCIDRIPV6TagKey: lo.ToPtr("64"), }, expectedNodeNameSubnetMaskSizesMap: map[string][]int{"vmss-0": {24, 64}}, }, @@ -186,8 +185,8 @@ func TestUpdateNodeSubnetMaskSizes(t *testing.T) { description: "updateNodeSubnetMaskSizes should report an error if the ipv4 mask is smaller than the cluster mask", providerID: "azure:///subscriptions/sub/resourceGroups/rg1/providers/Microsoft.Compute/virtualMachineScaleSets/vmss/virtualMachines/0", tags: map[string]*string{ - consts.VMSetCIDRIPV4TagKey: ptr.To("15"), - consts.VMSetCIDRIPV6TagKey: ptr.To("65"), + consts.VMSetCIDRIPV4TagKey: lo.ToPtr("15"), + consts.VMSetCIDRIPV6TagKey: lo.ToPtr("65"), }, expectedNodeNameSubnetMaskSizesMap: map[string][]int{}, expectedErr: fmt.Errorf("updateNodeSubnetMaskSizes: invalid ipv4 mask size %d of node %s because it is out of the range of the cluster CIDR with the mask size %d", 15, "vmss-0", 16), @@ -196,8 +195,8 @@ func TestUpdateNodeSubnetMaskSizes(t *testing.T) { description: "updateNodeSubnetMaskSizes should report an error if the ipv6 mask is smaller than the cluster mask", providerID: "azure:///subscriptions/sub/resourceGroups/rg1/providers/Microsoft.Compute/virtualMachineScaleSets/vmss/virtualMachines/0", tags: map[string]*string{ - consts.VMSetCIDRIPV4TagKey: ptr.To("25"), - consts.VMSetCIDRIPV6TagKey: ptr.To("45"), + consts.VMSetCIDRIPV4TagKey: lo.ToPtr("25"), + consts.VMSetCIDRIPV6TagKey: lo.ToPtr("45"), }, expectedNodeNameSubnetMaskSizesMap: map[string][]int{}, expectedErr: fmt.Errorf("updateNodeSubnetMaskSizes: invalid ipv6 mask size %d of node %s because it is out of the range of the cluster CIDR with the mask size %d", 45, "vmss-0", 48), @@ -209,7 +208,7 @@ func TestUpdateNodeSubnetMaskSizes(t *testing.T) { assert.NoError(t, err) expectedVMSS := compute.VirtualMachineScaleSet{ - Name: ptr.To("vmss"), + Name: lo.ToPtr("vmss"), Tags: tc.tags, VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{ OrchestrationMode: compute.Uniform, diff --git a/pkg/provider/azure_controller_standard.go b/pkg/provider/azure_controller_standard.go index 39f4d8258a..9a8fca8799 100644 --- a/pkg/provider/azure_controller_standard.go +++ b/pkg/provider/azure_controller_standard.go @@ -22,13 +22,13 @@ import ( "net/http" "strings" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" "github.com/Azure/go-autorest/autorest/azure" - + "github.com/samber/lo" "k8s.io/apimachinery/pkg/types" "k8s.io/klog/v2" - "k8s.io/utils/ptr" azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" @@ -89,7 +89,7 @@ func (as *availabilitySet) AttachDisk(ctx context.Context, nodeName types.NodeNa Caching: opt.CachingMode, CreateOption: "attach", ManagedDisk: managedDisk, - WriteAcceleratorEnabled: ptr.To(opt.WriteAcceleratorEnabled), + WriteAcceleratorEnabled: to.Ptr(opt.WriteAcceleratorEnabled), }) } @@ -178,7 +178,7 @@ func (as *availabilitySet) DetachDisk(ctx context.Context, nodeName types.NodeNa (disk.ManagedDisk != nil && diskURI != "" && strings.EqualFold(*disk.ManagedDisk.ID, diskURI)) { // found the disk klog.V(2).Infof("azureDisk - detach disk: name %s uri %s", diskName, diskURI) - disks[i].ToBeDetached = ptr.To(true) + disks[i].ToBeDetached = to.Ptr(true) if forceDetach { disks[i].DetachOption = compute.ForceDetach } @@ -195,7 +195,7 @@ func (as *availabilitySet) DetachDisk(ctx context.Context, nodeName types.NodeNa // Azure stack does not support ToBeDetached flag, use original way to detach disk newDisks := []compute.DataDisk{} for _, disk := range disks { - if !ptr.Deref(disk.ToBeDetached, false) { + if !lo.FromPtrOr(disk.ToBeDetached, false) { newDisks = append(newDisks, disk) } } diff --git a/pkg/provider/azure_controller_standard_test.go b/pkg/provider/azure_controller_standard_test.go index 65ffe23edb..00c568d2d3 100644 --- a/pkg/provider/azure_controller_standard_test.go +++ b/pkg/provider/azure_controller_standard_test.go @@ -23,17 +23,15 @@ import ( "testing" "time" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" "github.com/Azure/go-autorest/autorest/azure" autorestmocks "github.com/Azure/go-autorest/autorest/mocks" "github.com/stretchr/testify/assert" - "go.uber.org/mock/gomock" - "k8s.io/apimachinery/pkg/types" cloudprovider "k8s.io/cloud-provider" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmclient/mockvmclient" azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" @@ -94,11 +92,11 @@ func TestStandardAttachDisk(t *testing.T) { for _, vm := range expectedVMs { vm.StorageProfile = &compute.StorageProfile{ OsDisk: &compute.OSDisk{ - Name: ptr.To("osdisk1"), + Name: to.Ptr("osdisk1"), ManagedDisk: &compute.ManagedDiskParameters{ - ID: ptr.To("ManagedID"), + ID: to.Ptr("ManagedID"), DiskEncryptionSet: &compute.DiskEncryptionSetParameters{ - ID: ptr.To("DiskEncryptionSetID"), + ID: to.Ptr("DiskEncryptionSetID"), }, }, }, @@ -108,7 +106,7 @@ func TestStandardAttachDisk(t *testing.T) { diskName := "disk-name2" diskURI := "uri" vm.StorageProfile.DataDisks = &[]compute.DataDisk{ - {Lun: ptr.To(int32(0)), Name: &diskName, ManagedDisk: &compute.ManagedDiskParameters{ID: &diskURI}}, + {Lun: to.Ptr(int32(0)), Name: &diskName, ManagedDisk: &compute.ManagedDiskParameters{ID: &diskURI}}, } } mockVMsClient.EXPECT().Get(gomock.Any(), testCloud.ResourceGroup, *vm.Name, gomock.Any()).Return(vm, nil).AnyTimes() @@ -318,16 +316,16 @@ func TestGetDataDisks(t *testing.T) { nodeName: "vm1", expectedDataDisks: []*armcompute.DataDisk{ { - Lun: ptr.To(int32(0)), - Name: ptr.To("disk1"), + Lun: to.Ptr(int32(0)), + Name: to.Ptr("disk1"), }, { - Lun: ptr.To(int32(1)), - Name: ptr.To("disk2"), + Lun: to.Ptr(int32(1)), + Name: to.Ptr("disk2"), }, { - Lun: ptr.To(int32(2)), - Name: ptr.To("disk3"), + Lun: to.Ptr(int32(2)), + Name: to.Ptr("disk3"), }, }, expectedError: false, @@ -338,16 +336,16 @@ func TestGetDataDisks(t *testing.T) { nodeName: "vm1", expectedDataDisks: []*armcompute.DataDisk{ { - Lun: ptr.To(int32(0)), - Name: ptr.To("disk1"), + Lun: to.Ptr(int32(0)), + Name: to.Ptr("disk1"), }, { - Lun: ptr.To(int32(1)), - Name: ptr.To("disk2"), + Lun: to.Ptr(int32(1)), + Name: to.Ptr("disk2"), }, { - Lun: ptr.To(int32(2)), - Name: ptr.To("disk3"), + Lun: to.Ptr(int32(2)), + Name: to.Ptr("disk3"), }, }, expectedError: false, diff --git a/pkg/provider/azure_controller_vmss.go b/pkg/provider/azure_controller_vmss.go index 48e4185048..9ffc4c6b8f 100644 --- a/pkg/provider/azure_controller_vmss.go +++ b/pkg/provider/azure_controller_vmss.go @@ -22,13 +22,13 @@ import ( "net/http" "strings" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" "github.com/Azure/go-autorest/autorest/azure" - + "github.com/samber/lo" "k8s.io/apimachinery/pkg/types" "k8s.io/klog/v2" - "k8s.io/utils/ptr" azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" @@ -96,7 +96,7 @@ func (ss *ScaleSet) AttachDisk(ctx context.Context, nodeName types.NodeName, dis Caching: opt.CachingMode, CreateOption: "attach", ManagedDisk: managedDisk, - WriteAcceleratorEnabled: ptr.To(opt.WriteAcceleratorEnabled), + WriteAcceleratorEnabled: to.Ptr(opt.WriteAcceleratorEnabled), }) } @@ -192,7 +192,7 @@ func (ss *ScaleSet) DetachDisk(ctx context.Context, nodeName types.NodeName, dis (disk.ManagedDisk != nil && diskURI != "" && strings.EqualFold(*disk.ManagedDisk.ID, diskURI)) { // found the disk klog.V(2).Infof("azureDisk - detach disk: name %s uri %s", diskName, diskURI) - disks[i].ToBeDetached = ptr.To(true) + disks[i].ToBeDetached = to.Ptr(true) if forceDetach { disks[i].DetachOption = compute.ForceDetach } @@ -209,7 +209,7 @@ func (ss *ScaleSet) DetachDisk(ctx context.Context, nodeName types.NodeName, dis // Azure stack does not support ToBeDetached flag, use original way to detach disk var newDisks []compute.DataDisk for _, disk := range disks { - if !ptr.Deref(disk.ToBeDetached, false) { + if !lo.FromPtrOr(disk.ToBeDetached, false) { newDisks = append(newDisks, disk) } } diff --git a/pkg/provider/azure_controller_vmss_test.go b/pkg/provider/azure_controller_vmss_test.go index 5dff138cfb..940b07864a 100644 --- a/pkg/provider/azure_controller_vmss_test.go +++ b/pkg/provider/azure_controller_vmss_test.go @@ -23,17 +23,15 @@ import ( "strings" "testing" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" "github.com/Azure/go-autorest/autorest/azure" autorestmocks "github.com/Azure/go-autorest/autorest/mocks" "github.com/stretchr/testify/assert" - "go.uber.org/mock/gomock" - "k8s.io/apimachinery/pkg/types" cloudprovider "k8s.io/cloud-provider" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmclient/mockvmclient" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssclient/mockvmssclient" @@ -112,11 +110,11 @@ func TestAttachDiskWithVMSS(t *testing.T) { for _, vmssvm := range expectedVMSSVMs { vmssvm.StorageProfile = &compute.StorageProfile{ OsDisk: &compute.OSDisk{ - Name: ptr.To("osdisk1"), + Name: to.Ptr("osdisk1"), ManagedDisk: &compute.ManagedDiskParameters{ - ID: ptr.To("ManagedID"), + ID: to.Ptr("ManagedID"), DiskEncryptionSet: &compute.DiskEncryptionSetParameters{ - ID: ptr.To("DiskEncryptionSetID"), + ID: to.Ptr("DiskEncryptionSetID"), }, }, }, @@ -126,7 +124,7 @@ func TestAttachDiskWithVMSS(t *testing.T) { diskURI := fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/disks/%s", testCloud.SubscriptionID, testCloud.ResourceGroup, diskname) vmssvm.StorageProfile.DataDisks = &[]compute.DataDisk{ - {Lun: ptr.To(int32(0)), Name: &diskname, ManagedDisk: &compute.ManagedDiskParameters{ID: &diskURI}}, + {Lun: to.Ptr(int32(0)), Name: &diskname, ManagedDisk: &compute.ManagedDiskParameters{ID: &diskURI}}, } } } @@ -251,26 +249,26 @@ func TestDetachDiskWithVMSS(t *testing.T) { for itr, vmssvm := range expectedVMSSVMs { vmssvm.StorageProfile = &compute.StorageProfile{ OsDisk: &compute.OSDisk{ - Name: ptr.To("osdisk1"), + Name: to.Ptr("osdisk1"), ManagedDisk: &compute.ManagedDiskParameters{ - ID: ptr.To("ManagedID"), + ID: to.Ptr("ManagedID"), DiskEncryptionSet: &compute.DiskEncryptionSetParameters{ - ID: ptr.To("DiskEncryptionSetID"), + ID: to.Ptr("DiskEncryptionSetID"), }, }, }, DataDisks: &[]compute.DataDisk{ { - Lun: ptr.To(int32(0)), - Name: ptr.To(diskName), + Lun: to.Ptr(int32(0)), + Name: to.Ptr(diskName), }, { - Lun: ptr.To(int32(1)), - Name: ptr.To("disk2"), + Lun: to.Ptr(int32(1)), + Name: to.Ptr("disk2"), }, { - Lun: ptr.To(int32(2)), - Name: ptr.To("disk3"), + Lun: to.Ptr(int32(2)), + Name: to.Ptr("disk3"), }, }, } @@ -333,7 +331,7 @@ func TestUpdateVMWithVMSS(t *testing.T) { vmssVMList: []string{"vmss-vm-000001"}, vmssName: "vm1", vmssvmName: "vm1", - existedDisk: compute.Disk{Name: ptr.To(diskName)}, + existedDisk: compute.Disk{Name: to.Ptr(diskName)}, expectedErr: true, expectedErrMsg: fmt.Errorf("not a vmss instance"), }, @@ -342,7 +340,7 @@ func TestUpdateVMWithVMSS(t *testing.T) { vmssVMList: []string{"vmss00-vm-000000", "vmss00-vm-000001", "vmss00-vm-000002"}, vmssName: "vmss00", vmssvmName: "vmss00-vm-000000", - existedDisk: compute.Disk{Name: ptr.To(diskName)}, + existedDisk: compute.Disk{Name: to.Ptr(diskName)}, expectedErr: false, }, { @@ -350,7 +348,7 @@ func TestUpdateVMWithVMSS(t *testing.T) { vmssVMList: []string{"vmss00-vm-000000", "vmss00-vm-000001", "vmss00-vm-000002"}, vmssName: fakeStatusNotFoundVMSSName, vmssvmName: "vmss00-vm-000000", - existedDisk: compute.Disk{Name: ptr.To(diskName)}, + existedDisk: compute.Disk{Name: to.Ptr(diskName)}, expectedErr: true, expectedErrMsg: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 404, RawError: %w", fmt.Errorf("instance not found")), }, @@ -359,7 +357,7 @@ func TestUpdateVMWithVMSS(t *testing.T) { vmssVMList: []string{"vmss00-vm-000000", "vmss00-vm-000001", "vmss00-vm-000002"}, vmssName: "vmss00", vmssvmName: "vmss00-vm-000000", - existedDisk: compute.Disk{Name: ptr.To("disk-name-err")}, + existedDisk: compute.Disk{Name: to.Ptr("disk-name-err")}, expectedErr: false, }, } @@ -382,17 +380,17 @@ func TestUpdateVMWithVMSS(t *testing.T) { for itr, vmssvm := range expectedVMSSVMs { vmssvm.StorageProfile = &compute.StorageProfile{ OsDisk: &compute.OSDisk{ - Name: ptr.To("osdisk1"), + Name: to.Ptr("osdisk1"), ManagedDisk: &compute.ManagedDiskParameters{ - ID: ptr.To("ManagedID"), + ID: to.Ptr("ManagedID"), DiskEncryptionSet: &compute.DiskEncryptionSetParameters{ - ID: ptr.To("DiskEncryptionSetID"), + ID: to.Ptr("DiskEncryptionSetID"), }, }, }, DataDisks: &[]compute.DataDisk{{ - Lun: ptr.To(int32(0)), - Name: ptr.To(diskName), + Lun: to.Ptr(int32(0)), + Name: to.Ptr(diskName), }}, } @@ -458,8 +456,8 @@ func TestGetDataDisksWithVMSS(t *testing.T) { nodeName: "vmss00-vm-000000", expectedDataDisks: []*armcompute.DataDisk{ { - Lun: ptr.To(int32(0)), - Name: ptr.To("disk1"), + Lun: to.Ptr(int32(0)), + Name: to.Ptr("disk1"), }, }, expectedErr: false, @@ -470,8 +468,8 @@ func TestGetDataDisksWithVMSS(t *testing.T) { nodeName: "vmss00-vm-000000", expectedDataDisks: []*armcompute.DataDisk{ { - Lun: ptr.To(int32(0)), - Name: ptr.To("disk1"), + Lun: to.Ptr(int32(0)), + Name: to.Ptr("disk1"), }, }, expectedErr: false, @@ -503,8 +501,8 @@ func TestGetDataDisksWithVMSS(t *testing.T) { for _, vmssvm := range expectedVMSSVMs { vmssvm.StorageProfile = &compute.StorageProfile{ DataDisks: &[]compute.DataDisk{{ - Lun: ptr.To(int32(0)), - Name: ptr.To("disk1"), + Lun: to.Ptr(int32(0)), + Name: to.Ptr("disk1"), }}, } } diff --git a/pkg/provider/azure_controller_vmssflex.go b/pkg/provider/azure_controller_vmssflex.go index 7e22880879..dec40087cd 100644 --- a/pkg/provider/azure_controller_vmssflex.go +++ b/pkg/provider/azure_controller_vmssflex.go @@ -23,13 +23,13 @@ import ( "strings" "sync" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" "github.com/Azure/go-autorest/autorest/azure" - + "github.com/samber/lo" "k8s.io/apimachinery/pkg/types" "k8s.io/klog/v2" - "k8s.io/utils/ptr" azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" @@ -90,7 +90,7 @@ func (fs *FlexScaleSet) AttachDisk(ctx context.Context, nodeName types.NodeName, Caching: opt.CachingMode, CreateOption: "attach", ManagedDisk: managedDisk, - WriteAcceleratorEnabled: ptr.To(opt.WriteAcceleratorEnabled), + WriteAcceleratorEnabled: to.Ptr(opt.WriteAcceleratorEnabled), }) } @@ -148,7 +148,7 @@ func (fs *FlexScaleSet) DetachDisk(ctx context.Context, nodeName types.NodeName, (disk.ManagedDisk != nil && diskURI != "" && strings.EqualFold(*disk.ManagedDisk.ID, diskURI)) { // found the disk klog.V(2).Infof("azureDisk - detach disk: name %s uri %s", diskName, diskURI) - disks[i].ToBeDetached = ptr.To(true) + disks[i].ToBeDetached = to.Ptr(true) if forceDetach { disks[i].DetachOption = compute.ForceDetach } @@ -165,7 +165,7 @@ func (fs *FlexScaleSet) DetachDisk(ctx context.Context, nodeName types.NodeName, // Azure stack does not support ToBeDetached flag, use original way to detach disk newDisks := []compute.DataDisk{} for _, disk := range disks { - if !ptr.Deref(disk.ToBeDetached, false) { + if !lo.FromPtrOr(disk.ToBeDetached, false) { newDisks = append(newDisks, disk) } } diff --git a/pkg/provider/azure_controller_vmssflex_test.go b/pkg/provider/azure_controller_vmssflex_test.go index afd57f54b9..5c11795dbb 100644 --- a/pkg/provider/azure_controller_vmssflex_test.go +++ b/pkg/provider/azure_controller_vmssflex_test.go @@ -22,17 +22,15 @@ import ( "net/http" "testing" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" "github.com/Azure/go-autorest/autorest/azure" autorestmocks "github.com/Azure/go-autorest/autorest/mocks" "github.com/stretchr/testify/assert" - "go.uber.org/mock/gomock" - "k8s.io/apimachinery/pkg/types" cloudprovider "k8s.io/cloud-provider" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmclient/mockvmclient" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssclient/mockvmssclient" @@ -324,9 +322,9 @@ func TestGetDataDisksWithVmssFlex(t *testing.T) { vmListErr: nil, expectedDataDisks: []*armcompute.DataDisk{ { - Lun: ptr.To(int32(1)), - Name: ptr.To("dataDisktestvm1"), - ManagedDisk: &armcompute.ManagedDiskParameters{ID: ptr.To("uri")}, + Lun: to.Ptr(int32(1)), + Name: to.Ptr("dataDisktestvm1"), + ManagedDisk: &armcompute.ManagedDiskParameters{ID: to.Ptr("uri")}, }, }, expectedErr: nil, @@ -382,14 +380,14 @@ func TestVMSSFlexUpdateCache(t *testing.T) { { description: "vm.VirtualMachineProperties is nil", nodeName: "vmssflex1000001", - vm: &compute.VirtualMachine{Name: ptr.To("vmssflex1000001")}, + vm: &compute.VirtualMachine{Name: to.Ptr("vmssflex1000001")}, expectedErr: fmt.Errorf("vm.VirtualMachineProperties is nil"), }, { description: "vm.OsProfile.ComputerName is nil", nodeName: "vmssflex1000001", vm: &compute.VirtualMachine{ - Name: ptr.To("vmssflex1000001"), + Name: to.Ptr("vmssflex1000001"), VirtualMachineProperties: &compute.VirtualMachineProperties{}, }, expectedErr: fmt.Errorf("vm.OsProfile.ComputerName is nil"), @@ -398,7 +396,7 @@ func TestVMSSFlexUpdateCache(t *testing.T) { description: "vm.OsProfile.ComputerName is nil", nodeName: "vmssflex1000001", vm: &compute.VirtualMachine{ - Name: ptr.To("vmssflex1000001"), + Name: to.Ptr("vmssflex1000001"), VirtualMachineProperties: &compute.VirtualMachineProperties{ OsProfile: &compute.OSProfile{}, }, diff --git a/pkg/provider/azure_instances_test.go b/pkg/provider/azure_instances_test.go index ec2abe0978..e45ddc243f 100644 --- a/pkg/provider/azure_instances_test.go +++ b/pkg/provider/azure_instances_test.go @@ -26,17 +26,15 @@ import ( "k8s.io/apimachinery/pkg/util/wait" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" "github.com/stretchr/testify/assert" - "go.uber.org/mock/gomock" - v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" cloudprovider "k8s.io/cloud-provider" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/interfaceclient/mockinterfaceclient" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/publicipclient/mockpublicipclient" @@ -63,14 +61,14 @@ func setTestVirtualMachines(c *Cloud, vmList map[string]string, isDataDisksFull } status := []compute.InstanceViewStatus{ { - Code: ptr.To(powerState), + Code: to.Ptr(powerState), }, { - Code: ptr.To("ProvisioningState/succeeded"), + Code: to.Ptr("ProvisioningState/succeeded"), }, } vm.VirtualMachineProperties = &compute.VirtualMachineProperties{ - ProvisioningState: ptr.To(string(consts.ProvisioningStateSucceeded)), + ProvisioningState: to.Ptr(string(consts.ProvisioningStateSucceeded)), HardwareProfile: &compute.HardwareProfile{ VMSize: compute.StandardA0, }, @@ -84,22 +82,22 @@ func setTestVirtualMachines(c *Cloud, vmList map[string]string, isDataDisksFull if !isDataDisksFull { vm.StorageProfile.DataDisks = &[]compute.DataDisk{ { - Lun: ptr.To(int32(0)), - Name: ptr.To("disk1"), + Lun: to.Ptr(int32(0)), + Name: to.Ptr("disk1"), }, { - Lun: ptr.To(int32(1)), - Name: ptr.To("disk2"), + Lun: to.Ptr(int32(1)), + Name: to.Ptr("disk2"), }, { - Lun: ptr.To(int32(2)), - Name: ptr.To("disk3"), + Lun: to.Ptr(int32(2)), + Name: to.Ptr("disk3"), }, } } else { dataDisks := make([]compute.DataDisk, maxLUN) for i := 0; i < maxLUN; i++ { - dataDisks[i] = compute.DataDisk{Lun: ptr.To(int32(i))} + dataDisks[i] = compute.DataDisk{Lun: to.Ptr(int32(i))} } vm.StorageProfile.DataDisks = &dataDisks } @@ -366,7 +364,7 @@ func TestInstanceShutdownByProviderID(t *testing.T) { cloud := GetTestCloud(ctrl) expectedVMs := setTestVirtualMachines(cloud, test.vmList, false) if test.provisioningState != "" { - expectedVMs[0].ProvisioningState = ptr.To(test.provisioningState) + expectedVMs[0].ProvisioningState = to.Ptr(test.provisioningState) } mockVMsClient := cloud.VirtualMachinesClient.(*mockvmclient.MockInterface) for _, vm := range expectedVMs { @@ -400,9 +398,9 @@ func TestNodeAddresses(t *testing.T) { NetworkInterfaces: &[]compute.NetworkInterfaceReference{ { NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{ - Primary: ptr.To(true), + Primary: to.Ptr(true), }, - ID: ptr.To("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic"), + ID: to.Ptr("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic"), }, }, }, @@ -410,10 +408,10 @@ func TestNodeAddresses(t *testing.T) { } expectedPIP := network.PublicIPAddress{ - Name: ptr.To("pip1"), - ID: ptr.To("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/pip1"), + Name: to.Ptr("pip1"), + ID: to.Ptr("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/pip1"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("192.168.1.12"), + IPAddress: to.Ptr("192.168.1.12"), }, } @@ -422,7 +420,7 @@ func TestNodeAddresses(t *testing.T) { IPConfigurations: &[]network.InterfaceIPConfiguration{ { InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ - PrivateIPAddress: ptr.To("172.1.0.3"), + PrivateIPAddress: to.Ptr("172.1.0.3"), PublicIPAddress: &expectedPIP, }, }, @@ -901,25 +899,25 @@ func TestInstanceMetadata(t *testing.T) { expectedVM.HardwareProfile = &compute.HardwareProfile{ VMSize: compute.BasicA0, } - expectedVM.Location = ptr.To("westus2") + expectedVM.Location = to.Ptr("westus2") expectedVM.Zones = &[]string{"1"} - expectedVM.ID = ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Compute/VirtualMachines/vm") + expectedVM.ID = to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Compute/VirtualMachines/vm") mockVMClient := cloud.VirtualMachinesClient.(*mockvmclient.MockInterface) mockVMClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, "vm", gomock.Any()).Return(expectedVM, nil) expectedNIC := buildDefaultTestInterface(true, []string{}) - (*expectedNIC.IPConfigurations)[0].PrivateIPAddress = ptr.To("1.2.3.4") + (*expectedNIC.IPConfigurations)[0].PrivateIPAddress = to.Ptr("1.2.3.4") (*expectedNIC.IPConfigurations)[0].PublicIPAddress = &network.PublicIPAddress{ - ID: ptr.To("pip"), + ID: to.Ptr("pip"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("5.6.7.8"), + IPAddress: to.Ptr("5.6.7.8"), }, } mockNICClient := cloud.InterfacesClient.(*mockinterfaceclient.MockInterface) mockNICClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, "k8s-agentpool1-00000000-nic-1", gomock.Any()).Return(expectedNIC, nil) expectedPIP := network.PublicIPAddress{ - Name: ptr.To("pip"), + Name: to.Ptr("pip"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("5.6.7.8"), + IPAddress: to.Ptr("5.6.7.8"), }, } mockPIPClient := cloud.PublicIPAddressesClient.(*mockpublicipclient.MockInterface) diff --git a/pkg/provider/azure_interface_repo_test.go b/pkg/provider/azure_interface_repo_test.go index 8859ff0e69..ef96d1c5bc 100644 --- a/pkg/provider/azure_interface_repo_test.go +++ b/pkg/provider/azure_interface_repo_test.go @@ -22,13 +22,11 @@ import ( "net/http" "testing" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" "github.com/stretchr/testify/assert" - "go.uber.org/mock/gomock" - v1 "k8s.io/api/core/v1" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/interfaceclient/mockinterfaceclient" "sigs.k8s.io/cloud-provider-azure/pkg/retry" @@ -42,6 +40,6 @@ func TestCreateOrUpdateInterface(t *testing.T) { mockInterfaceClient := az.InterfacesClient.(*mockinterfaceclient.MockInterface) mockInterfaceClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, "nic", gomock.Any()).Return(&retry.Error{HTTPStatusCode: http.StatusInternalServerError}) - err := az.CreateOrUpdateInterface(context.TODO(), &v1.Service{}, network.Interface{Name: ptr.To("nic")}) + err := az.CreateOrUpdateInterface(context.TODO(), &v1.Service{}, network.Interface{Name: to.Ptr("nic")}) assert.EqualError(t, fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 500, RawError: %w", error(nil)), err.Error()) } diff --git a/pkg/provider/azure_loadbalancer.go b/pkg/provider/azure_loadbalancer.go index 88ce01229c..b6cda74bfd 100644 --- a/pkg/provider/azure_loadbalancer.go +++ b/pkg/provider/azure_loadbalancer.go @@ -29,8 +29,10 @@ import ( "strings" "unicode" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" + "github.com/samber/lo" v1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -39,7 +41,6 @@ import ( cloudprovider "k8s.io/cloud-provider" servicehelpers "k8s.io/cloud-provider/service/helpers" "k8s.io/klog/v2" - "k8s.io/utils/ptr" azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" @@ -150,7 +151,7 @@ func (az *Cloud) reconcileService(ctx context.Context, clusterName string, servi } } - if _, err := az.reconcileSecurityGroup(ctx, clusterName, service, ptr.Deref(lb.Name, ""), lbIPsPrimaryPIPs, true /* wantLb */); err != nil { + if _, err := az.reconcileSecurityGroup(ctx, clusterName, service, lo.FromPtrOr(lb.Name, ""), lbIPsPrimaryPIPs, true /* wantLb */); err != nil { logger.Error(err, "Failed to reconcile SecurityGroup") return nil, err } @@ -171,12 +172,12 @@ func (az *Cloud) reconcileService(ctx context.Context, clusterName string, servi // lb is not reused here because the ETAG may be changed in above operations, hence reconcilePublicIP() would get lb again from cache. logger.V(2).Info("Reconciling PublicIPs") - if _, err := az.reconcilePublicIPs(ctx, clusterName, updateService, ptr.Deref(lb.Name, ""), true /* wantLb */); err != nil { + if _, err := az.reconcilePublicIPs(ctx, clusterName, updateService, lo.FromPtrOr(lb.Name, ""), true /* wantLb */); err != nil { logger.Error(err, "Failed to reconcile PublicIPs") return nil, err } - lbName := strings.ToLower(ptr.Deref(lb.Name, "")) + lbName := strings.ToLower(lo.FromPtrOr(lb.Name, "")) key := strings.ToLower(getServiceName(service)) if az.UseMultipleStandardLoadBalancers() && isLocalService(service) { az.localServiceNameToServiceInfoMap.Store(key, newServiceInfo(getServiceIPFamily(service), lbName)) @@ -469,7 +470,7 @@ func (az *Cloud) EnsureLoadBalancerDeleted(ctx context.Context, clusterName stri return err } - _, err = az.reconcileSecurityGroup(ctx, clusterName, service, ptr.Deref(lb.Name, ""), lbIPsPrimaryPIPs, false /* wantLb */) + _, err = az.reconcileSecurityGroup(ctx, clusterName, service, lo.FromPtrOr(lb.Name, ""), lbIPsPrimaryPIPs, false /* wantLb */) if err != nil { return err } @@ -566,7 +567,7 @@ func (az *Cloud) removeFrontendIPConfigurationFromLoadBalancer(ctx context.Conte fipConfigs := *lb.FrontendIPConfigurations for i, fipConfig := range fipConfigs { for _, fip := range fips { - if strings.EqualFold(ptr.Deref(fipConfig.Name, ""), ptr.Deref(fip.Name, "")) { + if strings.EqualFold(lo.FromPtrOr(fipConfig.Name, ""), lo.FromPtrOr(fip.Name, "")) { fipConfigs = append(fipConfigs[:i], fipConfigs[i+1:]...) break } @@ -579,7 +580,7 @@ func (az *Cloud) removeFrontendIPConfigurationFromLoadBalancer(ctx context.Conte lbRules := *lb.LoadBalancingRules for i := len(lbRules) - 1; i >= 0; i-- { for _, fip := range fips { - if strings.Contains(ptr.Deref(lbRules[i].Name, ""), ptr.Deref(fip.Name, "")) { + if strings.Contains(lo.FromPtrOr(lbRules[i].Name, ""), lo.FromPtrOr(fip.Name, "")) { lbRules = append(lbRules[:i], lbRules[i+1:]...) } } @@ -590,7 +591,7 @@ func (az *Cloud) removeFrontendIPConfigurationFromLoadBalancer(ctx context.Conte lbProbes := *lb.Probes for i := len(lbProbes) - 1; i >= 0; i-- { for _, fip := range fips { - if strings.Contains(ptr.Deref(lbProbes[i].Name, ""), ptr.Deref(fip.Name, "")) { + if strings.Contains(lo.FromPtrOr(lbProbes[i].Name, ""), lo.FromPtrOr(fip.Name, "")) { lbProbes = append(lbProbes[:i], lbProbes[i+1:]...) } } @@ -602,7 +603,7 @@ func (az *Cloud) removeFrontendIPConfigurationFromLoadBalancer(ctx context.Conte for _, fip := range fips { // clean up any private link service associated with the frontEndIPConfig if err := az.reconcilePrivateLinkService(ctx, clusterName, service, fip, false /* wantPLS */); err != nil { - klog.Errorf("removeFrontendIPConfigurationFromLoadBalancer(%s, %s, %s, %s): failed to clean up PLS: %v", ptr.Deref(lb.Name, ""), ptr.Deref(fip.Name, ""), clusterName, service.Name, err) + klog.Errorf("removeFrontendIPConfigurationFromLoadBalancer(%s, %s, %s, %s): failed to clean up PLS: %v", lo.FromPtrOr(lb.Name, ""), lo.FromPtrOr(fip.Name, ""), clusterName, service.Name, err) return "", err } } @@ -610,9 +611,9 @@ func (az *Cloud) removeFrontendIPConfigurationFromLoadBalancer(ctx context.Conte var deletedLBName string fipNames := []string{} for _, fip := range fips { - fipNames = append(fipNames, ptr.Deref(fip.Name, "")) + fipNames = append(fipNames, lo.FromPtrOr(fip.Name, "")) } - logPrefix := fmt.Sprintf("removeFrontendIPConfigurationFromLoadBalancer(%s, %q, %s, %s)", ptr.Deref(lb.Name, ""), fipNames, clusterName, service.Name) + logPrefix := fmt.Sprintf("removeFrontendIPConfigurationFromLoadBalancer(%s, %q, %s, %s)", lo.FromPtrOr(lb.Name, ""), fipNames, clusterName, service.Name) if len(fipConfigs) == 0 { klog.V(2).Infof("%s: deleting load balancer because there is no remaining frontend IP configurations", logPrefix) err := az.cleanOrphanedLoadBalancer(ctx, lb, *existingLBs, service, clusterName) @@ -620,7 +621,7 @@ func (az *Cloud) removeFrontendIPConfigurationFromLoadBalancer(ctx context.Conte klog.Errorf("%s: failed to cleanupOrphanedLoadBalancer: %v", logPrefix, err) return "", err } - deletedLBName = ptr.Deref(lb.Name, "") + deletedLBName = lo.FromPtrOr(lb.Name, "") } else { klog.V(2).Infof("%s: updating the load balancer", logPrefix) err := az.CreateOrUpdateLB(ctx, service, *lb) @@ -628,13 +629,13 @@ func (az *Cloud) removeFrontendIPConfigurationFromLoadBalancer(ctx context.Conte klog.Errorf("%s: failed to CreateOrUpdateLB: %v", logPrefix, err) return "", err } - _ = az.lbCache.Delete(ptr.Deref(lb.Name, "")) + _ = az.lbCache.Delete(lo.FromPtrOr(lb.Name, "")) } return deletedLBName, nil } func (az *Cloud) cleanOrphanedLoadBalancer(ctx context.Context, lb *network.LoadBalancer, existingLBs []network.LoadBalancer, service *v1.Service, clusterName string) error { - lbName := ptr.Deref(lb.Name, "") + lbName := lo.FromPtrOr(lb.Name, "") serviceName := getServiceName(service) isBackendPoolPreConfigured := az.isBackendPoolPreConfigured(service) v4Enabled, v6Enabled := getIPFamiliesEnabled(service) @@ -651,13 +652,13 @@ func (az *Cloud) cleanOrphanedLoadBalancer(ctx context.Context, lb *network.Load } else { foundLB := false for _, existingLB := range existingLBs { - if strings.EqualFold(ptr.Deref(lb.Name, ""), ptr.Deref(existingLB.Name, "")) { + if strings.EqualFold(lo.FromPtrOr(lb.Name, ""), lo.FromPtrOr(existingLB.Name, "")) { foundLB = true break } } if !foundLB { - klog.V(2).Infof("cleanOrphanedLoadBalancer: the LB %s doesn't exist, will not delete it", ptr.Deref(lb.Name, "")) + klog.V(2).Infof("cleanOrphanedLoadBalancer: the LB %s doesn't exist, will not delete it", lo.FromPtrOr(lb.Name, "")) return nil } @@ -716,23 +717,23 @@ func (az *Cloud) safeDeleteLoadBalancer(ctx context.Context, lb network.LoadBala lbBackendPoolIDsToDelete := []string{} if lb.LoadBalancerPropertiesFormat != nil && lb.BackendAddressPools != nil { for _, bp := range *lb.BackendAddressPools { - lbBackendPoolIDsToDelete = append(lbBackendPoolIDsToDelete, ptr.Deref(bp.ID, "")) + lbBackendPoolIDsToDelete = append(lbBackendPoolIDsToDelete, lo.FromPtrOr(bp.ID, "")) } } if _, err := az.VMSet.EnsureBackendPoolDeleted(ctx, service, lbBackendPoolIDsToDelete, vmSetName, lb.BackendAddressPools, true); err != nil { return retry.NewError(false, fmt.Errorf("safeDeleteLoadBalancer: failed to EnsureBackendPoolDeleted: %w", err)) } - klog.V(2).Infof("safeDeleteLoadBalancer: deleting LB %s", ptr.Deref(lb.Name, "")) - if rerr := az.DeleteLB(ctx, service, ptr.Deref(lb.Name, "")); rerr != nil { + klog.V(2).Infof("safeDeleteLoadBalancer: deleting LB %s", lo.FromPtrOr(lb.Name, "")) + if rerr := az.DeleteLB(ctx, service, lo.FromPtrOr(lb.Name, "")); rerr != nil { return rerr } - _ = az.lbCache.Delete(ptr.Deref(lb.Name, "")) + _ = az.lbCache.Delete(lo.FromPtrOr(lb.Name, "")) // Remove corresponding nodes in ActiveNodes and nodesWithCorrectLoadBalancerByPrimaryVMSet. for i := range az.MultipleStandardLoadBalancerConfigurations { if strings.EqualFold( - trimSuffixIgnoreCase(ptr.Deref(lb.Name, ""), consts.InternalLoadBalancerNameSuffix), + trimSuffixIgnoreCase(lo.FromPtrOr(lb.Name, ""), consts.InternalLoadBalancerNameSuffix), az.MultipleStandardLoadBalancerConfigurations[i].Name, ) { for _, nodeName := range az.MultipleStandardLoadBalancerConfigurations[i].ActiveNodes.UnsortedList() { @@ -807,11 +808,11 @@ func (az *Cloud) getServiceLoadBalancer( deletedLBName string err error ) - if wantLb && az.shouldChangeLoadBalancer(service, ptr.Deref(existingLB.Name, ""), clusterName, defaultLBName) { + if wantLb && az.shouldChangeLoadBalancer(service, lo.FromPtrOr(existingLB.Name, ""), clusterName, defaultLBName) { shouldChangeLB = true fipConfigNames := []string{} for _, fipConfig := range fipConfigs { - fipConfigNames = append(fipConfigNames, ptr.Deref(fipConfig.Name, "")) + fipConfigNames = append(fipConfigNames, lo.FromPtrOr(fipConfig.Name, "")) } deletedLBName, err = az.removeFrontendIPConfigurationFromLoadBalancer(ctx, &existingLB, existingLBs, fipConfigs, clusterName, service) if err != nil { @@ -824,7 +825,7 @@ func (az *Cloud) getServiceLoadBalancer( az.reconcileMultipleStandardLoadBalancerConfigurationStatus( false, getServiceName(service), - ptr.Deref(existingLB.Name, ""), + lo.FromPtrOr(existingLB.Name, ""), ) if isLocalService(service) && az.UseMultipleStandardLoadBalancers() { @@ -869,7 +870,7 @@ func (az *Cloud) getServiceLoadBalancer( // instead of creating a new load balancer if it exists. if shouldChangeLB { for _, existingLB := range *existingLBs { - if strings.EqualFold(ptr.Deref(existingLB.Name, ""), defaultLBName) { + if strings.EqualFold(lo.FromPtrOr(existingLB.Name, ""), defaultLBName) { return &existingLB, existingLBs, status, lbIPsPrimaryPIPs, true, nil } } @@ -1002,7 +1003,7 @@ func (az *Cloud) getServiceLoadBalancerStatus(ctx context.Context, service *v1.S ipConfiguration := (*lb.FrontendIPConfigurations)[i] owns, isPrimaryService, _ := az.serviceOwnsFrontendIP(ctx, ipConfiguration, service) if owns { - klog.V(2).Infof("get(%s): lb(%s) - found frontend IP config, primary service: %v", serviceName, ptr.Deref(lb.Name, ""), isPrimaryService) + klog.V(2).Infof("get(%s): lb(%s) - found frontend IP config, primary service: %v", serviceName, lo.FromPtrOr(lb.Name, ""), isPrimaryService) var lbIP *string if isInternal { @@ -1028,10 +1029,10 @@ func (az *Cloud) getServiceLoadBalancerStatus(ctx context.Context, service *v1.S } } - klog.V(2).Infof("getServiceLoadBalancerStatus gets ingress IP %q from frontendIPConfiguration %q for service %q", ptr.Deref(lbIP, ""), ptr.Deref(ipConfiguration.Name, ""), serviceName) + klog.V(2).Infof("getServiceLoadBalancerStatus gets ingress IP %q from frontendIPConfiguration %q for service %q", lo.FromPtrOr(lbIP, ""), lo.FromPtrOr(ipConfiguration.Name, ""), serviceName) - lbIngresses = append(lbIngresses, v1.LoadBalancerIngress{IP: ptr.Deref(lbIP, "")}) - lbIPsPrimaryPIPs = append(lbIPsPrimaryPIPs, ptr.Deref(lbIP, "")) + lbIngresses = append(lbIngresses, v1.LoadBalancerIngress{IP: lo.FromPtrOr(lbIP, "")}) + lbIPsPrimaryPIPs = append(lbIPsPrimaryPIPs, lo.FromPtrOr(lbIP, "")) fipConfigs = append(fipConfigs, &ipConfiguration) } } @@ -1163,7 +1164,7 @@ func (az *Cloud) ensurePublicIPExists(ctx context.Context, service *v1.Service, } } - klog.V(2).Infof("ensurePublicIPExists for service(%s): pip(%s) - updating", serviceName, ptr.Deref(pip.Name, "")) + klog.V(2).Infof("ensurePublicIPExists for service(%s): pip(%s) - updating", serviceName, lo.FromPtrOr(pip.Name, "")) if pip.PublicIPAddressPropertiesFormat == nil { pip.PublicIPAddressPropertiesFormat = &network.PublicIPAddressPropertiesFormat{ PublicIPAllocationMethod: network.Static, @@ -1178,8 +1179,8 @@ func (az *Cloud) ensurePublicIPExists(ctx context.Context, service *v1.Service, changed = true - pip.Name = ptr.To(pipName) - pip.Location = ptr.To(az.Location) + pip.Name = to.Ptr(pipName) + pip.Location = to.Ptr(az.Location) if az.HasExtendedLocation() { klog.V(2).Infof("Using extended location with name %s, and type %s for PIP", az.ExtendedLocationName, az.ExtendedLocationType) var typ network.ExtendedLocationTypes @@ -1197,7 +1198,7 @@ func (az *Cloud) ensurePublicIPExists(ctx context.Context, service *v1.Service, IPTags: getServiceIPTagRequestForPublicIP(service).IPTags, } pip.Tags = map[string]*string{ - consts.ServiceTagKey: ptr.To(""), + consts.ServiceTagKey: to.Ptr(""), consts.ClusterNameKey: &clusterName, } if _, err = bindServicesToPIP(&pip, []string{serviceName}, false); err != nil { @@ -1210,13 +1211,13 @@ func (az *Cloud) ensurePublicIPExists(ctx context.Context, service *v1.Service, } if id := getServicePIPPrefixID(service, isIPv6); id != "" { - pip.PublicIPPrefix = &network.SubResource{ID: ptr.To(id)} + pip.PublicIPPrefix = &network.SubResource{ID: to.Ptr(id)} } // skip adding zone info since edge zones doesn't support multiple availability zones. if !az.HasExtendedLocation() { // only add zone information for the new standard pips - zones, err := az.getRegionZonesBackoff(ctx, ptr.Deref(pip.Location, "")) + zones, err := az.getRegionZonesBackoff(ctx, lo.FromPtrOr(pip.Location, "")) if err != nil { return nil, err } @@ -1325,7 +1326,7 @@ func reconcileDNSSettings( changed = true } else { existingDNSLabel := pip.PublicIPAddressPropertiesFormat.DNSSettings.DomainNameLabel - if !strings.EqualFold(ptr.Deref(existingDNSLabel, ""), domainNameLabel) { + if !strings.EqualFold(lo.FromPtrOr(existingDNSLabel, ""), domainNameLabel) { pip.PublicIPAddressPropertiesFormat.DNSSettings.DomainNameLabel = &domainNameLabel changed = true } @@ -1434,8 +1435,8 @@ func sortIPTags(ipTags *[]network.IPTag) { if ipTags != nil { sort.Slice(*ipTags, func(i, j int) bool { ipTag := *ipTags - return ptr.Deref(ipTag[i].IPTagType, "") < ptr.Deref(ipTag[j].IPTagType, "") || - ptr.Deref(ipTag[i].Tag, "") < ptr.Deref(ipTag[j].Tag, "") + return lo.FromPtrOr(ipTag[i].IPTagType, "") < lo.FromPtrOr(ipTag[j].IPTagType, "") || + lo.FromPtrOr(ipTag[i].Tag, "") < lo.FromPtrOr(ipTag[j].Tag, "") }) } } @@ -1467,8 +1468,8 @@ func convertIPTagMapToSlice(ipTagMap map[string]string) *[]network.IPTag { outputTags := []network.IPTag{} for k, v := range ipTagMap { ipTag := network.IPTag{ - IPTagType: ptr.To(k), - Tag: ptr.To(v), + IPTagType: to.Ptr(k), + Tag: to.Ptr(v), } outputTags = append(outputTags, ipTag) } @@ -1480,7 +1481,7 @@ func getDomainNameLabel(pip *network.PublicIPAddress) string { if pip == nil || pip.PublicIPAddressPropertiesFormat == nil || pip.PublicIPAddressPropertiesFormat.DNSSettings == nil { return "" } - return ptr.Deref(pip.PublicIPAddressPropertiesFormat.DNSSettings.DomainNameLabel, "") + return lo.FromPtrOr(pip.PublicIPAddressPropertiesFormat.DNSSettings.DomainNameLabel, "") } // subnet is reused to reduce API calls when dualstack. @@ -1493,10 +1494,10 @@ func (az *Cloud) isFrontendIPChanged( subnet *network.Subnet, ) (bool, error) { isServiceOwnsFrontendIP, isPrimaryService, fipIPVersion := az.serviceOwnsFrontendIP(ctx, config, service) - if isServiceOwnsFrontendIP && isPrimaryService && !strings.EqualFold(ptr.Deref(config.Name, ""), lbFrontendIPConfigName) { + if isServiceOwnsFrontendIP && isPrimaryService && !strings.EqualFold(lo.FromPtrOr(config.Name, ""), lbFrontendIPConfigName) { return true, nil } - if !strings.EqualFold(ptr.Deref(config.Name, ""), lbFrontendIPConfigName) { + if !strings.EqualFold(lo.FromPtrOr(config.Name, ""), lbFrontendIPConfigName) { return false, nil } pipRG := az.getPublicIPAddressResourceGroup(service) @@ -1516,13 +1517,13 @@ func (az *Cloud) isFrontendIPChanged( subnetName := getInternalSubnet(service) if subnetName != nil { if subnet == nil { - return false, fmt.Errorf("isFrontendIPChanged: Unexpected nil subnet %q", ptr.Deref(subnetName, "")) + return false, fmt.Errorf("isFrontendIPChanged: Unexpected nil subnet %q", lo.FromPtrOr(subnetName, "")) } - if config.Subnet != nil && !strings.EqualFold(ptr.Deref(config.Subnet.ID, ""), ptr.Deref(subnet.ID, "")) { + if config.Subnet != nil && !strings.EqualFold(lo.FromPtrOr(config.Subnet.ID, ""), lo.FromPtrOr(subnet.ID, "")) { return true, nil } } - return loadBalancerIP != "" && !strings.EqualFold(loadBalancerIP, ptr.Deref(config.PrivateIPAddress, "")), nil + return loadBalancerIP != "" && !strings.EqualFold(loadBalancerIP, lo.FromPtrOr(config.PrivateIPAddress, "")), nil } pipName, _, err := az.determinePublicIPName(ctx, clusterName, service, isIPv6) if err != nil { @@ -1535,7 +1536,7 @@ func (az *Cloud) isFrontendIPChanged( if !existsPip { return true, nil } - return config.PublicIPAddress != nil && !strings.EqualFold(ptr.Deref(pip.ID, ""), ptr.Deref(config.PublicIPAddress.ID, "")), nil + return config.PublicIPAddress != nil && !strings.EqualFold(lo.FromPtrOr(pip.ID, ""), lo.FromPtrOr(config.PublicIPAddress.ID, "")), nil } // isFrontendIPConfigUnsafeToDelete checks if a frontend IP config is safe to be deleted. @@ -1730,11 +1731,11 @@ func (az *Cloud) reconcileMultipleStandardLoadBalancerConfigurations( } for _, existingLB := range *existingLBs { - lbName := ptr.Deref(existingLB.Name, "") + lbName := lo.FromPtrOr(existingLB.Name, "") if existingLB.LoadBalancerPropertiesFormat != nil && existingLB.LoadBalancingRules != nil { for _, rule := range *existingLB.LoadBalancingRules { - ruleName := ptr.Deref(rule.Name, "") + ruleName := lo.FromPtrOr(rule.Name, "") rulePrefix := strings.Split(ruleName, "-")[0] if rulePrefix == "" { klog.Warningf("reconcileMultipleStandardLoadBalancerConfigurations: the load balancing rule name %s is not in the correct format", ruleName) @@ -1914,7 +1915,7 @@ func (az *Cloud) reconcileLoadBalancer(ctx context.Context, clusterName string, "reconcileLoadBalancer for service(%s): lb(%s) - failed to clean up PrivateLinkService for frontEnd(%s): %v", serviceName, lbName, - ptr.Deref(fipConfigToDel.Name, ""), + lo.FromPtrOr(fipConfigToDel.Name, ""), err, ) } @@ -2001,11 +2002,11 @@ func (az *Cloud) reconcileBackendPoolHosts( res = currentLB for _, lb := range lbs { lb := lb - lbName := ptr.Deref(lb.Name, "") + lbName := lo.FromPtrOr(lb.Name, "") if lb.LoadBalancerPropertiesFormat != nil && lb.LoadBalancerPropertiesFormat.BackendAddressPools != nil { for i, backendPool := range *lb.LoadBalancerPropertiesFormat.BackendAddressPools { - isIPv6 := isBackendPoolIPv6(ptr.Deref(backendPool.Name, "")) - if strings.EqualFold(ptr.Deref(backendPool.Name, ""), az.getBackendPoolNameForService(service, clusterName, isIPv6)) { + isIPv6 := isBackendPoolIPv6(lo.FromPtrOr(backendPool.Name, "")) + if strings.EqualFold(lo.FromPtrOr(backendPool.Name, ""), az.getBackendPoolNameForService(service, clusterName, isIPv6)) { if err := az.LoadBalancerBackendPool.EnsureHostsInPool( ctx, service, @@ -2031,7 +2032,7 @@ func (az *Cloud) reconcileBackendPoolHosts( // addOrUpdateLBInList adds or updates the given lb in the list func addOrUpdateLBInList(lbs *[]network.LoadBalancer, targetLB *network.LoadBalancer) { for i, lb := range *lbs { - if strings.EqualFold(ptr.Deref(lb.Name, ""), ptr.Deref(targetLB.Name, "")) { + if strings.EqualFold(lo.FromPtrOr(lb.Name, ""), lo.FromPtrOr(targetLB.Name, "")) { (*lbs)[i] = *targetLB return } @@ -2043,7 +2044,7 @@ func addOrUpdateLBInList(lbs *[]network.LoadBalancer, targetLB *network.LoadBala func removeLBFromList(lbs *[]network.LoadBalancer, lbName string) { if lbs != nil { for i := len(*lbs) - 1; i >= 0; i-- { - if strings.EqualFold(ptr.Deref((*lbs)[i].Name, ""), lbName) { + if strings.EqualFold(lo.FromPtrOr((*lbs)[i].Name, ""), lbName) { *lbs = append((*lbs)[:i], (*lbs)[i+1:]...) break } @@ -2236,7 +2237,7 @@ func (az *Cloud) accommodateNodesByNodeSelector( func isLBInList(lbs *[]network.LoadBalancer, lbConfigName string) bool { if lbs != nil { for _, lb := range *lbs { - if strings.EqualFold(trimSuffixIgnoreCase(ptr.Deref(lb.Name, ""), consts.InternalLoadBalancerNameSuffix), lbConfigName) { + if strings.EqualFold(trimSuffixIgnoreCase(lo.FromPtrOr(lb.Name, ""), consts.InternalLoadBalancerNameSuffix), lbConfigName) { return true } } @@ -2312,7 +2313,7 @@ func (az *Cloud) recordExistingNodesOnLoadBalancers(clusterName string, lbs *[]n lb.LoadBalancerPropertiesFormat.BackendAddressPools == nil { continue } - lbName := ptr.Deref(lb.Name, "") + lbName := lo.FromPtrOr(lb.Name, "") for _, backendPool := range *lb.LoadBalancerPropertiesFormat.BackendAddressPools { backendPool := backendPool if found, _ := isLBBackendPoolsExisting(bpNames, backendPool.Name); found { @@ -2519,10 +2520,10 @@ func (az *Cloud) reconcileFrontendIPConfigs( config := newConfigs[i] isServiceOwnsFrontendIP, _, fipIPVersion := az.serviceOwnsFrontendIP(ctx, config, service) if !isServiceOwnsFrontendIP { - klog.V(4).Infof("reconcileFrontendIPConfigs for service (%s): the frontend IP configuration %s does not belong to the service", serviceName, ptr.Deref(config.Name, "")) + klog.V(4).Infof("reconcileFrontendIPConfigs for service (%s): the frontend IP configuration %s does not belong to the service", serviceName, lo.FromPtrOr(config.Name, "")) continue } - klog.V(4).Infof("reconcileFrontendIPConfigs for service (%s): checking owned frontend IP configuration %s", serviceName, ptr.Deref(config.Name, "")) + klog.V(4).Infof("reconcileFrontendIPConfigs for service (%s): checking owned frontend IP configuration %s", serviceName, lo.FromPtrOr(config.Name, "")) var isIPv6 bool var err error if fipIPVersion != "" { @@ -2588,7 +2589,7 @@ func (az *Cloud) reconcileFrontendIPConfigs( } else if status != nil && len(status.Ingress) > 0 && ingressIPInSubnet(status.Ingress) { klog.V(4).Infof("reconcileFrontendIPConfigs for service (%s): keep the original private IP %s", serviceName, privateIP) configProperties.PrivateIPAllocationMethod = network.Static - configProperties.PrivateIPAddress = ptr.To(privateIP) + configProperties.PrivateIPAddress = to.Ptr(privateIP) } else { // We'll need to call GetLoadBalancer later to retrieve allocated IP. klog.V(4).Infof("reconcileFrontendIPConfigs for service (%s): dynamically allocate the private IP", serviceName) @@ -2612,8 +2613,8 @@ func (az *Cloud) reconcileFrontendIPConfigs( } newConfig := network.FrontendIPConfiguration{ - Name: ptr.To(lbFrontendIPConfigNames[isIPv6]), - ID: ptr.To(fmt.Sprintf(consts.FrontendIPConfigIDTemplate, az.getNetworkResourceSubscriptionID(), az.ResourceGroup, ptr.Deref(lb.Name, ""), lbFrontendIPConfigNames[isIPv6])), + Name: to.Ptr(lbFrontendIPConfigNames[isIPv6]), + ID: to.Ptr(fmt.Sprintf(consts.FrontendIPConfigIDTemplate, az.getNetworkResourceSubscriptionID(), az.ResourceGroup, lo.FromPtrOr(lb.Name, ""), lbFrontendIPConfigNames[isIPv6])), FrontendIPConfigurationPropertiesFormat: fipConfigurationProperties, } @@ -2808,9 +2809,9 @@ func (az *Cloud) getExpectedLBRules( nodeEndpointHealthprobe = &network.Probe{ Name: &lbRuleName, ProbePropertiesFormat: &network.ProbePropertiesFormat{ - RequestPath: ptr.To(podPresencePath), + RequestPath: to.Ptr(podPresencePath), Protocol: network.ProbeProtocolHTTP, - Port: ptr.To(podPresencePort), + Port: to.Ptr(podPresencePort), IntervalInSeconds: probeInterval, ProbeThreshold: numberOfProbes, }, @@ -2849,7 +2850,7 @@ func (az *Cloud) getExpectedLBRules( } if portprobe != nil { props.Probe = &network.SubResource{ - ID: ptr.To(az.getLoadBalancerProbeID(lbName, *portprobe.Name)), + ID: to.Ptr(az.getLoadBalancerProbeID(lbName, *portprobe.Name)), } expectedProbes = append(expectedProbes, *portprobe) break @@ -2857,7 +2858,7 @@ func (az *Cloud) getExpectedLBRules( } } else { props.Probe = &network.SubResource{ - ID: ptr.To(az.getLoadBalancerProbeID(lbName, *nodeEndpointHealthprobe.Name)), + ID: to.Ptr(az.getLoadBalancerProbeID(lbName, *nodeEndpointHealthprobe.Name)), } expectedProbes = append(expectedProbes, *nodeEndpointHealthprobe) } @@ -2911,12 +2912,12 @@ func (az *Cloud) getExpectedLBRules( } if portprobe != nil { props.Probe = &network.SubResource{ - ID: ptr.To(az.getLoadBalancerProbeID(lbName, *portprobe.Name)), + ID: to.Ptr(az.getLoadBalancerProbeID(lbName, *portprobe.Name)), } expectedProbes = append(expectedProbes, *portprobe) } else if nodeEndpointHealthprobe != nil { props.Probe = &network.SubResource{ - ID: ptr.To(az.getLoadBalancerProbeID(lbName, *nodeEndpointHealthprobe.Name)), + ID: to.Ptr(az.getLoadBalancerProbeID(lbName, *nodeEndpointHealthprobe.Name)), } if !nodeEndpointHealthprobeAdded { expectedProbes = append(expectedProbes, *nodeEndpointHealthprobe) @@ -2925,8 +2926,8 @@ func (az *Cloud) getExpectedLBRules( } } if consts.IsK8sServiceDisableLoadBalancerFloatingIP(service) { - props.BackendPort = ptr.To(port.NodePort) - props.EnableFloatingIP = ptr.To(false) + props.BackendPort = to.Ptr(port.NodePort) + props.EnableFloatingIP = to.Ptr(false) } expectedRules = append(expectedRules, network.LoadBalancingRule{ Name: &lbRuleName, @@ -2964,33 +2965,33 @@ func (az *Cloud) getExpectedLoadBalancingRulePropertiesForPort( }); err != nil { return nil, fmt.Errorf("error parsing idle timeout key: %s, err: %w", consts.ServiceAnnotationLoadBalancerIdleTimeout, err) } else if lbIdleTimeout == nil { - lbIdleTimeout = ptr.To(int32(4)) + lbIdleTimeout = to.Ptr(int32(4)) } props := &network.LoadBalancingRulePropertiesFormat{ Protocol: transportProto, - FrontendPort: ptr.To(servicePort.Port), - BackendPort: ptr.To(servicePort.Port), - DisableOutboundSnat: ptr.To(az.DisableLoadBalancerOutboundSNAT()), - EnableFloatingIP: ptr.To(true), + FrontendPort: to.Ptr(servicePort.Port), + BackendPort: to.Ptr(servicePort.Port), + DisableOutboundSnat: to.Ptr(az.DisableLoadBalancerOutboundSNAT()), + EnableFloatingIP: to.Ptr(true), LoadDistribution: loadDistribution, FrontendIPConfiguration: &network.SubResource{ - ID: ptr.To(lbFrontendIPConfigID), + ID: to.Ptr(lbFrontendIPConfigID), }, BackendAddressPool: &network.SubResource{ - ID: ptr.To(lbBackendPoolID), + ID: to.Ptr(lbBackendPoolID), }, IdleTimeoutInMinutes: lbIdleTimeout, } if strings.EqualFold(string(transportProto), string(network.TransportProtocolTCP)) && az.UseStandardLoadBalancer() { - props.EnableTCPReset = ptr.To(!consts.IsTCPResetDisabled(service.Annotations)) + props.EnableTCPReset = to.Ptr(!consts.IsTCPResetDisabled(service.Annotations)) } // Azure ILB does not support secondary IPs as floating IPs on the LB. Therefore, floating IP needs to be turned // off and the rule should point to the nodeIP:nodePort. if consts.IsK8sServiceUsingInternalLoadBalancer(service) && isBackendPoolIPv6(lbBackendPoolID) { - props.BackendPort = ptr.To(servicePort.NodePort) - props.EnableFloatingIP = ptr.To(false) + props.BackendPort = to.Ptr(servicePort.NodePort) + props.EnableFloatingIP = to.Ptr(false) } return props, nil } @@ -3005,7 +3006,7 @@ func (az *Cloud) getExpectedHAModeLoadBalancingRuleProperties( if err != nil { return nil, fmt.Errorf("error generate lb rule for ha mod loadbalancer. err: %w", err) } - props.EnableTCPReset = ptr.To(!consts.IsTCPResetDisabled(service.Annotations)) + props.EnableTCPReset = to.Ptr(!consts.IsTCPResetDisabled(service.Annotations)) return props, nil } @@ -3209,7 +3210,7 @@ func (az *Cloud) ensurePIPTagged(service *v1.Service, pip *network.PublicIPAddre found, key := findKeyInMapCaseInsensitive(configTags, k) if !found { configTags[k] = v - } else if !strings.EqualFold(ptr.Deref(v, ""), ptr.Deref(configTags[key], "")) { + } else if !strings.EqualFold(lo.FromPtrOr(v, ""), lo.FromPtrOr(configTags[key], "")) { configTags[key] = v } } @@ -3398,7 +3399,7 @@ func (az *Cloud) getPublicIPUpdates( owns, isUserAssignedPIP := serviceOwnsPublicIP(service, &pip, clusterName) if owns { var ( - serviceReferences = parsePIPServiceTag(ptr.To(getServiceFromPIPServiceTags(pip.Tags))) + serviceReferences = parsePIPServiceTag(to.Ptr(getServiceFromPIPServiceTags(pip.Tags))) dirtyPIP, toBeDeleted bool ) if !wantLb && !isUserAssignedPIP { @@ -3464,12 +3465,12 @@ func (az *Cloud) safeDeletePublicIP(ctx context.Context, service *v1.Service, pi loadBalancerRuleUpdated := false // Check whether there are still frontend IP configurations referring to it. - ipConfigurationID := ptr.Deref(pip.PublicIPAddressPropertiesFormat.IPConfiguration.ID, "") + ipConfigurationID := lo.FromPtrOr(pip.PublicIPAddressPropertiesFormat.IPConfiguration.ID, "") if ipConfigurationID != "" { lbFrontendIPConfigs := *lb.LoadBalancerPropertiesFormat.FrontendIPConfigurations for i := len(lbFrontendIPConfigs) - 1; i >= 0; i-- { config := lbFrontendIPConfigs[i] - if strings.EqualFold(ipConfigurationID, ptr.Deref(config.ID, "")) { + if strings.EqualFold(ipConfigurationID, lo.FromPtrOr(config.ID, "")) { if config.FrontendIPConfigurationPropertiesFormat != nil && config.FrontendIPConfigurationPropertiesFormat.LoadBalancingRules != nil { referencedLBRules = *config.FrontendIPConfigurationPropertiesFormat.LoadBalancingRules @@ -3490,13 +3491,13 @@ func (az *Cloud) safeDeletePublicIP(ctx context.Context, service *v1.Service, pi if len(referencedLBRules) > 0 { referencedLBRuleIDs := utilsets.NewString() for _, refer := range referencedLBRules { - referencedLBRuleIDs.Insert(ptr.Deref(refer.ID, "")) + referencedLBRuleIDs.Insert(lo.FromPtrOr(refer.ID, "")) } if lb.LoadBalancerPropertiesFormat.LoadBalancingRules != nil { lbRules := *lb.LoadBalancerPropertiesFormat.LoadBalancingRules for i := len(lbRules) - 1; i >= 0; i-- { - ruleID := ptr.Deref(lbRules[i].ID, "") + ruleID := lo.FromPtrOr(lbRules[i].ID, "") if ruleID != "" && referencedLBRuleIDs.Has(ruleID) { loadBalancerRuleUpdated = true lbRules = append(lbRules[:i], lbRules[i+1:]...) @@ -3520,7 +3521,7 @@ func (az *Cloud) safeDeletePublicIP(ctx context.Context, service *v1.Service, pi } } - pipName := ptr.Deref(pip.Name, "") + pipName := lo.FromPtrOr(pip.Name, "") klog.V(10).Infof("DeletePublicIP(%s, %q): start", pipResourceGroup, pipName) err := az.DeletePublicIP(service, pipResourceGroup, pipName) if err != nil { @@ -3533,7 +3534,7 @@ func (az *Cloud) safeDeletePublicIP(ctx context.Context, service *v1.Service, pi func findRule(rules []network.LoadBalancingRule, rule network.LoadBalancingRule, wantLB bool) bool { for _, existingRule := range rules { - if strings.EqualFold(ptr.Deref(existingRule.Name, ""), ptr.Deref(rule.Name, "")) && + if strings.EqualFold(lo.FromPtrOr(existingRule.Name, ""), lo.FromPtrOr(rule.Name, "")) && equalLoadBalancingRulePropertiesFormat(existingRule.LoadBalancingRulePropertiesFormat, rule.LoadBalancingRulePropertiesFormat, wantLB) { return true } @@ -3555,7 +3556,7 @@ func equalLoadBalancingRulePropertiesFormat(s *network.LoadBalancingRuleProperti } if reflect.DeepEqual(s.Protocol, network.TransportProtocolTCP) { - properties = properties && reflect.DeepEqual(ptr.Deref(s.EnableTCPReset, false), ptr.Deref(t.EnableTCPReset, false)) + properties = properties && reflect.DeepEqual(lo.FromPtrOr(s.EnableTCPReset, false), lo.FromPtrOr(t.EnableTCPReset, false)) } properties = properties && equalSubResource(s.FrontendIPConfiguration, t.FrontendIPConfiguration) && @@ -3565,7 +3566,7 @@ func equalLoadBalancingRulePropertiesFormat(s *network.LoadBalancingRuleProperti reflect.DeepEqual(s.BackendPort, t.BackendPort) && equalSubResource(s.Probe, t.Probe) && reflect.DeepEqual(s.EnableFloatingIP, t.EnableFloatingIP) && - reflect.DeepEqual(ptr.Deref(s.DisableOutboundSnat, false), ptr.Deref(t.DisableOutboundSnat, false)) + reflect.DeepEqual(lo.FromPtrOr(s.DisableOutboundSnat, false), lo.FromPtrOr(t.DisableOutboundSnat, false)) if wantLB && s.IdleTimeoutInMinutes != nil && t.IdleTimeoutInMinutes != nil { return properties && reflect.DeepEqual(s.IdleTimeoutInMinutes, t.IdleTimeoutInMinutes) @@ -3580,7 +3581,7 @@ func equalSubResource(s *network.SubResource, t *network.SubResource) bool { if s == nil || t == nil { return false } - return strings.EqualFold(ptr.Deref(s.ID, ""), ptr.Deref(t.ID, "")) + return strings.EqualFold(lo.FromPtrOr(s.ID, ""), lo.FromPtrOr(t.ID, "")) } func (az *Cloud) getPublicIPAddressResourceGroup(service *v1.Service) string { @@ -3692,7 +3693,7 @@ func serviceOwnsPublicIP(service *v1.Service, pip *network.PublicIPAddress, clus return false, false } - if pip.PublicIPAddressPropertiesFormat == nil || ptr.Deref(pip.IPAddress, "") == "" { + if pip.PublicIPAddressPropertiesFormat == nil || lo.FromPtrOr(pip.IPAddress, "") == "" { klog.Warningf("serviceOwnsPublicIP: empty pip.IPAddress") return false, false } @@ -3731,11 +3732,11 @@ func serviceOwnsPublicIP(service *v1.Service, pip *network.PublicIPAddress, clus } func isServiceLoadBalancerIPMatchesPIP(service *v1.Service, pip *network.PublicIPAddress, isIPV6 bool) bool { - return strings.EqualFold(ptr.Deref(pip.IPAddress, ""), getServiceLoadBalancerIP(service, isIPV6)) + return strings.EqualFold(lo.FromPtrOr(pip.IPAddress, ""), getServiceLoadBalancerIP(service, isIPV6)) } func isServicePIPNameMatchesPIP(service *v1.Service, pip *network.PublicIPAddress, isIPV6 bool) bool { - return strings.EqualFold(ptr.Deref(pip.Name, ""), getServicePIPName(service, isIPV6)) + return strings.EqualFold(lo.FromPtrOr(pip.Name, ""), getServicePIPName(service, isIPV6)) } func isServiceSelectPIP(service *v1.Service, pip *network.PublicIPAddress, isIPV6 bool) bool { @@ -3782,17 +3783,17 @@ func bindServicesToPIP(pip *network.PublicIPAddress, incomingServiceNames []stri } if pip.Tags == nil { - pip.Tags = map[string]*string{consts.ServiceTagKey: ptr.To("")} + pip.Tags = map[string]*string{consts.ServiceTagKey: to.Ptr("")} } - serviceTagValue := ptr.To(getServiceFromPIPServiceTags(pip.Tags)) + serviceTagValue := to.Ptr(getServiceFromPIPServiceTags(pip.Tags)) serviceTagValueSet := make(map[string]struct{}) existingServiceNames := parsePIPServiceTag(serviceTagValue) addedNew := false // replace is used when unbinding the service from PIP so addedNew remains false all the time if replace { - serviceTagValue = ptr.To(strings.Join(incomingServiceNames, ",")) + serviceTagValue = to.Ptr(strings.Join(incomingServiceNames, ",")) pip.Tags[consts.ServiceTagKey] = serviceTagValue return false, nil @@ -3806,7 +3807,7 @@ func bindServicesToPIP(pip *network.PublicIPAddress, incomingServiceNames []stri for _, serviceName := range incomingServiceNames { if serviceTagValue == nil || *serviceTagValue == "" { - serviceTagValue = ptr.To(serviceName) + serviceTagValue = to.Ptr(serviceName) addedNew = true } else { // detect duplicates @@ -3842,7 +3843,7 @@ func unbindServiceFromPIP( } // skip removing tags for user assigned pips - serviceTagValue := ptr.To(getServiceFromPIPServiceTags(pip.Tags)) + serviceTagValue := to.Ptr(getServiceFromPIPServiceTags(pip.Tags)) existingServiceNames := parsePIPServiceTag(serviceTagValue) var found bool for i := len(existingServiceNames) - 1; i >= 0; i-- { @@ -3951,7 +3952,7 @@ func getMostEligibleLBForService( if existingLBs != nil { for i := range *existingLBs { existingLB := (*existingLBs)[i] - if strings.EqualFold(trimSuffixIgnoreCase(ptr.Deref(existingLB.Name, ""), consts.InternalLoadBalancerNameSuffix), eligibleLB) && + if strings.EqualFold(trimSuffixIgnoreCase(lo.FromPtrOr(existingLB.Name, ""), consts.InternalLoadBalancerNameSuffix), eligibleLB) && isInternalLoadBalancer(&existingLB) == isInternal { found = true break @@ -3970,13 +3971,13 @@ func getMostEligibleLBForService( if existingLBs != nil { for i := range *existingLBs { existingLB := (*existingLBs)[i] - if StringInSlice(trimSuffixIgnoreCase(ptr.Deref(existingLB.Name, ""), consts.InternalLoadBalancerNameSuffix), eligibleLBs) && + if StringInSlice(trimSuffixIgnoreCase(lo.FromPtrOr(existingLB.Name, ""), consts.InternalLoadBalancerNameSuffix), eligibleLBs) && isInternalLoadBalancer(&existingLB) == isInternal { if existingLB.LoadBalancerPropertiesFormat != nil && existingLB.LoadBalancingRules != nil { if len(*existingLB.LoadBalancingRules) < ruleCount { ruleCount = len(*existingLB.LoadBalancingRules) - expectedLBName = ptr.Deref(existingLB.Name, "") + expectedLBName = lo.FromPtrOr(existingLB.Name, "") } } } @@ -4052,7 +4053,7 @@ func (az *Cloud) getEligibleLoadBalancersForService(ctx context.Context, service // 2. If the LB does not allow service placement, it is not eligible, // unless the service is already using the LB. - if !ptr.Deref(eligibleLB.AllowServicePlacement, true) { + if !lo.FromPtrOr(eligibleLB.AllowServicePlacement, true) { if az.isLoadBalancerInUseByService(service, eligibleLB) { logger.V(4).Info("although the load balancer has AllowServicePlacement=false, service is allowed to be placed on load balancer because it is using the load balancer", "load balancer configuration name", eligibleLB.Name) @@ -4177,7 +4178,7 @@ func (az *Cloud) isLoadBalancerInUseByService(service *v1.Service, lbConfig conf func (az *Cloud) serviceOwnsFrontendIP(ctx context.Context, fip network.FrontendIPConfiguration, service *v1.Service) (bool, bool, network.IPVersion) { var isPrimaryService bool baseName := az.GetLoadBalancerName(ctx, "", service) - if strings.HasPrefix(ptr.Deref(fip.Name, ""), baseName) { + if strings.HasPrefix(lo.FromPtrOr(fip.Name, ""), baseName) { klog.V(6).Infof("serviceOwnsFrontendIP: found primary service %s of the frontend IP config %s", service.Name, *fip.Name) isPrimaryService = true return true, isPrimaryService, "" diff --git a/pkg/provider/azure_loadbalancer_accesscontrol.go b/pkg/provider/azure_loadbalancer_accesscontrol.go index e2e48a7993..fd2dcb9e3b 100644 --- a/pkg/provider/azure_loadbalancer_accesscontrol.go +++ b/pkg/provider/azure_loadbalancer_accesscontrol.go @@ -22,32 +22,32 @@ import ( "net/netip" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" + "github.com/samber/lo" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/labels" "sigs.k8s.io/cloud-provider-azure/pkg/consts" "sigs.k8s.io/cloud-provider-azure/pkg/log" "sigs.k8s.io/cloud-provider-azure/pkg/provider/loadbalancer" - fnutil "sigs.k8s.io/cloud-provider-azure/pkg/util/collectionutil" ) func filterServicesByIngressIPs(services []*v1.Service, ips []netip.Addr) []*v1.Service { - targetIPs := fnutil.Map(func(ip netip.Addr) string { return ip.String() }, ips) + targetIPs := lo.Map(ips, func(ip netip.Addr, _ int) string { return ip.String() }) - return fnutil.Filter(func(svc *v1.Service) bool { + return lo.Filter(services, func(svc *v1.Service, _ int) bool { - ingressIPs := fnutil.Map(func(ing v1.LoadBalancerIngress) string { return ing.IP }, svc.Status.LoadBalancer.Ingress) + ingressIPs := lo.Map(svc.Status.LoadBalancer.Ingress, func(ing v1.LoadBalancerIngress, _ int) string { return ing.IP }) - ingressIPs = fnutil.Filter(func(ip string) bool { return ip != "" }, ingressIPs) + ingressIPs = lo.Filter(ingressIPs, func(ip string, _ int) bool { return ip != "" }) - return len(fnutil.Intersection(ingressIPs, targetIPs)) > 0 - }, services) + return len(lo.Intersect(ingressIPs, targetIPs)) > 0 + }) } func filterServicesByDisableFloatingIP(services []*v1.Service) []*v1.Service { - return fnutil.Filter(func(svc *v1.Service) bool { + return lo.Filter(services, func(svc *v1.Service, _ int) bool { return consts.IsK8sServiceDisableLoadBalancerFloatingIP(svc) - }, services) + }) } // listSharedIPPortMapping lists the shared IP port mapping for the service excluding the service itself. diff --git a/pkg/provider/azure_loadbalancer_accesscontrol_test.go b/pkg/provider/azure_loadbalancer_accesscontrol_test.go index cd853b50e7..c3d4822844 100644 --- a/pkg/provider/azure_loadbalancer_accesscontrol_test.go +++ b/pkg/provider/azure_loadbalancer_accesscontrol_test.go @@ -33,7 +33,6 @@ import ( "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/informers" "k8s.io/client-go/kubernetes/fake" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/internal/testutil" "sigs.k8s.io/cloud-provider-azure/internal/testutil/fixture" @@ -1414,29 +1413,29 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { Build(), { - Name: ptr.To("foo"), + Name: to.Ptr("foo"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolTCP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), SourceAddressPrefixes: to.SliceOfPtrs("foo"), DestinationPortRanges: to.SliceOfPtrs("4000", "6000"), DestinationAddressPrefixes: to.SliceOfPtrs(azureFx.LoadBalancer().Addresses()...), // Should remove the rule - Priority: ptr.To(int32(4003)), + Priority: to.Ptr(int32(4003)), }, }, { - Name: ptr.To("bar"), + Name: to.Ptr("bar"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolUDP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), SourceAddressPrefixes: to.SliceOfPtrs("bar"), DestinationPortRanges: to.SliceOfPtrs("5000", "6000"), DestinationAddressPrefixes: to.SliceOfPtrs(append(azureFx.LoadBalancer().Addresses(), "bar")...), // Should keep bar but clean the rest - Priority: ptr.To(int32(4004)), + Priority: to.Ptr(int32(4004)), }, }, } @@ -1520,16 +1519,16 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { Build(), &armnetwork.SecurityRule{ - Name: ptr.To("bar"), + Name: to.Ptr("bar"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolUDP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), SourceAddressPrefixes: to.SliceOfPtrs("bar"), DestinationPortRanges: to.SliceOfPtrs("5000", "6000"), - DestinationAddressPrefix: ptr.To("bar"), // Should keep bar but clean the rest - Priority: ptr.To(int32(4004)), + DestinationAddressPrefix: to.Ptr("bar"), // Should keep bar but clean the rest + Priority: to.Ptr(int32(4004)), }, }, ) @@ -1726,29 +1725,29 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { Build(), { - Name: ptr.To("foo"), + Name: to.Ptr("foo"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolTCP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), SourceAddressPrefixes: to.SliceOfPtrs("foo"), DestinationPortRanges: to.SliceOfPtrs("4000", "6000"), DestinationAddressPrefixes: to.SliceOfPtrs(azureFx.LoadBalancer().Addresses()...), // Should remove the rule - Priority: ptr.To(int32(4003)), + Priority: to.Ptr(int32(4003)), }, }, { - Name: ptr.To("bar"), + Name: to.Ptr("bar"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolUDP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), SourceAddressPrefixes: to.SliceOfPtrs("bar"), DestinationPortRanges: to.SliceOfPtrs("5000", "6000"), DestinationAddressPrefixes: to.SliceOfPtrs(append(azureFx.LoadBalancer().Addresses(), "bar")...), // Should keep bar but clean the rest - Priority: ptr.To(int32(4004)), + Priority: to.Ptr(int32(4004)), }, }, @@ -1833,16 +1832,16 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { Build(), &armnetwork.SecurityRule{ - Name: ptr.To("bar"), + Name: to.Ptr("bar"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolUDP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), SourceAddressPrefixes: to.SliceOfPtrs("bar"), DestinationPortRanges: to.SliceOfPtrs("5000", "6000"), - DestinationAddressPrefix: ptr.To("bar"), // Should keep bar but clean the rest - Priority: ptr.To(int32(4004)), + DestinationAddressPrefix: to.Ptr("bar"), // Should keep bar but clean the rest + Priority: to.Ptr(int32(4004)), }, }, azureFx. @@ -2513,29 +2512,29 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { Build(), { - Name: ptr.To("foo"), + Name: to.Ptr("foo"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolTCP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), SourceAddressPrefixes: to.SliceOfPtrs("foo"), DestinationPortRanges: to.SliceOfPtrs("4000", "6000"), DestinationAddressPrefixes: to.SliceOfPtrs(azureFx.LoadBalancer().Addresses()...), // Should remove the rule - Priority: ptr.To(int32(4003)), + Priority: to.Ptr(int32(4003)), }, }, { - Name: ptr.To("bar"), + Name: to.Ptr("bar"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolUDP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), SourceAddressPrefixes: to.SliceOfPtrs("bar"), DestinationPortRanges: to.SliceOfPtrs("5000", "6000"), DestinationAddressPrefixes: to.SliceOfPtrs(append(azureFx.LoadBalancer().Addresses(), "bar")...), // Should keep bar but clean the rest - Priority: ptr.To(int32(4004)), + Priority: to.Ptr(int32(4004)), }, }, } @@ -2589,16 +2588,16 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { Build(), &armnetwork.SecurityRule{ - Name: ptr.To("bar"), + Name: to.Ptr("bar"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolUDP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), SourceAddressPrefixes: to.SliceOfPtrs("bar"), DestinationPortRanges: to.SliceOfPtrs("5000", "6000"), - DestinationAddressPrefix: ptr.To("bar"), // Should keep bar but clean the rest - Priority: ptr.To(int32(4004)), + DestinationAddressPrefix: to.Ptr("bar"), // Should keep bar but clean the rest + Priority: to.Ptr(int32(4004)), }, }, @@ -2700,29 +2699,29 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { Build(), { - Name: ptr.To("foo"), + Name: to.Ptr("foo"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolTCP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), SourceAddressPrefixes: to.SliceOfPtrs("foo"), DestinationPortRanges: to.SliceOfPtrs("4000", "6000"), DestinationAddressPrefixes: to.SliceOfPtrs(azureFx.LoadBalancer().Addresses()...), // Should remove the rule - Priority: ptr.To(int32(4003)), + Priority: to.Ptr(int32(4003)), }, }, { - Name: ptr.To("bar"), + Name: to.Ptr("bar"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolUDP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), SourceAddressPrefixes: to.SliceOfPtrs("bar"), DestinationPortRanges: to.SliceOfPtrs("5000", "6000"), DestinationAddressPrefixes: to.SliceOfPtrs(append(azureFx.LoadBalancer().Addresses(), "bar")...), // Should keep bar but clean the rest - Priority: ptr.To(int32(4004)), + Priority: to.Ptr(int32(4004)), }, }, } @@ -2776,16 +2775,16 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { Build(), &armnetwork.SecurityRule{ - Name: ptr.To("bar"), + Name: to.Ptr("bar"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolUDP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), SourceAddressPrefixes: to.SliceOfPtrs("bar"), DestinationPortRanges: to.SliceOfPtrs("5000", "6000"), - DestinationAddressPrefix: ptr.To("bar"), // Should keep bar but clean the rest - Priority: ptr.To(int32(4004)), + DestinationAddressPrefix: to.Ptr("bar"), // Should keep bar but clean the rest + Priority: to.Ptr(int32(4004)), }, }, @@ -2875,29 +2874,29 @@ func TestCloud_reconcileSecurityGroup(t *testing.T) { Build(), { - Name: ptr.To("foo"), + Name: to.Ptr("foo"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolTCP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), SourceAddressPrefixes: to.SliceOfPtrs("foo"), DestinationPortRanges: to.SliceOfPtrs("4000", "6000"), DestinationAddressPrefixes: to.SliceOfPtrs(azureFx.LoadBalancer().Addresses()...), // Should remove the rule - Priority: ptr.To(int32(4003)), + Priority: to.Ptr(int32(4003)), }, }, { - Name: ptr.To("bar"), + Name: to.Ptr("bar"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolUDP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), SourceAddressPrefixes: to.SliceOfPtrs("bar"), DestinationPortRanges: to.SliceOfPtrs("5000", "6000"), DestinationAddressPrefixes: to.SliceOfPtrs(append(azureFx.LoadBalancer().Addresses(), "bar")...), // Should keep bar but clean the rest - Priority: ptr.To(int32(4004)), + Priority: to.Ptr(int32(4004)), }, }, } diff --git a/pkg/provider/azure_loadbalancer_backendpool.go b/pkg/provider/azure_loadbalancer_backendpool.go index 38364f0f64..190c4bbc9c 100644 --- a/pkg/provider/azure_loadbalancer_backendpool.go +++ b/pkg/provider/azure_loadbalancer_backendpool.go @@ -24,13 +24,13 @@ import ( "fmt" "strings" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - + "github.com/samber/lo" v1 "k8s.io/api/core/v1" cloudprovider "k8s.io/cloud-provider" "k8s.io/klog/v2" utilnet "k8s.io/utils/net" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" @@ -72,11 +72,11 @@ func (bc *backendPoolTypeNodeIPConfig) EnsureHostsInPool(ctx context.Context, se } func isLBBackendPoolsExisting(lbBackendPoolNames map[bool]string, bpName *string) (found, isIPv6 bool) { - if strings.EqualFold(ptr.Deref(bpName, ""), lbBackendPoolNames[consts.IPVersionIPv4]) { + if strings.EqualFold(lo.FromPtrOr(bpName, ""), lbBackendPoolNames[consts.IPVersionIPv4]) { isIPv6 = false found = true } - if strings.EqualFold(ptr.Deref(bpName, ""), lbBackendPoolNames[consts.IPVersionIPv6]) { + if strings.EqualFold(lo.FromPtrOr(bpName, ""), lbBackendPoolNames[consts.IPVersionIPv6]) { isIPv6 = true found = true } @@ -87,7 +87,7 @@ func (bc *backendPoolTypeNodeIPConfig) CleanupVMSetFromBackendPoolByCondition(ct v4Enabled, v6Enabled := getIPFamiliesEnabled(service) lbBackendPoolNames := getBackendPoolNames(clusterName) - lbBackendPoolIDs := bc.getBackendPoolIDs(clusterName, ptr.Deref(slb.Name, "")) + lbBackendPoolIDs := bc.getBackendPoolIDs(clusterName, lo.FromPtrOr(slb.Name, "")) newBackendPools := make([]network.BackendAddressPool, 0) if slb.LoadBalancerPropertiesFormat != nil && slb.BackendAddressPools != nil { newBackendPools = *slb.BackendAddressPools @@ -96,11 +96,11 @@ func (bc *backendPoolTypeNodeIPConfig) CleanupVMSetFromBackendPoolByCondition(ct for j, bp := range newBackendPools { if found, _ := isLBBackendPoolsExisting(lbBackendPoolNames, bp.Name); found { - klog.V(2).Infof("bc.CleanupVMSetFromBackendPoolByCondition: checking the backend pool %s from standard load balancer %s", ptr.Deref(bp.Name, ""), ptr.Deref(slb.Name, "")) + klog.V(2).Infof("bc.CleanupVMSetFromBackendPoolByCondition: checking the backend pool %s from standard load balancer %s", lo.FromPtrOr(bp.Name, ""), lo.FromPtrOr(slb.Name, "")) if bp.BackendAddressPoolPropertiesFormat != nil && bp.BackendIPConfigurations != nil { for i := len(*bp.BackendIPConfigurations) - 1; i >= 0; i-- { ipConf := (*bp.BackendIPConfigurations)[i] - ipConfigID := ptr.Deref(ipConf.ID, "") + ipConfigID := lo.FromPtrOr(ipConf.ID, "") _, vmSetName, err := bc.VMSet.GetNodeNameByIPConfigurationID(ctx, ipConfigID) if err != nil && !errors.Is(err, cloudprovider.InstanceNotFound) { return nil, err @@ -110,7 +110,7 @@ func (bc *backendPoolTypeNodeIPConfig) CleanupVMSetFromBackendPoolByCondition(ct klog.V(2).Infof("bc.CleanupVMSetFromBackendPoolByCondition: 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 interfaceIPConfigToBeDeleted := network.InterfaceIPConfiguration{ - ID: ptr.To(ipConfigID), + ID: to.Ptr(ipConfigID), } vmSetNameToBackendIPConfigurationsToBeDeleted[vmSetName] = append(vmSetNameToBackendIPConfigurationsToBeDeleted[vmSetName], interfaceIPConfigToBeDeleted) *bp.BackendIPConfigurations = append((*bp.BackendIPConfigurations)[:i], (*bp.BackendIPConfigurations)[i+1:]...) @@ -130,7 +130,7 @@ func (bc *backendPoolTypeNodeIPConfig) CleanupVMSetFromBackendPoolByCondition(ct findBackendpoolToBeDeleted := func(isIPv6 bool) { lbBackendPoolIDsSlice = append(lbBackendPoolIDsSlice, lbBackendPoolIDs[isIPv6]) backendpoolToBeDeleted = append(backendpoolToBeDeleted, network.BackendAddressPool{ - ID: ptr.To(lbBackendPoolIDs[isIPv6]), + ID: to.Ptr(lbBackendPoolIDs[isIPv6]), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ BackendIPConfigurations: &backendIPConfigurationsToBeDeleted, }, @@ -148,9 +148,9 @@ func (bc *backendPoolTypeNodeIPConfig) CleanupVMSetFromBackendPoolByCondition(ct return nil, err } if shouldRefreshLB { - slb, _, err := bc.getAzureLoadBalancer(ctx, ptr.Deref(slb.Name, ""), cache.CacheReadTypeForceRefresh) + slb, _, err := bc.getAzureLoadBalancer(ctx, lo.FromPtrOr(slb.Name, ""), cache.CacheReadTypeForceRefresh) if err != nil { - return nil, fmt.Errorf("bc.CleanupVMSetFromBackendPoolByCondition: failed to get load balancer %s, err: %w", ptr.Deref(slb.Name, ""), err) + return nil, fmt.Errorf("bc.CleanupVMSetFromBackendPoolByCondition: failed to get load balancer %s, err: %w", lo.FromPtrOr(slb.Name, ""), err) } } } @@ -189,7 +189,7 @@ func (bc *backendPoolTypeNodeIPConfig) ReconcileBackendPools( found, isIPv6 := isLBBackendPoolsExisting(lbBackendPoolNames, bp.Name) if found { klog.V(10).Infof("bc.ReconcileBackendPools for service (%s): lb backendpool - found wanted backendpool. not adding anything", serviceName) - foundBackendPools[isBackendPoolIPv6(ptr.Deref(bp.Name, ""))] = true + foundBackendPools[isBackendPoolIPv6(lo.FromPtrOr(bp.Name, ""))] = true // Don't bother to remove unused nodeIPConfiguration if backend pool is pre configured if isBackendPoolPreConfigured { @@ -218,7 +218,7 @@ func (bc *backendPoolTypeNodeIPConfig) ReconcileBackendPools( var backendIPConfigurationsToBeDeleted, bipConfigNotFound, bipConfigExclude []network.InterfaceIPConfiguration if bp.BackendAddressPoolPropertiesFormat != nil && bp.BackendIPConfigurations != nil { for _, ipConf := range *bp.BackendIPConfigurations { - ipConfID := ptr.Deref(ipConf.ID, "") + ipConfID := lo.FromPtrOr(ipConf.ID, "") nodeName, _, err := bc.VMSet.GetNodeNameByIPConfigurationID(ctx, ipConfID) if err != nil { if errors.Is(err, cloudprovider.InstanceNotFound) { @@ -241,14 +241,14 @@ func (bc *backendPoolTypeNodeIPConfig) ReconcileBackendPools( if shouldExcludeLoadBalancer { klog.V(2).Infof("bc.ReconcileBackendPools for service (%s): lb backendpool - found unwanted node %s, decouple it from the LB %s", serviceName, nodeName, lbName) // construct a backendPool that only contains the IP config of the node to be deleted - bipConfigExclude = append(bipConfigExclude, network.InterfaceIPConfiguration{ID: ptr.To(ipConfID)}) + bipConfigExclude = append(bipConfigExclude, network.InterfaceIPConfiguration{ID: to.Ptr(ipConfID)}) } } } backendIPConfigurationsToBeDeleted = getBackendIPConfigurationsToBeDeleted(bp, bipConfigNotFound, bipConfigExclude) if len(backendIPConfigurationsToBeDeleted) > 0 { backendpoolToBeDeleted = append(backendpoolToBeDeleted, network.BackendAddressPool{ - ID: ptr.To(lbBackendPoolIDs[isIPv6]), + ID: to.Ptr(lbBackendPoolIDs[isIPv6]), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ BackendIPConfigurations: &backendIPConfigurationsToBeDeleted, }, @@ -256,7 +256,7 @@ func (bc *backendPoolTypeNodeIPConfig) ReconcileBackendPools( lbBackendPoolIDsSlice = append(lbBackendPoolIDsSlice, lbBackendPoolIDs[isIPv6]) } } else { - klog.V(10).Infof("bc.ReconcileBackendPools for service (%s): lb backendpool - found unmanaged backendpool %s", serviceName, ptr.Deref(bp.Name, "")) + klog.V(10).Infof("bc.ReconcileBackendPools for service (%s): lb backendpool - found unmanaged backendpool %s", serviceName, lo.FromPtrOr(bp.Name, "")) } } if len(backendpoolToBeDeleted) > 0 { @@ -309,16 +309,16 @@ func getBackendIPConfigurationsToBeDeleted( bipConfigNotFoundIDSet := utilsets.NewString() bipConfigExcludeIDSet := utilsets.NewString() for _, ipConfig := range bipConfigNotFound { - bipConfigNotFoundIDSet.Insert(ptr.Deref(ipConfig.ID, "")) + bipConfigNotFoundIDSet.Insert(lo.FromPtrOr(ipConfig.ID, "")) } for _, ipConfig := range bipConfigExclude { - bipConfigExcludeIDSet.Insert(ptr.Deref(ipConfig.ID, "")) + bipConfigExcludeIDSet.Insert(lo.FromPtrOr(ipConfig.ID, "")) } var bipConfigToBeDeleted []network.InterfaceIPConfiguration ipConfigs := *bp.BackendIPConfigurations for i := len(ipConfigs) - 1; i >= 0; i-- { - ipConfigID := ptr.Deref(ipConfigs[i].ID, "") + ipConfigID := lo.FromPtrOr(ipConfigs[i].ID, "") if bipConfigNotFoundIDSet.Has(ipConfigID) { bipConfigToBeDeleted = append(bipConfigToBeDeleted, ipConfigs[i]) ipConfigs = append(ipConfigs[:i], ipConfigs[i+1:]...) @@ -327,7 +327,7 @@ func getBackendIPConfigurationsToBeDeleted( var unwantedIPConfigs []network.InterfaceIPConfiguration for _, ipConfig := range ipConfigs { - ipConfigID := ptr.Deref(ipConfig.ID, "") + ipConfigID := lo.FromPtrOr(ipConfig.ID, "") if bipConfigExcludeIDSet.Has(ipConfigID) { unwantedIPConfigs = append(unwantedIPConfigs, ipConfig) } @@ -350,10 +350,10 @@ func (bc *backendPoolTypeNodeIPConfig) GetBackendPrivateIPs(ctx context.Context, for _, bp := range *lb.BackendAddressPools { found, _ := isLBBackendPoolsExisting(lbBackendPoolNames, bp.Name) if found { - klog.V(10).Infof("bc.GetBackendPrivateIPs for service (%s): found wanted backendpool %s", serviceName, ptr.Deref(bp.Name, "")) + klog.V(10).Infof("bc.GetBackendPrivateIPs for service (%s): found wanted backendpool %s", serviceName, lo.FromPtrOr(bp.Name, "")) if bp.BackendAddressPoolPropertiesFormat != nil && bp.BackendIPConfigurations != nil { for _, backendIPConfig := range *bp.BackendIPConfigurations { - ipConfigID := ptr.Deref(backendIPConfig.ID, "") + ipConfigID := lo.FromPtrOr(backendIPConfig.ID, "") nodeName, _, err := bc.VMSet.GetNodeNameByIPConfigurationID(ctx, ipConfigID) if err != nil { klog.Errorf("bc.GetBackendPrivateIPs for service (%s): GetNodeNameByIPConfigurationID failed with error: %v", serviceName, err) @@ -376,7 +376,7 @@ func (bc *backendPoolTypeNodeIPConfig) GetBackendPrivateIPs(ctx context.Context, } } } else { - klog.V(10).Infof("bc.GetBackendPrivateIPs for service (%s): found unmanaged backendpool %s", serviceName, ptr.Deref(bp.Name, "")) + klog.V(10).Infof("bc.GetBackendPrivateIPs for service (%s): found unmanaged backendpool %s", serviceName, lo.FromPtrOr(bp.Name, "")) } } return backendPrivateIPv4s.UnsortedList(), backendPrivateIPv6s.UnsortedList() @@ -404,7 +404,7 @@ func (az *Cloud) getVnetResourceID() string { } func (bi *backendPoolTypeNodeIP) EnsureHostsInPool(ctx context.Context, service *v1.Service, nodes []*v1.Node, _, _, clusterName, lbName string, backendPool network.BackendAddressPool) error { - isIPv6 := isBackendPoolIPv6(ptr.Deref(backendPool.Name, "")) + isIPv6 := isBackendPoolIPv6(lo.FromPtrOr(backendPool.Name, "")) var ( changed bool @@ -428,13 +428,13 @@ func (bi *backendPoolTypeNodeIP) EnsureHostsInPool(ctx context.Context, service } if isNICPool(backendPool) { - klog.V(4).InfoS("EnsureHostsInPool: skipping NIC-based backend pool", "backendPoolName", ptr.Deref(backendPool.Name, "")) + klog.V(4).InfoS("EnsureHostsInPool: skipping NIC-based backend pool", "backendPoolName", lo.FromPtrOr(backendPool.Name, "")) return nil } } lbBackendPoolName := bi.getBackendPoolNameForService(service, clusterName, isIPv6) - if strings.EqualFold(ptr.Deref(backendPool.Name, ""), lbBackendPoolName) && + if strings.EqualFold(lo.FromPtrOr(backendPool.Name, ""), lbBackendPoolName) && backendPool.BackendAddressPoolPropertiesFormat != nil { if backendPool.LoadBalancerBackendAddresses == nil { lbBackendPoolAddresses := make([]network.LoadBalancerBackendAddress, 0) @@ -445,8 +445,8 @@ func (bi *backendPoolTypeNodeIP) EnsureHostsInPool(ctx context.Context, service for _, loadBalancerBackendAddress := range *backendPool.LoadBalancerBackendAddresses { if loadBalancerBackendAddress.LoadBalancerBackendAddressPropertiesFormat != nil && loadBalancerBackendAddress.IPAddress != nil { - klog.V(4).Infof("bi.EnsureHostsInPool: found existing IP %s in the backend pool %s", ptr.Deref(loadBalancerBackendAddress.IPAddress, ""), lbBackendPoolName) - existingIPs.Insert(ptr.Deref(loadBalancerBackendAddress.IPAddress, "")) + klog.V(4).Infof("bi.EnsureHostsInPool: found existing IP %s in the backend pool %s", lo.FromPtrOr(loadBalancerBackendAddress.IPAddress, ""), lbBackendPoolName) + existingIPs.Insert(lo.FromPtrOr(loadBalancerBackendAddress.IPAddress, "")) } } @@ -481,7 +481,7 @@ func (bi *backendPoolTypeNodeIP) EnsureHostsInPool(ctx context.Context, service var nodeIPsToBeDeleted []string for _, loadBalancerBackendAddress := range *backendPool.LoadBalancerBackendAddresses { - ip := ptr.Deref(loadBalancerBackendAddress.IPAddress, "") + ip := lo.FromPtrOr(loadBalancerBackendAddress.IPAddress, "") if !nodePrivateIPsSet.Has(ip) { klog.V(4).Infof("bi.EnsureHostsInPool: removing IP %s because it is deleted or should be excluded", ip) nodeIPsToBeDeleted = append(nodeIPsToBeDeleted, ip) @@ -524,7 +524,7 @@ func (bi *backendPoolTypeNodeIP) CleanupVMSetFromBackendPoolByCondition(ctx cont for j, bp := range newBackendPools { found, isIPv6 := isLBBackendPoolsExisting(lbBackendPoolNames, bp.Name) if found { - klog.V(2).Infof("bi.CleanupVMSetFromBackendPoolByCondition: checking the backend pool %s from standard load balancer %s", ptr.Deref(bp.Name, ""), ptr.Deref(slb.Name, "")) + klog.V(2).Infof("bi.CleanupVMSetFromBackendPoolByCondition: checking the backend pool %s from standard load balancer %s", lo.FromPtrOr(bp.Name, ""), lo.FromPtrOr(slb.Name, "")) vmIPsToBeDeleted := utilsets.NewString() for _, node := range nodes { vmSetName, err := bi.VMSet.GetNodeVMSetName(ctx, node) @@ -542,7 +542,7 @@ func (bi *backendPoolTypeNodeIP) CleanupVMSetFromBackendPoolByCondition(ctx cont if bp.BackendAddressPoolPropertiesFormat != nil && bp.LoadBalancerBackendAddresses != nil { for i := len(*bp.LoadBalancerBackendAddresses) - 1; i >= 0; i-- { if (*bp.LoadBalancerBackendAddresses)[i].LoadBalancerBackendAddressPropertiesFormat != nil && - vmIPsToBeDeleted.Has(ptr.Deref((*bp.LoadBalancerBackendAddresses)[i].IPAddress, "")) { + vmIPsToBeDeleted.Has(lo.FromPtrOr((*bp.LoadBalancerBackendAddresses)[i].IPAddress, "")) { *bp.LoadBalancerBackendAddresses = append((*bp.LoadBalancerBackendAddresses)[:i], (*bp.LoadBalancerBackendAddresses)[i+1:]...) updatedPrivateIPs[isIPv6] = true } @@ -551,17 +551,17 @@ func (bi *backendPoolTypeNodeIP) CleanupVMSetFromBackendPoolByCondition(ctx cont newBackendPools[j] = bp } else { - klog.V(10).Infof("bi.CleanupVMSetFromBackendPoolByCondition: found unmanaged backendpool %s from standard load balancer %q", ptr.Deref(bp.Name, ""), ptr.Deref(slb.Name, "")) + klog.V(10).Infof("bi.CleanupVMSetFromBackendPoolByCondition: found unmanaged backendpool %s from standard load balancer %q", lo.FromPtrOr(bp.Name, ""), lo.FromPtrOr(slb.Name, "")) } } for isIPv6 := range updatedPrivateIPs { - klog.V(2).Infof("bi.CleanupVMSetFromBackendPoolByCondition: updating lb %s since there are private IP updates", ptr.Deref(slb.Name, "")) + klog.V(2).Infof("bi.CleanupVMSetFromBackendPoolByCondition: updating lb %s since there are private IP updates", lo.FromPtrOr(slb.Name, "")) slb.BackendAddressPools = &newBackendPools for _, backendAddressPool := range *slb.BackendAddressPools { - if strings.EqualFold(lbBackendPoolNames[isIPv6], ptr.Deref(backendAddressPool.Name, "")) { - if err := bi.CreateOrUpdateLBBackendPool(ctx, ptr.Deref(slb.Name, ""), backendAddressPool); err != nil { + if strings.EqualFold(lbBackendPoolNames[isIPv6], lo.FromPtrOr(backendAddressPool.Name, "")) { + if err := bi.CreateOrUpdateLBBackendPool(ctx, lo.FromPtrOr(slb.Name, ""), backendAddressPool); err != nil { return nil, fmt.Errorf("bi.CleanupVMSetFromBackendPoolByCondition: "+ "failed to create or update backend pool %s: %w", lbBackendPoolNames[isIPv6], err) } @@ -584,7 +584,7 @@ func (bi *backendPoolTypeNodeIP) ReconcileBackendPools(ctx context.Context, clus serviceName := getServiceName(service) lbBackendPoolNames := bi.getBackendPoolNamesForService(service, clusterName) vmSetName := bi.mapLoadBalancerNameToVMSet(lbName, clusterName) - lbBackendPoolIDs := bi.getBackendPoolIDsForService(service, clusterName, ptr.Deref(lb.Name, "")) + lbBackendPoolIDs := bi.getBackendPoolIDsForService(service, clusterName, lo.FromPtrOr(lb.Name, "")) isBackendPoolPreConfigured := bi.isBackendPoolPreConfigured(service) mc := metrics.NewMetricContext("services", "migrate_to_ip_based_backend_pool", bi.ResourceGroup, bi.getNetworkResourceSubscriptionID(), serviceName) @@ -605,11 +605,11 @@ func (bi *backendPoolTypeNodeIP) ReconcileBackendPools(ctx context.Context, clus lbBackendPoolIDsSlice = append(lbBackendPoolIDsSlice, lbBackendPoolIDs[isIPv6]) if nicsCount := countNICsOnBackendPool(bp); nicsCount > 0 { - nicsCountMap[ptr.Deref(bp.Name, "")] = nicsCount + nicsCountMap[lo.FromPtrOr(bp.Name, "")] = nicsCount klog.V(4).Infof( "bi.ReconcileBackendPools for service(%s): found NIC-based backendpool %s with %d NICs, will migrate to IP-based", serviceName, - ptr.Deref(bp.Name, ""), + lo.FromPtrOr(bp.Name, ""), nicsCount, ) isMigration = true @@ -683,13 +683,13 @@ func (bi *backendPoolTypeNodeIP) ReconcileBackendPools(ctx context.Context, clus var vnet string if bp.BackendAddressPoolPropertiesFormat != nil { if bp.VirtualNetwork == nil || - ptr.Deref(bp.VirtualNetwork.ID, "") == "" { + lo.FromPtrOr(bp.VirtualNetwork.ID, "") == "" { if bp.LoadBalancerBackendAddresses != nil { for _, a := range *bp.LoadBalancerBackendAddresses { if a.LoadBalancerBackendAddressPropertiesFormat != nil && a.VirtualNetwork != nil { if vnet == "" { - vnet = ptr.Deref(a.VirtualNetwork.ID, "") + vnet = lo.FromPtrOr(a.VirtualNetwork.ID, "") } a.VirtualNetwork = nil } @@ -697,7 +697,7 @@ func (bi *backendPoolTypeNodeIP) ReconcileBackendPools(ctx context.Context, clus } if vnet != "" { bp.VirtualNetwork = &network.SubResource{ - ID: ptr.To(vnet), + ID: to.Ptr(vnet), } updated = true } @@ -707,7 +707,7 @@ func (bi *backendPoolTypeNodeIP) ReconcileBackendPools(ctx context.Context, clus if updated { (*lb.BackendAddressPools)[i] = bp if err := bi.CreateOrUpdateLBBackendPool(ctx, lbName, bp); err != nil { - return false, false, nil, fmt.Errorf("bi.ReconcileBackendPools for service (%s): lb backendpool - failed to update backend pool %s for load balancer %s: %w", serviceName, ptr.Deref(bp.Name, ""), lbName, err) + return false, false, nil, fmt.Errorf("bi.ReconcileBackendPools for service (%s): lb backendpool - failed to update backend pool %s for load balancer %s: %w", serviceName, lo.FromPtrOr(bp.Name, ""), lbName, err) } shouldRefreshLB = true } @@ -754,7 +754,7 @@ func (bi *backendPoolTypeNodeIP) GetBackendPrivateIPs(_ context.Context, cluster for _, bp := range *lb.BackendAddressPools { found, _ := isLBBackendPoolsExisting(lbBackendPoolNames, bp.Name) if found { - klog.V(10).Infof("bi.GetBackendPrivateIPs for service (%s): found wanted backendpool %s", serviceName, ptr.Deref(bp.Name, "")) + klog.V(10).Infof("bi.GetBackendPrivateIPs for service (%s): found wanted backendpool %s", serviceName, lo.FromPtrOr(bp.Name, "")) if bp.BackendAddressPoolPropertiesFormat != nil && bp.LoadBalancerBackendAddresses != nil { for _, backendAddress := range *bp.LoadBalancerBackendAddresses { ipAddress := backendAddress.IPAddress @@ -771,7 +771,7 @@ func (bi *backendPoolTypeNodeIP) GetBackendPrivateIPs(_ context.Context, cluster } } } else { - klog.V(10).Infof("bi.GetBackendPrivateIPs for service (%s): found unmanaged backendpool %s", serviceName, ptr.Deref(bp.Name, "")) + klog.V(10).Infof("bi.GetBackendPrivateIPs for service (%s): found unmanaged backendpool %s", serviceName, lo.FromPtrOr(bp.Name, "")) } } return backendPrivateIPv4s.UnsortedList(), backendPrivateIPv6s.UnsortedList() @@ -783,7 +783,7 @@ func (bi *backendPoolTypeNodeIP) getBackendPoolNodeNames(bp *network.BackendAddr if bp.BackendAddressPoolPropertiesFormat != nil && bp.LoadBalancerBackendAddresses != nil { for _, backendAddress := range *bp.LoadBalancerBackendAddresses { if backendAddress.LoadBalancerBackendAddressPropertiesFormat != nil { - ip := ptr.Deref(backendAddress.IPAddress, "") + ip := lo.FromPtrOr(backendAddress.IPAddress, "") nodeNames.Insert(bi.nodePrivateIPToNodeNameMap[ip]) } } @@ -804,7 +804,7 @@ func newBackendPool(lb *network.LoadBalancer, isBackendPoolPreConfigured bool, p lb.BackendAddressPools = &[]network.BackendAddressPool{} } *lb.BackendAddressPools = append(*lb.BackendAddressPools, network.BackendAddressPool{ - Name: ptr.To(lbBackendPoolName), + Name: to.Ptr(lbBackendPoolName), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{}, }) @@ -839,11 +839,11 @@ func (az *Cloud) addNodeIPAddressesToBackendPool(backendPool *network.BackendAdd for _, ipAddress := range nodeIPAddresses { if !hasIPAddressInBackendPool(backendPool, ipAddress) { name := az.nodePrivateIPToNodeNameMap[ipAddress] - klog.V(4).Infof("bi.addNodeIPAddressesToBackendPool: adding %s to the backend pool %s", ipAddress, ptr.Deref(backendPool.Name, "")) + klog.V(4).Infof("bi.addNodeIPAddressesToBackendPool: adding %s to the backend pool %s", ipAddress, lo.FromPtrOr(backendPool.Name, "")) addresses = append(addresses, network.LoadBalancerBackendAddress{ - Name: ptr.To(name), + Name: to.Ptr(name), LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To(ipAddress), + IPAddress: to.Ptr(ipAddress), }, }) changed = true @@ -861,7 +861,7 @@ func hasIPAddressInBackendPool(backendPool *network.BackendAddressPool, ipAddres addresses := *backendPool.LoadBalancerBackendAddresses for _, address := range addresses { if address.LoadBalancerBackendAddressPropertiesFormat != nil && - ptr.Deref(address.IPAddress, "") == ipAddress { + lo.FromPtrOr(address.IPAddress, "") == ipAddress { return true } } @@ -887,19 +887,19 @@ func removeNodeIPAddressesFromBackendPool( addresses := *backendPool.LoadBalancerBackendAddresses for i := len(addresses) - 1; i >= 0; i-- { if addresses[i].LoadBalancerBackendAddressPropertiesFormat != nil { - ipAddress := ptr.Deref((*backendPool.LoadBalancerBackendAddresses)[i].IPAddress, "") + ipAddress := lo.FromPtrOr((*backendPool.LoadBalancerBackendAddresses)[i].IPAddress, "") if ipAddress == "" { if isNodeIP { - logger.V(4).Info("LoadBalancerBackendAddress is not IP-based, removing", "LoadBalancerBackendAddress", ptr.Deref(addresses[i].Name, "")) + logger.V(4).Info("LoadBalancerBackendAddress is not IP-based, removing", "LoadBalancerBackendAddress", lo.FromPtrOr(addresses[i].Name, "")) addresses = append(addresses[:i], addresses[i+1:]...) changed = true } else { - logger.V(4).Info("LoadBalancerBackendAddress is not IP-based, skipping", "LoadBalancerBackendAddress", ptr.Deref(addresses[i].Name, "")) + logger.V(4).Info("LoadBalancerBackendAddress is not IP-based, skipping", "LoadBalancerBackendAddress", lo.FromPtrOr(addresses[i].Name, "")) } continue } if removeAll || nodeIPsSet.Has(ipAddress) { - klog.V(4).Infof("removeNodeIPAddressFromBackendPool: removing %s from the backend pool %s", ipAddress, ptr.Deref(backendPool.Name, "")) + klog.V(4).Infof("removeNodeIPAddressFromBackendPool: removing %s from the backend pool %s", ipAddress, lo.FromPtrOr(backendPool.Name, "")) addresses = append(addresses[:i], addresses[i+1:]...) changed = true } diff --git a/pkg/provider/azure_loadbalancer_backendpool_test.go b/pkg/provider/azure_loadbalancer_backendpool_test.go index 2675786e4a..e2fc2aa979 100644 --- a/pkg/provider/azure_loadbalancer_backendpool_test.go +++ b/pkg/provider/azure_loadbalancer_backendpool_test.go @@ -23,16 +23,14 @@ import ( "strings" "testing" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" "github.com/stretchr/testify/assert" - "go.uber.org/mock/gomock" - v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes/fake" cloudprovider "k8s.io/cloud-provider" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/loadbalancerclient/mockloadbalancerclient" "sigs.k8s.io/cloud-provider-azure/pkg/consts" @@ -119,42 +117,42 @@ func TestEnsureHostsInPoolNodeIP(t *testing.T) { { desc: "IPv4", backendPool: network.BackendAddressPool{ - Name: ptr.To("kubernetes"), + Name: to.Ptr("kubernetes"), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ { LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To("10.0.0.1"), + IPAddress: to.Ptr("10.0.0.1"), }, }, { LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To("10.0.0.3"), + IPAddress: to.Ptr("10.0.0.3"), }, }, }, }, }, expectedBackendPool: network.BackendAddressPool{ - Name: ptr.To("kubernetes"), + Name: to.Ptr("kubernetes"), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - VirtualNetwork: &network.SubResource{ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks/vnet")}, + VirtualNetwork: &network.SubResource{ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks/vnet")}, LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ { LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To("10.0.0.1"), + IPAddress: to.Ptr("10.0.0.1"), }, }, { - Name: ptr.To("vmss-0"), + Name: to.Ptr("vmss-0"), LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To("10.0.0.2"), + IPAddress: to.Ptr("10.0.0.2"), }, }, { - Name: ptr.To("vmss-2"), + Name: to.Ptr("vmss-2"), LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To("10.0.0.4"), + IPAddress: to.Ptr("10.0.0.4"), }, }, }, @@ -164,37 +162,37 @@ func TestEnsureHostsInPoolNodeIP(t *testing.T) { { desc: "IPv6", backendPool: network.BackendAddressPool{ - Name: ptr.To("kubernetes-IPv6"), + Name: to.Ptr("kubernetes-IPv6"), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ { LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To("2001::1"), + IPAddress: to.Ptr("2001::1"), }, }, }, }, }, expectedBackendPool: network.BackendAddressPool{ - Name: ptr.To("kubernetes-IPv6"), + Name: to.Ptr("kubernetes-IPv6"), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - VirtualNetwork: &network.SubResource{ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks/vnet")}, + VirtualNetwork: &network.SubResource{ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks/vnet")}, LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ { LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To("2001::1"), + IPAddress: to.Ptr("2001::1"), }, }, { - Name: ptr.To("vmss-0"), + Name: to.Ptr("vmss-0"), LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To("2001::2"), + IPAddress: to.Ptr("2001::2"), }, }, { - Name: ptr.To("vmss-2"), + Name: to.Ptr("vmss-2"), LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To("2001::4"), + IPAddress: to.Ptr("2001::4"), }, }, }, @@ -204,12 +202,12 @@ func TestEnsureHostsInPoolNodeIP(t *testing.T) { { desc: "should skip NIC-based backend pool when using multi-slb", backendPool: network.BackendAddressPool{ - Name: ptr.To("kubernetes"), + Name: to.Ptr("kubernetes"), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ { LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To(""), + IPAddress: to.Ptr(""), }, }, }, @@ -224,12 +222,12 @@ func TestEnsureHostsInPoolNodeIP(t *testing.T) { }, }, expectedBackendPool: network.BackendAddressPool{ - Name: ptr.To("kubernetes"), + Name: to.Ptr("kubernetes"), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ { LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To(""), + IPAddress: to.Ptr(""), }, }, }, @@ -240,17 +238,17 @@ func TestEnsureHostsInPoolNodeIP(t *testing.T) { { desc: "should add correct nodes to the pool and remove unwanted ones when using multi-slb", backendPool: network.BackendAddressPool{ - Name: ptr.To("kubernetes"), + Name: to.Ptr("kubernetes"), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ { LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To("10.0.0.1"), + IPAddress: to.Ptr("10.0.0.1"), }, }, { LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To("10.0.0.3"), + IPAddress: to.Ptr("10.0.0.3"), }, }, }, @@ -265,14 +263,14 @@ func TestEnsureHostsInPoolNodeIP(t *testing.T) { }, }, expectedBackendPool: network.BackendAddressPool{ - Name: ptr.To("kubernetes"), + Name: to.Ptr("kubernetes"), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - VirtualNetwork: &network.SubResource{ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks/vnet")}, + VirtualNetwork: &network.SubResource{ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks/vnet")}, LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ { - Name: ptr.To("vmss-2"), + Name: to.Ptr("vmss-2"), LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To("10.0.0.4"), + IPAddress: to.Ptr("10.0.0.4"), }, }, }, @@ -303,7 +301,7 @@ func TestEnsureHostsInPoolNodeIP(t *testing.T) { desc: "local service with its endpoint slice in cache", local: true, backendPool: network.BackendAddressPool{ - Name: ptr.To("default-svc-1"), + Name: to.Ptr("default-svc-1"), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{}, }, @@ -314,20 +312,20 @@ func TestEnsureHostsInPoolNodeIP(t *testing.T) { }, }, expectedBackendPool: network.BackendAddressPool{ - Name: ptr.To("default-svc-1"), + Name: to.Ptr("default-svc-1"), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - VirtualNetwork: &network.SubResource{ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks/vnet")}, + VirtualNetwork: &network.SubResource{ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks/vnet")}, LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ { - Name: ptr.To("vmss-0"), + Name: to.Ptr("vmss-0"), LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To("10.0.0.2"), + IPAddress: to.Ptr("10.0.0.2"), }, }, { - Name: ptr.To("vmss-1"), + Name: to.Ptr("vmss-1"), LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To("10.0.0.1"), + IPAddress: to.Ptr("10.0.0.1"), }, }, }, @@ -339,7 +337,7 @@ func TestEnsureHostsInPoolNodeIP(t *testing.T) { desc: "local service in another namespace", local: true, backendPool: network.BackendAddressPool{ - Name: ptr.To("another-svc-1"), + Name: to.Ptr("another-svc-1"), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{}, }, @@ -350,20 +348,20 @@ func TestEnsureHostsInPoolNodeIP(t *testing.T) { }, }, expectedBackendPool: network.BackendAddressPool{ - Name: ptr.To("another-svc-1"), + Name: to.Ptr("another-svc-1"), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ - VirtualNetwork: &network.SubResource{ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks/vnet")}, + VirtualNetwork: &network.SubResource{ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks/vnet")}, LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ { - Name: ptr.To("vmss-0"), + Name: to.Ptr("vmss-0"), LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To("10.0.0.2"), + IPAddress: to.Ptr("10.0.0.2"), }, }, { - Name: ptr.To("vmss-2"), + Name: to.Ptr("vmss-2"), LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To("10.0.0.4"), + IPAddress: to.Ptr("10.0.0.4"), }, }, }, @@ -457,7 +455,7 @@ func TestIsLBBackendPoolsExisting(t *testing.T) { false: "bp", true: "bp-IPv6", }, - bpName: ptr.To("bp"), + bpName: to.Ptr("bp"), expectedFound: true, expectedIsIPv6: false, }, @@ -467,7 +465,7 @@ func TestIsLBBackendPoolsExisting(t *testing.T) { false: "bp", true: "bp-IPv6", }, - bpName: ptr.To("bp-IPv6"), + bpName: to.Ptr("bp-IPv6"), expectedFound: true, expectedIsIPv6: true, }, @@ -477,7 +475,7 @@ func TestIsLBBackendPoolsExisting(t *testing.T) { false: "bp", true: "bp-IPv6", }, - bpName: ptr.To("bp0"), + bpName: to.Ptr("bp0"), expectedFound: false, expectedIsIPv6: false, }, @@ -510,15 +508,15 @@ func TestCleanupVMSetFromBackendPoolByConditionNodeIPConfig(t *testing.T) { cloud.VMSet = mockVMSet expectedLB := network.LoadBalancer{ - Name: ptr.To("testCluster"), + Name: to.Ptr("testCluster"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ BackendAddressPools: &[]network.BackendAddressPool{ { - Name: ptr.To("testCluster"), + Name: to.Ptr("testCluster"), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ BackendIPConfigurations: &[]network.InterfaceIPConfiguration{ { - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/k8s-agentpool1-00000000-nic-1/ipConfigurations/ipconfig1"), + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/k8s-agentpool1-00000000-nic-1/ipConfigurations/ipconfig1"), }, }, }, @@ -602,15 +600,15 @@ func TestCleanupVMSetFromBackendPoolForInstanceNotFound(t *testing.T) { cloud.VMSet = mockVMSet expectedLB := network.LoadBalancer{ - Name: ptr.To("testCluster"), + Name: to.Ptr("testCluster"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ BackendAddressPools: &[]network.BackendAddressPool{ { - Name: ptr.To("testCluster"), + Name: to.Ptr("testCluster"), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ BackendIPConfigurations: &[]network.InterfaceIPConfiguration{ { - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/k8s-agentpool1-00000000-nic-1/ipConfigurations/ipconfig1"), + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/k8s-agentpool1-00000000-nic-1/ipConfigurations/ipconfig1"), }, }, }, @@ -659,7 +657,7 @@ func TestReconcileBackendPoolsNodeIPConfig(t *testing.T) { assert.NoError(t, err) lb = network.LoadBalancer{ - Name: ptr.To(testClusterName), + Name: to.Ptr(testClusterName), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{}, } az = GetTestCloud(ctrl) @@ -792,15 +790,15 @@ func TestReconcileBackendPoolsNodeIP(t *testing.T) { } bp := network.BackendAddressPool{ - Name: ptr.To("kubernetes"), + Name: to.Ptr("kubernetes"), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ VirtualNetwork: &network.SubResource{ - ID: ptr.To("vnet"), + ID: to.Ptr("vnet"), }, LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ { LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To("10.0.0.2"), + IPAddress: to.Ptr("10.0.0.2"), }, }, }, @@ -827,7 +825,7 @@ func TestReconcileBackendPoolsNodeIP(t *testing.T) { assert.NoError(t, err) lb = &network.LoadBalancer{ - Name: ptr.To(testClusterName), + Name: to.Ptr(testClusterName), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{}, } az = GetTestCloud(ctrl) @@ -1109,11 +1107,11 @@ func TestGetBackendIPConfigurationsToBeDeleted(t *testing.T) { { description: "should ignore excluded IP configurations if the backend pool will be empty after removing IP configurations of not found vms", bipConfigNotFound: []network.InterfaceIPConfiguration{ - {ID: ptr.To("ipconfig1")}, - {ID: ptr.To("ipconfig2")}, + {ID: to.Ptr("ipconfig1")}, + {ID: to.Ptr("ipconfig2")}, }, bipConfigExclude: []network.InterfaceIPConfiguration{ - {ID: ptr.To("ipconfig3")}, + {ID: to.Ptr("ipconfig3")}, }, expected: map[string]bool{ "ipconfig1": true, @@ -1123,10 +1121,10 @@ func TestGetBackendIPConfigurationsToBeDeleted(t *testing.T) { { description: "should remove both not found and excluded vms", bipConfigNotFound: []network.InterfaceIPConfiguration{ - {ID: ptr.To("ipconfig1")}, + {ID: to.Ptr("ipconfig1")}, }, bipConfigExclude: []network.InterfaceIPConfiguration{ - {ID: ptr.To("ipconfig3")}, + {ID: to.Ptr("ipconfig3")}, }, expected: map[string]bool{ "ipconfig1": true, @@ -1136,12 +1134,12 @@ func TestGetBackendIPConfigurationsToBeDeleted(t *testing.T) { { description: "should remove all not found vms even if the backend pool will be empty", bipConfigNotFound: []network.InterfaceIPConfiguration{ - {ID: ptr.To("ipconfig1")}, - {ID: ptr.To("ipconfig2")}, - {ID: ptr.To("ipconfig3")}, + {ID: to.Ptr("ipconfig1")}, + {ID: to.Ptr("ipconfig2")}, + {ID: to.Ptr("ipconfig3")}, }, bipConfigExclude: []network.InterfaceIPConfiguration{ - {ID: ptr.To("ipconfig4")}, + {ID: to.Ptr("ipconfig4")}, }, expected: map[string]bool{ "ipconfig1": true, @@ -1153,9 +1151,9 @@ func TestGetBackendIPConfigurationsToBeDeleted(t *testing.T) { bp := network.BackendAddressPool{ BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ BackendIPConfigurations: &[]network.InterfaceIPConfiguration{ - {ID: ptr.To("ipconfig1")}, - {ID: ptr.To("ipconfig2")}, - {ID: ptr.To("ipconfig3")}, + {ID: to.Ptr("ipconfig1")}, + {ID: to.Ptr("ipconfig2")}, + {ID: to.Ptr("ipconfig3")}, }, }, } diff --git a/pkg/provider/azure_loadbalancer_healthprobe.go b/pkg/provider/azure_loadbalancer_healthprobe.go index 281a8d94d9..adccc5804a 100644 --- a/pkg/provider/azure_loadbalancer_healthprobe.go +++ b/pkg/provider/azure_loadbalancer_healthprobe.go @@ -21,24 +21,24 @@ import ( "strconv" "strings" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - + "github.com/samber/lo" v1 "k8s.io/api/core/v1" "k8s.io/klog/v2" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/consts" ) func (az *Cloud) buildClusterServiceSharedProbe() *network.Probe { return &network.Probe{ - Name: ptr.To(consts.SharedProbeName), + Name: to.Ptr(consts.SharedProbeName), ProbePropertiesFormat: &network.ProbePropertiesFormat{ Protocol: network.ProbeProtocolHTTP, - Port: ptr.To(az.ClusterServiceSharedLoadBalancerHealthProbePort), - RequestPath: ptr.To(az.ClusterServiceSharedLoadBalancerHealthProbePath), - IntervalInSeconds: ptr.To(consts.HealthProbeDefaultProbeInterval), - ProbeThreshold: ptr.To(consts.HealthProbeDefaultNumOfProbe), + Port: to.Ptr(az.ClusterServiceSharedLoadBalancerHealthProbePort), + RequestPath: to.Ptr(az.ClusterServiceSharedLoadBalancerHealthProbePath), + IntervalInSeconds: to.Ptr(consts.HealthProbeDefaultProbeInterval), + ProbeThreshold: to.Ptr(consts.HealthProbeDefaultNumOfProbe), }, } } @@ -99,7 +99,7 @@ func (az *Cloud) buildHealthProbeRulesForPort(serviceManifest *v1.Service, port for _, item := range serviceManifest.Spec.Ports { if strings.EqualFold(item.Name, *probePort) { //found the port - properties.Port = ptr.To(item.NodePort) + properties.Port = to.Ptr(item.NodePort) } } } else { @@ -109,14 +109,14 @@ func (az *Cloud) buildHealthProbeRulesForPort(serviceManifest *v1.Service, port //nolint:gosec if item.Port == int32(port) { //found the port - properties.Port = ptr.To(item.NodePort) + properties.Port = to.Ptr(item.NodePort) found = true break } } if !found { //nolint:gosec - properties.Port = ptr.To(int32(port)) + properties.Port = to.Ptr(int32(port)) } } } else if healthCheckNodePortProbe != nil { @@ -150,7 +150,7 @@ func (az *Cloud) buildHealthProbeRulesForPort(serviceManifest *v1.Service, port // 4. Finally, if protocol is still nil, default to TCP if protocol == nil { - protocol = ptr.To(string(network.ProtocolTCP)) + protocol = to.Ptr(string(network.ProtocolTCP)) } *protocol = strings.TrimSpace(*protocol) @@ -185,7 +185,7 @@ func (az *Cloud) buildHealthProbeRulesForPort(serviceManifest *v1.Service, port } } if path == nil { - path = ptr.To(consts.HealthProbeDefaultRequestPath) + path = to.Ptr(consts.HealthProbeDefaultRequestPath) } properties.RequestPath = path } @@ -244,7 +244,7 @@ func (*Cloud) getHealthProbeConfigProbeInterval(serviceManifest *v1.Service, por } if probeInterval == nil { - probeInterval = ptr.To(consts.HealthProbeDefaultProbeInterval) + probeInterval = to.Ptr(consts.HealthProbeDefaultProbeInterval) } return probeInterval, nil } @@ -273,19 +273,19 @@ func (*Cloud) getHealthProbeConfigNumOfProbe(serviceManifest *v1.Service, port i } if numberOfProbes == nil { - numberOfProbes = ptr.To(consts.HealthProbeDefaultNumOfProbe) + numberOfProbes = to.Ptr(consts.HealthProbeDefaultNumOfProbe) } return numberOfProbes, nil } func findProbe(probes []network.Probe, probe network.Probe) bool { for _, existingProbe := range probes { - if strings.EqualFold(ptr.Deref(existingProbe.Name, ""), ptr.Deref(probe.Name, "")) && - ptr.Deref(existingProbe.Port, 0) == ptr.Deref(probe.Port, 0) && + if strings.EqualFold(lo.FromPtrOr(existingProbe.Name, ""), lo.FromPtrOr(probe.Name, "")) && + lo.FromPtrOr(existingProbe.Port, 0) == lo.FromPtrOr(probe.Port, 0) && strings.EqualFold(string(existingProbe.Protocol), string(probe.Protocol)) && - strings.EqualFold(ptr.Deref(existingProbe.RequestPath, ""), ptr.Deref(probe.RequestPath, "")) && - ptr.Deref(existingProbe.IntervalInSeconds, 0) == ptr.Deref(probe.IntervalInSeconds, 0) && - ptr.Deref(existingProbe.ProbeThreshold, 0) == ptr.Deref(probe.ProbeThreshold, 0) { + strings.EqualFold(lo.FromPtrOr(existingProbe.RequestPath, ""), lo.FromPtrOr(probe.RequestPath, "")) && + lo.FromPtrOr(existingProbe.IntervalInSeconds, 0) == lo.FromPtrOr(probe.IntervalInSeconds, 0) && + lo.FromPtrOr(existingProbe.ProbeThreshold, 0) == lo.FromPtrOr(probe.ProbeThreshold, 0) { return true } } @@ -306,7 +306,7 @@ func (az *Cloud) keepSharedProbe( if lb.LoadBalancerPropertiesFormat != nil && lb.Probes != nil { for _, probe := range *lb.Probes { - if strings.EqualFold(ptr.Deref(probe.Name, ""), consts.SharedProbeName) { + if strings.EqualFold(lo.FromPtrOr(probe.Name, ""), consts.SharedProbeName) { if !az.useSharedLoadBalancerHealthProbeMode() { shouldConsiderRemoveSharedProbe = true } diff --git a/pkg/provider/azure_loadbalancer_healthprobe_test.go b/pkg/provider/azure_loadbalancer_healthprobe_test.go index b1e35c3b05..6e4d106cdb 100644 --- a/pkg/provider/azure_loadbalancer_healthprobe_test.go +++ b/pkg/provider/azure_loadbalancer_healthprobe_test.go @@ -21,15 +21,13 @@ import ( "strings" "testing" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" "github.com/stretchr/testify/assert" - "go.uber.org/mock/gomock" - v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/consts" ) @@ -48,7 +46,7 @@ func getTestProbe(protocol, path string, interval, servicePort, probePort, numOf suffix = "-" + consts.IPVersionIPv6String } expectedProbes := network.Probe{ - Name: ptr.To(fmt.Sprintf("atest1-TCP-%d", *servicePort) + suffix), + Name: to.Ptr(fmt.Sprintf("atest1-TCP-%d", *servicePort) + suffix), ProbePropertiesFormat: &network.ProbePropertiesFormat{ Protocol: network.ProbeProtocol(protocol), Port: probePort, @@ -57,14 +55,14 @@ func getTestProbe(protocol, path string, interval, servicePort, probePort, numOf }, } if (strings.EqualFold(protocol, "Http") || strings.EqualFold(protocol, "Https")) && len(strings.TrimSpace(path)) > 0 { - expectedProbes.RequestPath = ptr.To(path) + expectedProbes.RequestPath = to.Ptr(path) } return expectedProbes } // getDefaultTestProbes returns dualStack probes. func getDefaultTestProbes(protocol, path string) map[bool][]network.Probe { - return getTestProbes(protocol, path, ptr.To(int32(5)), ptr.To(int32(80)), ptr.To(int32(10080)), ptr.To(int32(2))) + return getTestProbes(protocol, path, to.Ptr(int32(5)), to.Ptr(int32(80)), to.Ptr(int32(10080)), to.Ptr(int32(2))) } func TestFindProbe(t *testing.T) { @@ -82,16 +80,16 @@ func TestFindProbe(t *testing.T) { msg: "probe names match while ports don't should return false", existingProbe: []network.Probe{ { - Name: ptr.To("httpProbe"), + Name: to.Ptr("httpProbe"), ProbePropertiesFormat: &network.ProbePropertiesFormat{ - Port: ptr.To(int32(1)), + Port: to.Ptr(int32(1)), }, }, }, curProbe: network.Probe{ - Name: ptr.To("httpProbe"), + Name: to.Ptr("httpProbe"), ProbePropertiesFormat: &network.ProbePropertiesFormat{ - Port: ptr.To(int32(2)), + Port: to.Ptr(int32(2)), }, }, expected: false, @@ -100,16 +98,16 @@ func TestFindProbe(t *testing.T) { msg: "probe ports match while names don't should return false", existingProbe: []network.Probe{ { - Name: ptr.To("probe1"), + Name: to.Ptr("probe1"), ProbePropertiesFormat: &network.ProbePropertiesFormat{ - Port: ptr.To(int32(1)), + Port: to.Ptr(int32(1)), }, }, }, curProbe: network.Probe{ - Name: ptr.To("probe2"), + Name: to.Ptr("probe2"), ProbePropertiesFormat: &network.ProbePropertiesFormat{ - Port: ptr.To(int32(1)), + Port: to.Ptr(int32(1)), }, }, expected: false, @@ -118,17 +116,17 @@ func TestFindProbe(t *testing.T) { msg: "probe protocol don't match should return false", existingProbe: []network.Probe{ { - Name: ptr.To("probe1"), + Name: to.Ptr("probe1"), ProbePropertiesFormat: &network.ProbePropertiesFormat{ - Port: ptr.To(int32(1)), + Port: to.Ptr(int32(1)), Protocol: network.ProbeProtocolHTTP, }, }, }, curProbe: network.Probe{ - Name: ptr.To("probe1"), + Name: to.Ptr("probe1"), ProbePropertiesFormat: &network.ProbePropertiesFormat{ - Port: ptr.To(int32(1)), + Port: to.Ptr(int32(1)), Protocol: network.ProbeProtocolTCP, }, }, @@ -138,18 +136,18 @@ func TestFindProbe(t *testing.T) { msg: "probe path don't match should return false", existingProbe: []network.Probe{ { - Name: ptr.To("probe1"), + Name: to.Ptr("probe1"), ProbePropertiesFormat: &network.ProbePropertiesFormat{ - Port: ptr.To(int32(1)), - RequestPath: ptr.To("/path1"), + Port: to.Ptr(int32(1)), + RequestPath: to.Ptr("/path1"), }, }, }, curProbe: network.Probe{ - Name: ptr.To("probe1"), + Name: to.Ptr("probe1"), ProbePropertiesFormat: &network.ProbePropertiesFormat{ - Port: ptr.To(int32(1)), - RequestPath: ptr.To("/path2"), + Port: to.Ptr(int32(1)), + RequestPath: to.Ptr("/path2"), }, }, expected: false, @@ -158,20 +156,20 @@ func TestFindProbe(t *testing.T) { msg: "probe interval don't match should return false", existingProbe: []network.Probe{ { - Name: ptr.To("probe1"), + Name: to.Ptr("probe1"), ProbePropertiesFormat: &network.ProbePropertiesFormat{ - Port: ptr.To(int32(1)), - RequestPath: ptr.To("/path"), - IntervalInSeconds: ptr.To(int32(5)), + Port: to.Ptr(int32(1)), + RequestPath: to.Ptr("/path"), + IntervalInSeconds: to.Ptr(int32(5)), }, }, }, curProbe: network.Probe{ - Name: ptr.To("probe1"), + Name: to.Ptr("probe1"), ProbePropertiesFormat: &network.ProbePropertiesFormat{ - Port: ptr.To(int32(1)), - RequestPath: ptr.To("/path"), - IntervalInSeconds: ptr.To(int32(10)), + Port: to.Ptr(int32(1)), + RequestPath: to.Ptr("/path"), + IntervalInSeconds: to.Ptr(int32(10)), }, }, expected: false, @@ -180,16 +178,16 @@ func TestFindProbe(t *testing.T) { msg: "probe match should return true", existingProbe: []network.Probe{ { - Name: ptr.To("matchName"), + Name: to.Ptr("matchName"), ProbePropertiesFormat: &network.ProbePropertiesFormat{ - Port: ptr.To(int32(1)), + Port: to.Ptr(int32(1)), }, }, }, curProbe: network.Probe{ - Name: ptr.To("matchName"), + Name: to.Ptr("matchName"), ProbePropertiesFormat: &network.ProbePropertiesFormat{ - Port: ptr.To(int32(1)), + Port: to.Ptr(int32(1)), }, }, expected: true, @@ -226,7 +224,7 @@ func TestShouldKeepSharedProbe(t *testing.T) { LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ Probes: &[]network.Probe{ { - Name: ptr.To("notSharedProbe"), + Name: to.Ptr("notSharedProbe"), }, }, }, @@ -240,7 +238,7 @@ func TestShouldKeepSharedProbe(t *testing.T) { LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ Probes: &[]network.Probe{ { - Name: ptr.To(consts.SharedProbeName), + Name: to.Ptr(consts.SharedProbeName), ProbePropertiesFormat: &network.ProbePropertiesFormat{ LoadBalancingRules: &[]network.SubResource{}, }, @@ -261,15 +259,15 @@ func TestShouldKeepSharedProbe(t *testing.T) { LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ Probes: &[]network.Probe{ { - Name: ptr.To(consts.SharedProbeName), - ID: ptr.To("id"), + Name: to.Ptr(consts.SharedProbeName), + ID: to.Ptr("id"), ProbePropertiesFormat: &network.ProbePropertiesFormat{ LoadBalancingRules: &[]network.SubResource{ { - ID: ptr.To("other"), + ID: to.Ptr("other"), }, { - ID: ptr.To("auid"), + ID: to.Ptr("auid"), }, }, }, @@ -290,15 +288,15 @@ func TestShouldKeepSharedProbe(t *testing.T) { LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ Probes: &[]network.Probe{ { - Name: ptr.To(consts.SharedProbeName), - ID: ptr.To("id"), + Name: to.Ptr(consts.SharedProbeName), + ID: to.Ptr("id"), ProbePropertiesFormat: &network.ProbePropertiesFormat{ LoadBalancingRules: &[]network.SubResource{ { - ID: ptr.To("other"), + ID: to.Ptr("other"), }, { - ID: ptr.To("auid"), + ID: to.Ptr("auid"), }, }, }, @@ -319,12 +317,12 @@ func TestShouldKeepSharedProbe(t *testing.T) { LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ Probes: &[]network.Probe{ { - Name: ptr.To(consts.SharedProbeName), - ID: ptr.To("id"), + Name: to.Ptr(consts.SharedProbeName), + ID: to.Ptr("id"), ProbePropertiesFormat: &network.ProbePropertiesFormat{ LoadBalancingRules: &[]network.SubResource{ { - ID: ptr.To("auid"), + ID: to.Ptr("auid"), }, }, }, @@ -347,12 +345,12 @@ func TestShouldKeepSharedProbe(t *testing.T) { LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ Probes: &[]network.Probe{ { - Name: ptr.To(consts.SharedProbeName), - ID: ptr.To("id"), + Name: to.Ptr(consts.SharedProbeName), + ID: to.Ptr("id"), ProbePropertiesFormat: &network.ProbePropertiesFormat{ LoadBalancingRules: &[]network.SubResource{ { - ID: ptr.To(""), + ID: to.Ptr(""), }, }, }, diff --git a/pkg/provider/azure_loadbalancer_repo.go b/pkg/provider/azure_loadbalancer_repo.go index 9141db1ffc..8dad9d44c8 100644 --- a/pkg/provider/azure_loadbalancer_repo.go +++ b/pkg/provider/azure_loadbalancer_repo.go @@ -26,11 +26,10 @@ import ( "time" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - + "github.com/samber/lo" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/klog/v2" - "k8s.io/utils/ptr" azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" @@ -116,9 +115,9 @@ func (az *Cloud) ListManagedLBs(ctx context.Context, service *v1.Service, nodes } for _, lb := range allLBs { - if managedLBNames.Has(trimSuffixIgnoreCase(ptr.Deref(lb.Name, ""), consts.InternalLoadBalancerNameSuffix)) { + if managedLBNames.Has(trimSuffixIgnoreCase(lo.FromPtrOr(lb.Name, ""), consts.InternalLoadBalancerNameSuffix)) { managedLBs = append(managedLBs, lb) - klog.V(4).Infof("ListManagedLBs: found managed LB %s", ptr.Deref(lb.Name, "")) + klog.V(4).Infof("ListManagedLBs: found managed LB %s", lo.FromPtrOr(lb.Name, "")) } } @@ -130,7 +129,7 @@ func (az *Cloud) CreateOrUpdateLB(ctx context.Context, service *v1.Service, lb n lb = cleanupSubnetInFrontendIPConfigurations(&lb) rgName := az.getLoadBalancerResourceGroup() - rerr := az.LoadBalancerClient.CreateOrUpdate(ctx, rgName, ptr.Deref(lb.Name, ""), lb, ptr.Deref(lb.Etag, "")) + rerr := az.LoadBalancerClient.CreateOrUpdate(ctx, rgName, lo.FromPtrOr(lb.Name, ""), lb, lo.FromPtrOr(lb.Etag, "")) klog.V(10).Infof("LoadBalancerClient.CreateOrUpdate(%s): end", *lb.Name) if rerr == nil { // Invalidate the cache right after updating @@ -139,18 +138,18 @@ func (az *Cloud) CreateOrUpdateLB(ctx context.Context, service *v1.Service, lb n } lbJSON, _ := json.Marshal(lb) - klog.Warningf("LoadBalancerClient.CreateOrUpdate(%s) failed: %v, LoadBalancer request: %s", ptr.Deref(lb.Name, ""), rerr.Error(), string(lbJSON)) + klog.Warningf("LoadBalancerClient.CreateOrUpdate(%s) failed: %v, LoadBalancer request: %s", lo.FromPtrOr(lb.Name, ""), rerr.Error(), string(lbJSON)) // Invalidate the cache because ETAG precondition mismatch. if rerr.HTTPStatusCode == http.StatusPreconditionFailed { - klog.V(3).Infof("LoadBalancer cache for %s is cleanup because of http.StatusPreconditionFailed", ptr.Deref(lb.Name, "")) + klog.V(3).Infof("LoadBalancer cache for %s is cleanup because of http.StatusPreconditionFailed", lo.FromPtrOr(lb.Name, "")) _ = az.lbCache.Delete(*lb.Name) } retryErrorMessage := rerr.Error().Error() // Invalidate the cache because another new operation has canceled the current request. if strings.Contains(strings.ToLower(retryErrorMessage), consts.OperationCanceledErrorMessage) { - klog.V(3).Infof("LoadBalancer cache for %s is cleanup because CreateOrUpdate is canceled by another operation", ptr.Deref(lb.Name, "")) + klog.V(3).Infof("LoadBalancer cache for %s is cleanup because CreateOrUpdate is canceled by another operation", lo.FromPtrOr(lb.Name, "")) _ = az.lbCache.Delete(*lb.Name) } @@ -162,7 +161,7 @@ func (az *Cloud) CreateOrUpdateLB(ctx context.Context, service *v1.Service, lb n return rerr.Error() } 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, ptr.Deref(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, lo.FromPtrOr(lb.Name, "")) pip, _, err := az.getPublicIPAddress(ctx, pipRG, pipName, azcache.CacheReadTypeDefault) if err != nil { klog.Errorf("Failed to get the public IP %s in resource group %s: %v", pipName, pipRG, err) @@ -183,8 +182,8 @@ func (az *Cloud) CreateOrUpdateLB(ctx context.Context, service *v1.Service, lb n } func (az *Cloud) CreateOrUpdateLBBackendPool(ctx context.Context, lbName string, backendPool network.BackendAddressPool) error { - klog.V(4).Infof("CreateOrUpdateLBBackendPool: updating backend pool %s in LB %s", ptr.Deref(backendPool.Name, ""), lbName) - rerr := az.LoadBalancerClient.CreateOrUpdateBackendPools(ctx, az.getLoadBalancerResourceGroup(), lbName, ptr.Deref(backendPool.Name, ""), backendPool, ptr.Deref(backendPool.Etag, "")) + klog.V(4).Infof("CreateOrUpdateLBBackendPool: updating backend pool %s in LB %s", lo.FromPtrOr(backendPool.Name, ""), lbName) + rerr := az.LoadBalancerClient.CreateOrUpdateBackendPools(ctx, az.getLoadBalancerResourceGroup(), lbName, lo.FromPtrOr(backendPool.Name, ""), backendPool, lo.FromPtrOr(backendPool.Etag, "")) if rerr == nil { // Invalidate the cache right after updating _ = az.lbCache.Delete(lbName) @@ -381,13 +380,13 @@ func (az *Cloud) serviceOwnsRule(service *v1.Service, rule string) bool { } func isNICPool(bp network.BackendAddressPool) bool { - logger := klog.Background().WithName("isNICPool").WithValues("backendPoolName", ptr.Deref(bp.Name, "")) + logger := klog.Background().WithName("isNICPool").WithValues("backendPoolName", lo.FromPtrOr(bp.Name, "")) if bp.BackendAddressPoolPropertiesFormat != nil && bp.LoadBalancerBackendAddresses != nil { for _, addr := range *bp.LoadBalancerBackendAddresses { - if ptr.Deref(addr.IPAddress, "") == "" { + if lo.FromPtrOr(addr.IPAddress, "") == "" { logger.V(4).Info("The load balancer backend address has empty ip address, assuming it is a NIC pool", - "loadBalancerBackendAddress", ptr.Deref(addr.Name, "")) + "loadBalancerBackendAddress", lo.FromPtrOr(addr.Name, "")) return true } } diff --git a/pkg/provider/azure_loadbalancer_repo_test.go b/pkg/provider/azure_loadbalancer_repo_test.go index 6b2b84431d..b1f23c920b 100644 --- a/pkg/provider/azure_loadbalancer_repo_test.go +++ b/pkg/provider/azure_loadbalancer_repo_test.go @@ -23,13 +23,11 @@ import ( "net/http" "testing" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" "github.com/stretchr/testify/assert" - "go.uber.org/mock/gomock" - v1 "k8s.io/api/core/v1" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/loadbalancerclient/mockloadbalancerclient" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/publicipclient/mockpublicipclient" @@ -73,36 +71,36 @@ func TestListManagedLBs(t *testing.T) { }, { existingLBs: []network.LoadBalancer{ - {Name: ptr.To("kubernetes")}, - {Name: ptr.To("kubernetes-internal")}, - {Name: ptr.To("vmas-1")}, - {Name: ptr.To("vmas-1-internal")}, - {Name: ptr.To("unmanaged")}, - {Name: ptr.To("unmanaged-internal")}, + {Name: to.Ptr("kubernetes")}, + {Name: to.Ptr("kubernetes-internal")}, + {Name: to.Ptr("vmas-1")}, + {Name: to.Ptr("vmas-1-internal")}, + {Name: to.Ptr("unmanaged")}, + {Name: to.Ptr("unmanaged-internal")}, }, expectedLBs: &[]network.LoadBalancer{ - {Name: ptr.To("kubernetes")}, - {Name: ptr.To("kubernetes-internal")}, - {Name: ptr.To("vmas-1")}, - {Name: ptr.To("vmas-1-internal")}, + {Name: to.Ptr("kubernetes")}, + {Name: to.Ptr("kubernetes-internal")}, + {Name: to.Ptr("vmas-1")}, + {Name: to.Ptr("vmas-1-internal")}, }, callTimes: 1, }, { existingLBs: []network.LoadBalancer{ - {Name: ptr.To("kubernetes")}, - {Name: ptr.To("kubernetes-internal")}, - {Name: ptr.To("lb1-internal")}, - {Name: ptr.To("lb2")}, + {Name: to.Ptr("kubernetes")}, + {Name: to.Ptr("kubernetes-internal")}, + {Name: to.Ptr("lb1-internal")}, + {Name: to.Ptr("lb2")}, }, multiSLBConfigs: []config.MultipleStandardLoadBalancerConfiguration{ {Name: "kubernetes"}, {Name: "lb1"}, }, expectedLBs: &[]network.LoadBalancer{ - {Name: ptr.To("kubernetes")}, - {Name: ptr.To("kubernetes-internal")}, - {Name: ptr.To("lb1-internal")}, + {Name: to.Ptr("kubernetes")}, + {Name: to.Ptr("kubernetes-internal")}, + {Name: to.Ptr("lb1-internal")}, }, }, } @@ -163,15 +161,15 @@ func TestCreateOrUpdateLB(t *testing.T) { mockPIPClient := az.PublicIPAddressesClient.(*mockpublicipclient.MockInterface) mockPIPClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, "pip", gomock.Any()).Return(nil).MaxTimes(1) mockPIPClient.EXPECT().List(gomock.Any(), az.ResourceGroup).Return([]network.PublicIPAddress{{ - Name: ptr.To("pip"), + Name: to.Ptr("pip"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ ProvisioningState: network.ProvisioningStateSucceeded, }, }}, nil).MaxTimes(2) err := az.CreateOrUpdateLB(context.TODO(), &v1.Service{}, network.LoadBalancer{ - Name: ptr.To("lb"), - Etag: ptr.To("etag"), + Name: to.Ptr("lb"), + Etag: to.Ptr("etag"), }) assert.EqualError(t, test.expectedErr, err.Error()) @@ -274,29 +272,29 @@ func TestMigrateToIPBasedBackendPoolAndWaitForCompletion(t *testing.T) { { desc: "MigrateToIPBasedBackendPoolAndWaitForCompletion should retry if the number IPs on the backend pool is not expected", backendPool: network.BackendAddressPool{ - Name: ptr.To(testClusterName), + Name: to.Ptr(testClusterName), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ { LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, }, }, }, backendPoolAfterRetry: &network.BackendAddressPool{ - Name: ptr.To(testClusterName), + Name: to.Ptr(testClusterName), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ { LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, { LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To("2.3.4.5"), + IPAddress: to.Ptr("2.3.4.5"), }, }, }, @@ -440,14 +438,14 @@ func TestIsNICPool(t *testing.T) { { desc: "nil BackendAddressPoolPropertiesFormat", bp: network.BackendAddressPool{ - Name: ptr.To("pool1"), + Name: to.Ptr("pool1"), }, expected: false, }, { desc: "nil LoadBalancerBackendAddresses", bp: network.BackendAddressPool{ - Name: ptr.To("pool1"), + Name: to.Ptr("pool1"), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{}, }, expected: false, @@ -455,7 +453,7 @@ func TestIsNICPool(t *testing.T) { { desc: "empty LoadBalancerBackendAddresses", bp: network.BackendAddressPool{ - Name: ptr.To("pool1"), + Name: to.Ptr("pool1"), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{}, }, @@ -465,13 +463,13 @@ func TestIsNICPool(t *testing.T) { { desc: "LoadBalancerBackendAddress with empty IPAddress", bp: network.BackendAddressPool{ - Name: ptr.To("pool1"), + Name: to.Ptr("pool1"), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ { - Name: ptr.To("addr1"), + Name: to.Ptr("addr1"), LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To(""), + IPAddress: to.Ptr(""), }, }, }, @@ -482,13 +480,13 @@ func TestIsNICPool(t *testing.T) { { desc: "LoadBalancerBackendAddress with non-empty IPAddress", bp: network.BackendAddressPool{ - Name: ptr.To("pool1"), + Name: to.Ptr("pool1"), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ { - Name: ptr.To("addr1"), + Name: to.Ptr("addr1"), LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To("10.0.0.1"), + IPAddress: to.Ptr("10.0.0.1"), }, }, }, @@ -499,19 +497,19 @@ func TestIsNICPool(t *testing.T) { { desc: "LoadBalancerBackendAddress with both empty and non-empty IPAddress", bp: network.BackendAddressPool{ - Name: ptr.To("pool1"), + Name: to.Ptr("pool1"), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ { - Name: ptr.To("addr1"), + Name: to.Ptr("addr1"), LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To(""), + IPAddress: to.Ptr(""), }, }, { - Name: ptr.To("addr2"), + Name: to.Ptr("addr2"), LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To("10.0.0.2"), + IPAddress: to.Ptr("10.0.0.2"), }, }, }, diff --git a/pkg/provider/azure_loadbalancer_test.go b/pkg/provider/azure_loadbalancer_test.go index 6b0fb9e1dd..f3cf6a9d63 100644 --- a/pkg/provider/azure_loadbalancer_test.go +++ b/pkg/provider/azure_loadbalancer_test.go @@ -32,6 +32,7 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" + "github.com/samber/lo" "github.com/stretchr/testify/assert" "go.uber.org/mock/gomock" "golang.org/x/text/cases" @@ -44,7 +45,6 @@ import ( "k8s.io/apimachinery/pkg/util/sets" "k8s.io/client-go/kubernetes/fake" k8stesting "k8s.io/client-go/testing" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/loadbalancerclient/mockloadbalancerclient" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/publicipclient/mockpublicipclient" @@ -90,9 +90,9 @@ func TestExistsPip(t *testing.T) { func(client *mockpublicipclient.MockInterface) { pips := []network.PublicIPAddress{ { - Name: ptr.To("testCluster-aservice"), + Name: to.Ptr("testCluster-aservice"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, } @@ -114,9 +114,9 @@ func TestExistsPip(t *testing.T) { func(client *mockpublicipclient.MockInterface) { pips := []network.PublicIPAddress{ { - Name: ptr.To("testCluster-aservice"), + Name: to.Ptr("testCluster-aservice"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("fe::1"), + IPAddress: to.Ptr("fe::1"), }, }, } @@ -130,9 +130,9 @@ func TestExistsPip(t *testing.T) { func(client *mockpublicipclient.MockInterface) { pips := []network.PublicIPAddress{ { - Name: ptr.To("testCluster-aservice-IPv6"), + Name: to.Ptr("testCluster-aservice-IPv6"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("fe::1"), + IPAddress: to.Ptr("fe::1"), }, }, } @@ -146,15 +146,15 @@ func TestExistsPip(t *testing.T) { func(client *mockpublicipclient.MockInterface) { pips := []network.PublicIPAddress{ { - Name: ptr.To("testCluster-aservice"), + Name: to.Ptr("testCluster-aservice"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, { - Name: ptr.To("testCluster-aservice-IPv6"), + Name: to.Ptr("testCluster-aservice-IPv6"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("fe::1"), + IPAddress: to.Ptr("fe::1"), }, }, } @@ -168,9 +168,9 @@ func TestExistsPip(t *testing.T) { func(client *mockpublicipclient.MockInterface) { pips := []network.PublicIPAddress{ { - Name: ptr.To("testCluster-aservice-IPv6"), + Name: to.Ptr("testCluster-aservice-IPv6"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("fe::1"), + IPAddress: to.Ptr("fe::1"), }, }, } @@ -194,30 +194,30 @@ func TestExistsPip(t *testing.T) { // TODO: Dualstack func TestGetLoadBalancer(t *testing.T) { lb1 := network.LoadBalancer{ - Name: ptr.To("testCluster"), + Name: to.Ptr("testCluster"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{}, } lb2 := network.LoadBalancer{ - Name: ptr.To("testCluster"), + Name: to.Ptr("testCluster"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ FrontendIPConfigurations: &[]network.FrontendIPConfiguration{ { - Name: ptr.To("aservice"), + Name: to.Ptr("aservice"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-aservice")}, }, }, }, }, } lb3 := network.LoadBalancer{ - Name: ptr.To("testCluster-internal"), + Name: to.Ptr("testCluster-internal"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ FrontendIPConfigurations: &[]network.FrontendIPConfiguration{ { - Name: ptr.To("aservice"), + Name: to.Ptr("aservice"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PrivateIPAddress: ptr.To("10.0.0.6"), + PrivateIPAddress: to.Ptr("10.0.0.6"), }, }, }, @@ -305,9 +305,9 @@ func TestGetLoadBalancer(t *testing.T) { if c.pipExists { mockPIPsClient.EXPECT().List(gomock.Any(), "rg").Return([]network.PublicIPAddress{ { - Name: ptr.To("testCluster-aservice"), + Name: to.Ptr("testCluster-aservice"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, }, nil) @@ -341,16 +341,16 @@ func TestFindRule(t *testing.T) { msg: "rule names don't match should return false", existingRule: []network.LoadBalancingRule{ { - Name: ptr.To("httpProbe1"), + Name: to.Ptr("httpProbe1"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - FrontendPort: ptr.To(int32(1)), + FrontendPort: to.Ptr(int32(1)), }, }, }, curRule: network.LoadBalancingRule{ - Name: ptr.To("httpProbe2"), + Name: to.Ptr("httpProbe2"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - FrontendPort: ptr.To(int32(1)), + FrontendPort: to.Ptr(int32(1)), }, }, expected: false, @@ -359,14 +359,14 @@ func TestFindRule(t *testing.T) { msg: "rule names match while protocols don't should return false", existingRule: []network.LoadBalancingRule{ { - Name: ptr.To("httpRule"), + Name: to.Ptr("httpRule"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ Protocol: network.TransportProtocolTCP, }, }, }, curRule: network.LoadBalancingRule{ - Name: ptr.To("httpRule"), + Name: to.Ptr("httpRule"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ Protocol: network.TransportProtocolUDP, }, @@ -377,18 +377,18 @@ func TestFindRule(t *testing.T) { msg: "rule names match while EnableTCPResets don't should return false", existingRule: []network.LoadBalancingRule{ { - Name: ptr.To("httpRule"), + Name: to.Ptr("httpRule"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ Protocol: network.TransportProtocolTCP, - EnableTCPReset: ptr.To(true), + EnableTCPReset: to.Ptr(true), }, }, }, curRule: network.LoadBalancingRule{ - Name: ptr.To("httpRule"), + Name: to.Ptr("httpRule"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ Protocol: network.TransportProtocolTCP, - EnableTCPReset: ptr.To(false), + EnableTCPReset: to.Ptr(false), }, }, expected: false, @@ -397,16 +397,16 @@ func TestFindRule(t *testing.T) { msg: "rule names match while frontend ports don't should return false", existingRule: []network.LoadBalancingRule{ { - Name: ptr.To("httpProbe"), + Name: to.Ptr("httpProbe"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - FrontendPort: ptr.To(int32(1)), + FrontendPort: to.Ptr(int32(1)), }, }, }, curRule: network.LoadBalancingRule{ - Name: ptr.To("httpProbe"), + Name: to.Ptr("httpProbe"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - FrontendPort: ptr.To(int32(2)), + FrontendPort: to.Ptr(int32(2)), }, }, expected: false, @@ -415,16 +415,16 @@ func TestFindRule(t *testing.T) { msg: "rule names match while backend ports don't should return false", existingRule: []network.LoadBalancingRule{ { - Name: ptr.To("httpProbe"), + Name: to.Ptr("httpProbe"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - BackendPort: ptr.To(int32(1)), + BackendPort: to.Ptr(int32(1)), }, }, }, curRule: network.LoadBalancingRule{ - Name: ptr.To("httpProbe"), + Name: to.Ptr("httpProbe"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - BackendPort: ptr.To(int32(2)), + BackendPort: to.Ptr(int32(2)), }, }, expected: false, @@ -433,16 +433,16 @@ func TestFindRule(t *testing.T) { msg: "rule names match while idletimeout don't should return false", existingRule: []network.LoadBalancingRule{ { - Name: ptr.To("httpRule"), + Name: to.Ptr("httpRule"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - IdleTimeoutInMinutes: ptr.To(int32(1)), + IdleTimeoutInMinutes: to.Ptr(int32(1)), }, }, }, curRule: network.LoadBalancingRule{ - Name: ptr.To("httpRule"), + Name: to.Ptr("httpRule"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - IdleTimeoutInMinutes: ptr.To(int32(2)), + IdleTimeoutInMinutes: to.Ptr(int32(2)), }, }, expected: false, @@ -451,14 +451,14 @@ func TestFindRule(t *testing.T) { msg: "rule names match while idletimeout nil should return true", existingRule: []network.LoadBalancingRule{ { - Name: ptr.To("httpRule"), + Name: to.Ptr("httpRule"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{}, }, }, curRule: network.LoadBalancingRule{ - Name: ptr.To("httpRule"), + Name: to.Ptr("httpRule"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - IdleTimeoutInMinutes: ptr.To(int32(2)), + IdleTimeoutInMinutes: to.Ptr(int32(2)), }, }, expected: true, @@ -467,14 +467,14 @@ func TestFindRule(t *testing.T) { msg: "rule names match while LoadDistribution don't should return false", existingRule: []network.LoadBalancingRule{ { - Name: ptr.To("httpRule"), + Name: to.Ptr("httpRule"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ LoadDistribution: network.LoadDistributionSourceIP, }, }, }, curRule: network.LoadBalancingRule{ - Name: ptr.To("httpRule"), + Name: to.Ptr("httpRule"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ LoadDistribution: network.LoadDistributionDefault, }, @@ -485,16 +485,16 @@ func TestFindRule(t *testing.T) { msg: "rule and probe names match should return true", existingRule: []network.LoadBalancingRule{ { - Name: ptr.To("probe1"), + Name: to.Ptr("probe1"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - Probe: &network.SubResource{ID: ptr.To("probe")}, + Probe: &network.SubResource{ID: to.Ptr("probe")}, }, }, }, curRule: network.LoadBalancingRule{ - Name: ptr.To("probe1"), + Name: to.Ptr("probe1"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - Probe: &network.SubResource{ID: ptr.To("probe")}, + Probe: &network.SubResource{ID: to.Ptr("probe")}, }, }, expected: true, @@ -503,16 +503,16 @@ func TestFindRule(t *testing.T) { msg: "rule names match while probe don't should return false", existingRule: []network.LoadBalancingRule{ { - Name: ptr.To("probe1"), + Name: to.Ptr("probe1"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ Probe: nil, }, }, }, curRule: network.LoadBalancingRule{ - Name: ptr.To("probe1"), + Name: to.Ptr("probe1"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - Probe: &network.SubResource{ID: ptr.To("probe")}, + Probe: &network.SubResource{ID: to.Ptr("probe")}, }, }, expected: false, @@ -521,19 +521,19 @@ func TestFindRule(t *testing.T) { msg: "both rule names and LoadBalancingRulePropertiesFormats match should return true", existingRule: []network.LoadBalancingRule{ { - Name: ptr.To("matchName"), + Name: to.Ptr("matchName"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - BackendPort: ptr.To(int32(2)), - FrontendPort: ptr.To(int32(2)), + BackendPort: to.Ptr(int32(2)), + FrontendPort: to.Ptr(int32(2)), LoadDistribution: network.LoadDistributionSourceIP, }, }, }, curRule: network.LoadBalancingRule{ - Name: ptr.To("matchName"), + Name: to.Ptr("matchName"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - BackendPort: ptr.To(int32(2)), - FrontendPort: ptr.To(int32(2)), + BackendPort: to.Ptr(int32(2)), + FrontendPort: to.Ptr(int32(2)), LoadDistribution: network.LoadDistributionSourceIP, }, }, @@ -543,16 +543,16 @@ func TestFindRule(t *testing.T) { msg: "rule and FrontendIPConfiguration names match should return true", existingRule: []network.LoadBalancingRule{ { - Name: ptr.To("matchName"), + Name: to.Ptr("matchName"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - FrontendIPConfiguration: &network.SubResource{ID: ptr.To("FrontendIPConfiguration")}, + FrontendIPConfiguration: &network.SubResource{ID: to.Ptr("FrontendIPConfiguration")}, }, }, }, curRule: network.LoadBalancingRule{ - Name: ptr.To("matchName"), + Name: to.Ptr("matchName"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - FrontendIPConfiguration: &network.SubResource{ID: ptr.To("frontendipconfiguration")}, + FrontendIPConfiguration: &network.SubResource{ID: to.Ptr("frontendipconfiguration")}, }, }, expected: true, @@ -561,16 +561,16 @@ func TestFindRule(t *testing.T) { msg: "rule names match while FrontendIPConfiguration don't should return false", existingRule: []network.LoadBalancingRule{ { - Name: ptr.To("matchName"), + Name: to.Ptr("matchName"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - FrontendIPConfiguration: &network.SubResource{ID: ptr.To("FrontendIPConfiguration")}, + FrontendIPConfiguration: &network.SubResource{ID: to.Ptr("FrontendIPConfiguration")}, }, }, }, curRule: network.LoadBalancingRule{ - Name: ptr.To("matchName"), + Name: to.Ptr("matchName"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - FrontendIPConfiguration: &network.SubResource{ID: ptr.To("frontendipconifguration")}, + FrontendIPConfiguration: &network.SubResource{ID: to.Ptr("frontendipconifguration")}, }, }, expected: false, @@ -579,16 +579,16 @@ func TestFindRule(t *testing.T) { msg: "rule and BackendAddressPool names match should return true", existingRule: []network.LoadBalancingRule{ { - Name: ptr.To("matchName"), + Name: to.Ptr("matchName"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - BackendAddressPool: &network.SubResource{ID: ptr.To("BackendAddressPool")}, + BackendAddressPool: &network.SubResource{ID: to.Ptr("BackendAddressPool")}, }, }, }, curRule: network.LoadBalancingRule{ - Name: ptr.To("matchName"), + Name: to.Ptr("matchName"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - BackendAddressPool: &network.SubResource{ID: ptr.To("backendaddresspool")}, + BackendAddressPool: &network.SubResource{ID: to.Ptr("backendaddresspool")}, }, }, expected: true, @@ -597,16 +597,16 @@ func TestFindRule(t *testing.T) { msg: "rule and Probe names match should return true", existingRule: []network.LoadBalancingRule{ { - Name: ptr.To("matchName"), + Name: to.Ptr("matchName"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - Probe: &network.SubResource{ID: ptr.To("Probe")}, + Probe: &network.SubResource{ID: to.Ptr("Probe")}, }, }, }, curRule: network.LoadBalancingRule{ - Name: ptr.To("matchName"), + Name: to.Ptr("matchName"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - Probe: &network.SubResource{ID: ptr.To("probe")}, + Probe: &network.SubResource{ID: to.Ptr("probe")}, }, }, expected: true, @@ -677,7 +677,7 @@ func TestSubnet(t *testing.T) { }, }, }, - expected: ptr.To("subnet"), + expected: to.Ptr("subnet"), }, } { realValue := getInternalSubnet(c.service) @@ -825,7 +825,7 @@ func TestEnsureLoadBalancerLock(t *testing.T) { Namespace: "kube-system", }, Spec: coordinationv1.LeaseSpec{ - LeaseDurationSeconds: ptr.To[int32](900), + LeaseDurationSeconds: to.Ptr[int32](900), }, }) // update lease failed for the second time @@ -881,7 +881,7 @@ func TestEnsureLoadBalancerDeletedLock(t *testing.T) { Namespace: "kube-system", }, Spec: coordinationv1.LeaseSpec{ - LeaseDurationSeconds: ptr.To[int32](900), + LeaseDurationSeconds: to.Ptr[int32](900), }, }) // update lease failed for the second time @@ -929,12 +929,12 @@ func TestServiceOwnsPublicIP(t *testing.T) { { desc: "false should be returned when service name tag doesn't match", pip: &network.PublicIPAddress{ - Name: ptr.To("pip1"), + Name: to.Ptr("pip1"), Tags: map[string]*string{ - consts.ServiceTagKey: ptr.To("default/nginx"), + consts.ServiceTagKey: to.Ptr("default/nginx"), }, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, serviceName: "web", @@ -944,10 +944,10 @@ func TestServiceOwnsPublicIP(t *testing.T) { desc: "true should be returned when service name tag matches and cluster name tag is not set", pip: &network.PublicIPAddress{ Tags: map[string]*string{ - consts.ServiceTagKey: ptr.To("default/nginx"), + consts.ServiceTagKey: to.Ptr("default/nginx"), }, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, clusterName: "kubernetes", @@ -958,11 +958,11 @@ func TestServiceOwnsPublicIP(t *testing.T) { desc: "false should be returned when cluster name doesn't match", pip: &network.PublicIPAddress{ Tags: map[string]*string{ - consts.ServiceTagKey: ptr.To("default/nginx"), - consts.ClusterNameKey: ptr.To("kubernetes"), + consts.ServiceTagKey: to.Ptr("default/nginx"), + consts.ClusterNameKey: to.Ptr("kubernetes"), }, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, clusterName: "k8s", @@ -972,13 +972,13 @@ func TestServiceOwnsPublicIP(t *testing.T) { { desc: "false should be returned when cluster name matches while service name doesn't match", pip: &network.PublicIPAddress{ - Name: ptr.To("pip1"), + Name: to.Ptr("pip1"), Tags: map[string]*string{ - consts.ServiceTagKey: ptr.To("default/web"), - consts.ClusterNameKey: ptr.To("kubernetes"), + consts.ServiceTagKey: to.Ptr("default/web"), + consts.ClusterNameKey: to.Ptr("kubernetes"), }, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, clusterName: "kubernetes", @@ -989,11 +989,11 @@ func TestServiceOwnsPublicIP(t *testing.T) { desc: "true should be returned when both service name tag and cluster name match", pip: &network.PublicIPAddress{ Tags: map[string]*string{ - consts.ServiceTagKey: ptr.To("default/nginx"), - consts.ClusterNameKey: ptr.To("kubernetes"), + consts.ServiceTagKey: to.Ptr("default/nginx"), + consts.ClusterNameKey: to.Ptr("kubernetes"), }, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, clusterName: "kubernetes", @@ -1003,13 +1003,13 @@ func TestServiceOwnsPublicIP(t *testing.T) { { desc: "false should be returned when the tag is empty and load balancer IP does not match", pip: &network.PublicIPAddress{ - Name: ptr.To("pip1"), + Name: to.Ptr("pip1"), Tags: map[string]*string{ - consts.ServiceTagKey: ptr.To(""), - consts.ClusterNameKey: ptr.To("kubernetes"), + consts.ServiceTagKey: to.Ptr(""), + consts.ClusterNameKey: to.Ptr("kubernetes"), }, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, clusterName: "kubernetes", @@ -1021,11 +1021,11 @@ func TestServiceOwnsPublicIP(t *testing.T) { desc: "true should be returned if there is a match among a multi-service tag", pip: &network.PublicIPAddress{ Tags: map[string]*string{ - consts.ServiceTagKey: ptr.To("default/nginx1,default/nginx2"), - consts.ClusterNameKey: ptr.To("kubernetes"), + consts.ServiceTagKey: to.Ptr("default/nginx1,default/nginx2"), + consts.ClusterNameKey: to.Ptr("kubernetes"), }, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, clusterName: "kubernetes", @@ -1035,13 +1035,13 @@ func TestServiceOwnsPublicIP(t *testing.T) { { desc: "false should be returned if there is not a match among a multi-service tag", pip: &network.PublicIPAddress{ - Name: ptr.To("pip1"), + Name: to.Ptr("pip1"), Tags: map[string]*string{ - consts.ServiceTagKey: ptr.To("default/nginx1,default/nginx2"), - consts.ClusterNameKey: ptr.To("kubernetes"), + consts.ServiceTagKey: to.Ptr("default/nginx1,default/nginx2"), + consts.ClusterNameKey: to.Ptr("kubernetes"), }, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, clusterName: "kubernetes", @@ -1052,11 +1052,11 @@ func TestServiceOwnsPublicIP(t *testing.T) { desc: "true should be returned if the load balancer IP is matched even if the svc name is not included in the tag", pip: &network.PublicIPAddress{ Tags: map[string]*string{ - consts.ServiceTagKey: ptr.To(""), - consts.ClusterNameKey: ptr.To("kubernetes"), + consts.ServiceTagKey: to.Ptr(""), + consts.ClusterNameKey: to.Ptr("kubernetes"), }, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, clusterName: "kubernetes", @@ -1069,11 +1069,11 @@ func TestServiceOwnsPublicIP(t *testing.T) { desc: "true should be returned if the load balancer IP is not matched but the svc name is included in the tag", pip: &network.PublicIPAddress{ Tags: map[string]*string{ - consts.ServiceTagKey: ptr.To("default/nginx1,default/nginx2"), - consts.ClusterNameKey: ptr.To("kubernetes"), + consts.ServiceTagKey: to.Ptr("default/nginx1,default/nginx2"), + consts.ClusterNameKey: to.Ptr("kubernetes"), }, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, clusterName: "kubernetes", @@ -1085,7 +1085,7 @@ func TestServiceOwnsPublicIP(t *testing.T) { desc: "should be user-assigned pip if it has no tags", pip: &network.PublicIPAddress{ PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, serviceLBIP: "1.2.3.4", @@ -1095,9 +1095,9 @@ func TestServiceOwnsPublicIP(t *testing.T) { { desc: "should be true if the pip name matches", pip: &network.PublicIPAddress{ - Name: ptr.To("pip1"), + Name: to.Ptr("pip1"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, serviceLBName: "pip1", @@ -1107,10 +1107,10 @@ func TestServiceOwnsPublicIP(t *testing.T) { { desc: "should be true if the pip with tag matches the pip name", pip: &network.PublicIPAddress{ - Name: ptr.To("pip1"), + Name: to.Ptr("pip1"), Tags: map[string]*string{}, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, serviceLBName: "pip1", @@ -1120,12 +1120,12 @@ func TestServiceOwnsPublicIP(t *testing.T) { { desc: "should be true if the pip with service tag matches the pip name", pip: &network.PublicIPAddress{ - Name: ptr.To("pip1"), + Name: to.Ptr("pip1"), Tags: map[string]*string{ - consts.ServiceTagKey: ptr.To("default/web"), + consts.ServiceTagKey: to.Ptr("default/web"), }, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, serviceLBName: "pip1", @@ -1189,26 +1189,26 @@ func TestGetPublicIPAddressResourceGroup(t *testing.T) { func TestShouldReleaseExistingOwnedPublicIP(t *testing.T) { existingPipWithTag := network.PublicIPAddress{ - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP"), - Name: ptr.To("testPIP"), + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP"), + Name: to.Ptr("testPIP"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv4, PublicIPAllocationMethod: network.Static, IPTags: &[]network.IPTag{ { - IPTagType: ptr.To("tag1"), - Tag: ptr.To("tag1value"), + IPTagType: to.Ptr("tag1"), + Tag: to.Ptr("tag1value"), }, }, }, } existingPipWithTagIPv6Suffix := existingPipWithTag - existingPipWithTagIPv6Suffix.Name = ptr.To("testPIP-IPv6") + existingPipWithTagIPv6Suffix.Name = to.Ptr("testPIP-IPv6") existingPipWithNoPublicIPAddressFormatProperties := network.PublicIPAddress{ - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP"), - Name: ptr.To("testPIP"), - Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test2")}, + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP"), + Name: to.Ptr("testPIP"), + Tags: map[string]*string{consts.ServiceTagKey: to.Ptr("default/test2")}, PublicIPAddressPropertiesFormat: nil, } @@ -1305,8 +1305,8 @@ func TestShouldReleaseExistingOwnedPublicIP(t *testing.T) { IPTagsRequestedByAnnotation: true, IPTags: &[]network.IPTag{ { - IPTagType: ptr.To("tag2"), - Tag: ptr.To("tag2value"), + IPTagType: to.Ptr("tag2"), + Tag: to.Ptr("tag2value"), }, }, }, @@ -1324,8 +1324,8 @@ func TestShouldReleaseExistingOwnedPublicIP(t *testing.T) { IPTagsRequestedByAnnotation: true, IPTags: &[]network.IPTag{ { - IPTagType: ptr.To("tag1"), - Tag: ptr.To("tag1value"), + IPTagType: to.Ptr("tag1"), + Tag: to.Ptr("tag1value"), }, }, }, @@ -1477,8 +1477,8 @@ func TestConvertIPTagMapToSlice(t *testing.T) { }, expected: &[]network.IPTag{ { - IPTagType: ptr.To("tag1"), - Tag: ptr.To("tag1value"), + IPTagType: to.Ptr("tag1"), + Tag: to.Ptr("tag1value"), }, }, }, @@ -1490,12 +1490,12 @@ func TestConvertIPTagMapToSlice(t *testing.T) { }, expected: &[]network.IPTag{ { - IPTagType: ptr.To("tag1"), - Tag: ptr.To("tag1value"), + IPTagType: to.Ptr("tag1"), + Tag: to.Ptr("tag1value"), }, { - IPTagType: ptr.To("tag2"), - Tag: ptr.To("tag2value"), + IPTagType: to.Ptr("tag2"), + Tag: to.Ptr("tag2value"), }, }, }, @@ -1509,13 +1509,13 @@ func TestConvertIPTagMapToSlice(t *testing.T) { if actual != nil { sort.Slice(*actual, func(i, j int) bool { ipTagSlice := *actual - return ptr.Deref(ipTagSlice[i].IPTagType, "") < ptr.Deref(ipTagSlice[j].IPTagType, "") + return lo.FromPtrOr(ipTagSlice[i].IPTagType, "") < lo.FromPtrOr(ipTagSlice[j].IPTagType, "") }) } if c.expected != nil { sort.Slice(*c.expected, func(i, j int) bool { ipTagSlice := *c.expected - return ptr.Deref(ipTagSlice[i].IPTagType, "") < ptr.Deref(ipTagSlice[j].IPTagType, "") + return lo.FromPtrOr(ipTagSlice[i].IPTagType, "") < lo.FromPtrOr(ipTagSlice[j].IPTagType, "") }) } @@ -1576,12 +1576,12 @@ func TestGetserviceIPTagRequestForPublicIP(t *testing.T) { IPTagsRequestedByAnnotation: true, IPTags: &[]network.IPTag{ { - IPTagType: ptr.To("tag1"), - Tag: ptr.To("tag1value"), + IPTagType: to.Ptr("tag1"), + Tag: to.Ptr("tag1value"), }, { - IPTagType: ptr.To("tag2"), - Tag: ptr.To("tag2value"), + IPTagType: to.Ptr("tag2"), + Tag: to.Ptr("tag2value"), }, }, }, @@ -1595,13 +1595,13 @@ func TestGetserviceIPTagRequestForPublicIP(t *testing.T) { if actual.IPTags != nil { sort.Slice(*actual.IPTags, func(i, j int) bool { ipTagSlice := *actual.IPTags - return ptr.Deref(ipTagSlice[i].IPTagType, "") < ptr.Deref(ipTagSlice[j].IPTagType, "") + return lo.FromPtrOr(ipTagSlice[i].IPTagType, "") < lo.FromPtrOr(ipTagSlice[j].IPTagType, "") }) } if c.expected.IPTags != nil { sort.Slice(*c.expected.IPTags, func(i, j int) bool { ipTagSlice := *c.expected.IPTags - return ptr.Deref(ipTagSlice[i].IPTagType, "") < ptr.Deref(ipTagSlice[j].IPTagType, "") + return lo.FromPtrOr(ipTagSlice[i].IPTagType, "") < lo.FromPtrOr(ipTagSlice[j].IPTagType, "") }) } @@ -1638,12 +1638,12 @@ func TestAreIpTagsEquivalent(t *testing.T) { desc: "nil should not be considered equal to anything (case 1)", input1: &[]network.IPTag{ { - IPTagType: ptr.To("tag1"), - Tag: ptr.To("tag1value"), + IPTagType: to.Ptr("tag1"), + Tag: to.Ptr("tag1value"), }, { - IPTagType: ptr.To("tag2"), - Tag: ptr.To("tag2value"), + IPTagType: to.Ptr("tag2"), + Tag: to.Ptr("tag2value"), }, }, input2: nil, @@ -1653,12 +1653,12 @@ func TestAreIpTagsEquivalent(t *testing.T) { desc: "nil should not be considered equal to anything (case 2)", input2: &[]network.IPTag{ { - IPTagType: ptr.To("tag1"), - Tag: ptr.To("tag1value"), + IPTagType: to.Ptr("tag1"), + Tag: to.Ptr("tag1value"), }, { - IPTagType: ptr.To("tag2"), - Tag: ptr.To("tag2value"), + IPTagType: to.Ptr("tag2"), + Tag: to.Ptr("tag2value"), }, }, input1: nil, @@ -1668,22 +1668,22 @@ func TestAreIpTagsEquivalent(t *testing.T) { desc: "exactly equal should be treated as equal", input1: &[]network.IPTag{ { - IPTagType: ptr.To("tag1"), - Tag: ptr.To("tag1value"), + IPTagType: to.Ptr("tag1"), + Tag: to.Ptr("tag1value"), }, { - IPTagType: ptr.To("tag2"), - Tag: ptr.To("tag2value"), + IPTagType: to.Ptr("tag2"), + Tag: to.Ptr("tag2value"), }, }, input2: &[]network.IPTag{ { - IPTagType: ptr.To("tag1"), - Tag: ptr.To("tag1value"), + IPTagType: to.Ptr("tag1"), + Tag: to.Ptr("tag1value"), }, { - IPTagType: ptr.To("tag2"), - Tag: ptr.To("tag2value"), + IPTagType: to.Ptr("tag2"), + Tag: to.Ptr("tag2value"), }, }, expected: true, @@ -1692,22 +1692,22 @@ func TestAreIpTagsEquivalent(t *testing.T) { desc: "equal but out of order should be treated as equal", input1: &[]network.IPTag{ { - IPTagType: ptr.To("tag1"), - Tag: ptr.To("tag1value"), + IPTagType: to.Ptr("tag1"), + Tag: to.Ptr("tag1value"), }, { - IPTagType: ptr.To("tag2"), - Tag: ptr.To("tag2value"), + IPTagType: to.Ptr("tag2"), + Tag: to.Ptr("tag2value"), }, }, input2: &[]network.IPTag{ { - IPTagType: ptr.To("tag2"), - Tag: ptr.To("tag2value"), + IPTagType: to.Ptr("tag2"), + Tag: to.Ptr("tag2value"), }, { - IPTagType: ptr.To("tag1"), - Tag: ptr.To("tag1value"), + IPTagType: to.Ptr("tag1"), + Tag: to.Ptr("tag1value"), }, }, expected: true, @@ -1739,21 +1739,21 @@ func TestGetServiceLoadBalancerMultiSLB(t *testing.T) { description: "should return the existing lb if the service is moved to the lb", existingLBs: []network.LoadBalancer{ { - Name: ptr.To("lb1-internal"), + Name: to.Ptr("lb1-internal"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ FrontendIPConfigurations: &[]network.FrontendIPConfiguration{ { - Name: ptr.To("atest1"), - ID: ptr.To("atest1"), + Name: to.Ptr("atest1"), + ID: to.Ptr("atest1"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PrivateIPAddress: ptr.To("1.2.3.4"), + PrivateIPAddress: to.Ptr("1.2.3.4"), }, }, }, }, }, { - Name: ptr.To("lb2-internal"), + Name: to.Ptr("lb2-internal"), }, }, service: getInternalTestService("test1"), @@ -1769,36 +1769,36 @@ func TestGetServiceLoadBalancerMultiSLB(t *testing.T) { }, }, expectedLB: &network.LoadBalancer{ - Name: ptr.To("lb2-internal"), + Name: to.Ptr("lb2-internal"), }, expectedLBs: &[]network.LoadBalancer{ - {Name: ptr.To("lb2-internal")}, + {Name: to.Ptr("lb2-internal")}, }, }, { description: "remove backend pool when a local service changes its load balancer", existingLBs: []network.LoadBalancer{ { - Name: ptr.To("lb1"), + Name: to.Ptr("lb1"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ FrontendIPConfigurations: &[]network.FrontendIPConfiguration{ { - Name: ptr.To("atest1"), - ID: ptr.To("atest1"), + Name: to.Ptr("atest1"), + ID: to.Ptr("atest1"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("pip")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("pip")}, }, }, { - Name: ptr.To("atest2"), + Name: to.Ptr("atest2"), }, }, BackendAddressPools: &[]network.BackendAddressPool{ { - Name: ptr.To("kubernetes"), + Name: to.Ptr("kubernetes"), }, { - Name: ptr.To("default-test1"), + Name: to.Ptr("default-test1"), }, }, }, @@ -1806,23 +1806,23 @@ func TestGetServiceLoadBalancerMultiSLB(t *testing.T) { }, refreshedLBs: []network.LoadBalancer{ { - Name: ptr.To("lb1"), + Name: to.Ptr("lb1"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ FrontendIPConfigurations: &[]network.FrontendIPConfiguration{ { - Name: ptr.To("atest1"), - ID: ptr.To("atest1"), + Name: to.Ptr("atest1"), + ID: to.Ptr("atest1"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("pip")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("pip")}, }, }, { - Name: ptr.To("atest2"), + Name: to.Ptr("atest2"), }, }, BackendAddressPools: &[]network.BackendAddressPool{ { - Name: ptr.To("kubernetes"), + Name: to.Ptr("kubernetes"), }, }, }, @@ -1830,9 +1830,9 @@ func TestGetServiceLoadBalancerMultiSLB(t *testing.T) { }, existingPIPs: []network.PublicIPAddress{ { - Name: ptr.To("pip"), + Name: to.Ptr("pip"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, }, @@ -1850,8 +1850,8 @@ func TestGetServiceLoadBalancerMultiSLB(t *testing.T) { }, }, expectedLB: &network.LoadBalancer{ - Name: ptr.To("lb2"), - Location: ptr.To("westus"), + Name: to.Ptr("lb2"), + Location: to.Ptr("westus"), Sku: &network.LoadBalancerSku{ Name: network.LoadBalancerSkuNameStandard, }, @@ -1859,23 +1859,23 @@ func TestGetServiceLoadBalancerMultiSLB(t *testing.T) { }, expectedLBs: &[]network.LoadBalancer{ { - Name: ptr.To("lb1"), + Name: to.Ptr("lb1"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ FrontendIPConfigurations: &[]network.FrontendIPConfiguration{ { - Name: ptr.To("atest1"), - ID: ptr.To("atest1"), + Name: to.Ptr("atest1"), + ID: to.Ptr("atest1"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("pip")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("pip")}, }, }, { - Name: ptr.To("atest2"), + Name: to.Ptr("atest2"), }, }, BackendAddressPools: &[]network.BackendAddressPool{ { - Name: ptr.To("kubernetes"), + Name: to.Ptr("kubernetes"), }, }, }, @@ -1932,13 +1932,13 @@ func TestGetServiceLoadBalancerCommon(t *testing.T) { desc: "getServiceLoadBalancer shall return corresponding lb, status, exists if there are existed lbs", existingLBs: []network.LoadBalancer{ { - Name: ptr.To("testCluster"), + Name: to.Ptr("testCluster"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ FrontendIPConfigurations: &[]network.FrontendIPConfiguration{ { - Name: ptr.To("aservice1"), + Name: to.Ptr("aservice1"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-aservice1")}, }, }, }, @@ -1948,13 +1948,13 @@ func TestGetServiceLoadBalancerCommon(t *testing.T) { service: getTestService("service1", v1.ProtocolTCP, nil, false, 80), wantLB: false, expectedLB: &network.LoadBalancer{ - Name: ptr.To("testCluster"), + Name: to.Ptr("testCluster"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ FrontendIPConfigurations: &[]network.FrontendIPConfiguration{ { - Name: ptr.To("aservice1"), + Name: to.Ptr("aservice1"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-aservice1")}, }, }, }, @@ -1969,29 +1969,29 @@ func TestGetServiceLoadBalancerCommon(t *testing.T) { "not standard and there are existing lbs already", existingLBs: []network.LoadBalancer{ { - Name: ptr.To("testCluster"), + Name: to.Ptr("testCluster"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ LoadBalancingRules: &[]network.LoadBalancingRule{ - {Name: ptr.To("rule1")}, + {Name: to.Ptr("rule1")}, }, }, }, { - Name: ptr.To("as-1"), + Name: to.Ptr("as-1"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ LoadBalancingRules: &[]network.LoadBalancingRule{ - {Name: ptr.To("rule1")}, - {Name: ptr.To("rule2")}, + {Name: to.Ptr("rule1")}, + {Name: to.Ptr("rule2")}, }, }, }, { - Name: ptr.To("as-2"), + Name: to.Ptr("as-2"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ LoadBalancingRules: &[]network.LoadBalancingRule{ - {Name: ptr.To("rule1")}, - {Name: ptr.To("rule2")}, - {Name: ptr.To("rule3")}, + {Name: to.Ptr("rule1")}, + {Name: to.Ptr("rule2")}, + {Name: to.Ptr("rule3")}, }, }, }, @@ -2000,10 +2000,10 @@ func TestGetServiceLoadBalancerCommon(t *testing.T) { annotations: map[string]string{consts.ServiceAnnotationLoadBalancerMode: "__auto__"}, wantLB: true, expectedLB: &network.LoadBalancer{ - Name: ptr.To("testCluster"), + Name: to.Ptr("testCluster"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ LoadBalancingRules: &[]network.LoadBalancingRule{ - {Name: ptr.To("rule1")}, + {Name: to.Ptr("rule1")}, }, }, }, @@ -2014,8 +2014,8 @@ func TestGetServiceLoadBalancerCommon(t *testing.T) { desc: "getServiceLoadBalancer shall create a new lb otherwise", service: getTestService("service1", v1.ProtocolTCP, nil, false, 80), expectedLB: &network.LoadBalancer{ - Name: ptr.To("testCluster"), - Location: ptr.To("westus"), + Name: to.Ptr("testCluster"), + Location: to.Ptr("westus"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{}, }, expectedExists: false, @@ -2067,10 +2067,10 @@ func TestGetServiceLoadBalancerWithExtendedLocation(t *testing.T) { // Test with wantLB=false expectedLB := &network.LoadBalancer{ - Name: ptr.To("testCluster"), - Location: ptr.To("westus"), + Name: to.Ptr("testCluster"), + Location: to.Ptr("westus"), ExtendedLocation: &network.ExtendedLocation{ - Name: ptr.To("microsoftlosangeles1"), + Name: to.Ptr("microsoftlosangeles1"), Type: network.EdgeZone, }, LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{}, @@ -2088,10 +2088,10 @@ func TestGetServiceLoadBalancerWithExtendedLocation(t *testing.T) { // Test with wantLB=true expectedLB = &network.LoadBalancer{ - Name: ptr.To("testCluster"), - Location: ptr.To("westus"), + Name: to.Ptr("testCluster"), + Location: to.Ptr("westus"), ExtendedLocation: &network.ExtendedLocation{ - Name: ptr.To("microsoftlosangeles1"), + Name: to.Ptr("microsoftlosangeles1"), Type: network.EdgeZone, }, LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{}, @@ -2131,7 +2131,7 @@ func TestIsFrontendIPChanged(t *testing.T) { { desc: "isFrontendIPChanged shall return true if config.Name has a prefix of lb's name and " + "config.Name != lbFrontendIPConfigName", - config: network.FrontendIPConfiguration{Name: ptr.To("atest1-name")}, + config: network.FrontendIPConfiguration{Name: to.Ptr("atest1-name")}, service: getInternalTestService("test1", 80), lbFrontendIPConfigName: "configName", expectedFlag: true, @@ -2140,7 +2140,7 @@ func TestIsFrontendIPChanged(t *testing.T) { { desc: "isFrontendIPChanged shall return false if config.Name doesn't have a prefix of lb's name " + "and config.Name != lbFrontendIPConfigName", - config: network.FrontendIPConfiguration{Name: ptr.To("btest1-name")}, + config: network.FrontendIPConfiguration{Name: to.Ptr("btest1-name")}, service: getInternalTestService("test1", 80), lbFrontendIPConfigName: "configName", expectedFlag: false, @@ -2150,7 +2150,7 @@ func TestIsFrontendIPChanged(t *testing.T) { desc: "isFrontendIPChanged shall return false if the service is internal, no loadBalancerIP is given, " + "subnetName == nil and config.PrivateIPAllocationMethod == network.Static", config: network.FrontendIPConfiguration{ - Name: ptr.To("btest1-name"), + Name: to.Ptr("btest1-name"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PrivateIPAllocationMethod: network.Static, }, @@ -2164,7 +2164,7 @@ func TestIsFrontendIPChanged(t *testing.T) { desc: "isFrontendIPChanged shall return false if the service is internal, no loadBalancerIP is given, " + "subnetName == nil and config.PrivateIPAllocationMethod != network.Static", config: network.FrontendIPConfiguration{ - Name: ptr.To("btest1-name"), + Name: to.Ptr("btest1-name"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PrivateIPAllocationMethod: network.Dynamic, }, @@ -2178,15 +2178,15 @@ func TestIsFrontendIPChanged(t *testing.T) { desc: "isFrontendIPChanged shall return true if the service is internal and " + "config.Subnet.ID != subnet.ID", config: network.FrontendIPConfiguration{ - Name: ptr.To("btest1-name"), + Name: to.Ptr("btest1-name"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - Subnet: &network.Subnet{ID: ptr.To("testSubnet")}, + Subnet: &network.Subnet{ID: to.Ptr("testSubnet")}, }, }, lbFrontendIPConfigName: "btest1-name", service: getInternalTestService("test1", 80), annotations: "testSubnet", - existingSubnet: network.Subnet{ID: ptr.To("testSubnet1")}, + existingSubnet: network.Subnet{ID: to.Ptr("testSubnet1")}, expectedFlag: true, expectedError: false, }, @@ -2194,10 +2194,10 @@ func TestIsFrontendIPChanged(t *testing.T) { desc: "isFrontendIPChanged shall return false if the service is internal, subnet == nil, " + "loadBalancerIP == config.PrivateIPAddress and config.PrivateIPAllocationMethod != 'static'", config: network.FrontendIPConfiguration{ - Name: ptr.To("btest1-name"), + Name: to.Ptr("btest1-name"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PrivateIPAllocationMethod: network.Dynamic, - PrivateIPAddress: ptr.To("1.1.1.1"), + PrivateIPAddress: to.Ptr("1.1.1.1"), }, }, lbFrontendIPConfigName: "btest1-name", @@ -2210,10 +2210,10 @@ func TestIsFrontendIPChanged(t *testing.T) { desc: "isFrontendIPChanged shall return false if the service is internal, subnet == nil, " + "loadBalancerIP == config.PrivateIPAddress and config.PrivateIPAllocationMethod == 'static'", config: network.FrontendIPConfiguration{ - Name: ptr.To("btest1-name"), + Name: to.Ptr("btest1-name"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PrivateIPAllocationMethod: network.Static, - PrivateIPAddress: ptr.To("1.1.1.1"), + PrivateIPAddress: to.Ptr("1.1.1.1"), }, }, lbFrontendIPConfigName: "btest1-name", @@ -2226,10 +2226,10 @@ func TestIsFrontendIPChanged(t *testing.T) { desc: "isFrontendIPChanged shall return true if the service is internal, subnet == nil and " + "loadBalancerIP != config.PrivateIPAddress", config: network.FrontendIPConfiguration{ - Name: ptr.To("btest1-name"), + Name: to.Ptr("btest1-name"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PrivateIPAllocationMethod: network.Static, - PrivateIPAddress: ptr.To("1.1.1.2"), + PrivateIPAddress: to.Ptr("1.1.1.2"), }, }, lbFrontendIPConfigName: "btest1-name", @@ -2241,7 +2241,7 @@ func TestIsFrontendIPChanged(t *testing.T) { { desc: "isFrontendIPChanged shall return false if config.PublicIPAddress == nil", config: network.FrontendIPConfiguration{ - Name: ptr.To("btest1-name"), + Name: to.Ptr("btest1-name"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{}, }, lbFrontendIPConfigName: "btest1-name", @@ -2249,10 +2249,10 @@ func TestIsFrontendIPChanged(t *testing.T) { loadBalancerIP: "1.1.1.1", existingPIPs: []network.PublicIPAddress{ { - Name: ptr.To("pipName"), - ID: ptr.To("pip"), + Name: to.Ptr("pipName"), + ID: to.Ptr("pip"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("1.1.1.1"), + IPAddress: to.Ptr("1.1.1.1"), }, }, }, @@ -2262,9 +2262,9 @@ func TestIsFrontendIPChanged(t *testing.T) { { desc: "isFrontendIPChanged shall return false if pip.ID == config.PublicIPAddress.ID", config: network.FrontendIPConfiguration{ - Name: ptr.To("btest1-name"), + Name: to.Ptr("btest1-name"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("/subscriptions/subscription" + + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("/subscriptions/subscription" + "/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/pipName")}, }, }, @@ -2273,11 +2273,11 @@ func TestIsFrontendIPChanged(t *testing.T) { loadBalancerIP: "1.1.1.1", existingPIPs: []network.PublicIPAddress{ { - Name: ptr.To("pipName"), + Name: to.Ptr("pipName"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("1.1.1.1"), + IPAddress: to.Ptr("1.1.1.1"), }, - ID: ptr.To("/subscriptions/subscription" + + ID: to.Ptr("/subscriptions/subscription" + "/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/pipName"), }, }, @@ -2287,10 +2287,10 @@ func TestIsFrontendIPChanged(t *testing.T) { { desc: "isFrontendIPChanged shall return true if pip.ID != config.PublicIPAddress.ID", config: network.FrontendIPConfiguration{ - Name: ptr.To("btest1-name"), + Name: to.Ptr("btest1-name"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PublicIPAddress: &network.PublicIPAddress{ - ID: ptr.To("/subscriptions/subscription" + + ID: to.Ptr("/subscriptions/subscription" + "/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/pipName1"), }, }, @@ -2300,11 +2300,11 @@ func TestIsFrontendIPChanged(t *testing.T) { loadBalancerIP: "1.1.1.1", existingPIPs: []network.PublicIPAddress{ { - Name: ptr.To("pipName"), - ID: ptr.To("/subscriptions/subscription" + + Name: to.Ptr("pipName"), + ID: to.Ptr("/subscriptions/subscription" + "/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/pipName2"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("1.1.1.1"), + IPAddress: to.Ptr("1.1.1.1"), }, }, }, @@ -2378,9 +2378,9 @@ func TestDeterminePublicIPName(t *testing.T) { loadBalancerIP: "1.2.3.4", existingPIPs: []network.PublicIPAddress{ { - Name: ptr.To("pipName"), + Name: to.Ptr("pipName"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, }, @@ -2486,7 +2486,7 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { loadBalancerSku: "standard", expectedProbes: map[bool][]network.Probe{ // Use false as IPv6 param but it is a IPv6 probe. - true: {getTestProbe("Tcp", "", ptr.To(int32(5)), ptr.To(int32(80)), ptr.To(int32(10080)), ptr.To(int32(2)), false)}, + true: {getTestProbe("Tcp", "", to.Ptr(int32(5)), to.Ptr(int32(80)), to.Ptr(int32(10080)), to.Ptr(int32(2)), false)}, }, expectedRules: getDefaultInternalIPv6Rules(true), }, @@ -2638,7 +2638,7 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { loadBalancerSku: "standard", probeProtocol: "Https", probePath: "/healthy1", - expectedProbes: getTestProbes("Https", "/healthy1", ptr.To(int32(20)), ptr.To(int32(80)), ptr.To(int32(10080)), ptr.To(int32(5))), + expectedProbes: getTestProbes("Https", "/healthy1", to.Ptr(int32(20)), to.Ptr(int32(80)), to.Ptr(int32(10080)), to.Ptr(int32(5))), expectedRules: getDefaultTestRules(true), }, { @@ -2649,7 +2649,7 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { }, 80), loadBalancerSku: "standard", probeProtocol: "Http", - expectedProbes: getTestProbes("Http", "/", ptr.To(int32(20)), ptr.To(int32(80)), ptr.To(int32(10080)), ptr.To(int32(5))), + expectedProbes: getTestProbes("Http", "/", to.Ptr(int32(20)), to.Ptr(int32(80)), to.Ptr(int32(10080)), to.Ptr(int32(5))), expectedRules: getDefaultTestRules(true), }, { @@ -2660,7 +2660,7 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { }, 80), loadBalancerSku: "standard", probeProtocol: "Tcp", - expectedProbes: getTestProbes("Tcp", "", ptr.To(int32(20)), ptr.To(int32(80)), ptr.To(int32(10080)), ptr.To(int32(5))), + expectedProbes: getTestProbes("Tcp", "", to.Ptr(int32(20)), to.Ptr(int32(80)), to.Ptr(int32(10080)), to.Ptr(int32(5))), expectedRules: getDefaultTestRules(true), }, { @@ -2770,12 +2770,12 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { }, expectedProbes: map[bool][]network.Probe{ consts.IPVersionIPv4: { - getTestProbe("Tcp", "/", ptr.To(int32(5)), ptr.To(int32(80)), ptr.To(int32(10080)), ptr.To(int32(2)), consts.IPVersionIPv4), - getTestProbe("Tcp", "/", ptr.To(int32(5)), ptr.To(int32(8000)), ptr.To(int32(10080)), ptr.To(int32(2)), consts.IPVersionIPv4), + getTestProbe("Tcp", "/", to.Ptr(int32(5)), to.Ptr(int32(80)), to.Ptr(int32(10080)), to.Ptr(int32(2)), consts.IPVersionIPv4), + getTestProbe("Tcp", "/", to.Ptr(int32(5)), to.Ptr(int32(8000)), to.Ptr(int32(10080)), to.Ptr(int32(2)), consts.IPVersionIPv4), }, consts.IPVersionIPv6: { - getTestProbe("Tcp", "/", ptr.To(int32(5)), ptr.To(int32(80)), ptr.To(int32(10080)), ptr.To(int32(2)), consts.IPVersionIPv6), - getTestProbe("Tcp", "/", ptr.To(int32(5)), ptr.To(int32(8000)), ptr.To(int32(10080)), ptr.To(int32(2)), consts.IPVersionIPv6), + getTestProbe("Tcp", "/", to.Ptr(int32(5)), to.Ptr(int32(80)), to.Ptr(int32(10080)), to.Ptr(int32(2)), consts.IPVersionIPv6), + getTestProbe("Tcp", "/", to.Ptr(int32(5)), to.Ptr(int32(8000)), to.Ptr(int32(10080)), to.Ptr(int32(2)), consts.IPVersionIPv6), }, }, }, @@ -2796,12 +2796,12 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { }, expectedProbes: map[bool][]network.Probe{ consts.IPVersionIPv4: { - getTestProbe("Tcp", "/", ptr.To(int32(5)), ptr.To(int32(80)), ptr.To(int32(10080)), ptr.To(int32(2)), consts.IPVersionIPv4), - getTestProbe("Tcp", "/", ptr.To(int32(5)), ptr.To(int32(8000)), ptr.To(int32(10080)), ptr.To(int32(2)), consts.IPVersionIPv4), + getTestProbe("Tcp", "/", to.Ptr(int32(5)), to.Ptr(int32(80)), to.Ptr(int32(10080)), to.Ptr(int32(2)), consts.IPVersionIPv4), + getTestProbe("Tcp", "/", to.Ptr(int32(5)), to.Ptr(int32(8000)), to.Ptr(int32(10080)), to.Ptr(int32(2)), consts.IPVersionIPv4), }, consts.IPVersionIPv6: { - getTestProbe("Tcp", "/", ptr.To(int32(5)), ptr.To(int32(80)), ptr.To(int32(10080)), ptr.To(int32(2)), consts.IPVersionIPv6), - getTestProbe("Tcp", "/", ptr.To(int32(5)), ptr.To(int32(8000)), ptr.To(int32(10080)), ptr.To(int32(2)), consts.IPVersionIPv6), + getTestProbe("Tcp", "/", to.Ptr(int32(5)), to.Ptr(int32(80)), to.Ptr(int32(10080)), to.Ptr(int32(2)), consts.IPVersionIPv6), + getTestProbe("Tcp", "/", to.Ptr(int32(5)), to.Ptr(int32(8000)), to.Ptr(int32(10080)), to.Ptr(int32(2)), consts.IPVersionIPv6), }, }, }, @@ -2830,10 +2830,10 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { }, expectedProbes: map[bool][]network.Probe{ consts.IPVersionIPv4: { - getTestProbe("Tcp", "/", ptr.To(int32(5)), ptr.To(int32(80)), ptr.To(int32(10080)), ptr.To(int32(2)), consts.IPVersionIPv4), + getTestProbe("Tcp", "/", to.Ptr(int32(5)), to.Ptr(int32(80)), to.Ptr(int32(10080)), to.Ptr(int32(2)), consts.IPVersionIPv4), }, consts.IPVersionIPv6: { - getTestProbe("Tcp", "/", ptr.To(int32(5)), ptr.To(int32(80)), ptr.To(int32(10080)), ptr.To(int32(2)), consts.IPVersionIPv6), + getTestProbe("Tcp", "/", to.Ptr(int32(5)), to.Ptr(int32(80)), to.Ptr(int32(10080)), to.Ptr(int32(2)), consts.IPVersionIPv6), }, }, }, @@ -2852,10 +2852,10 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { }, expectedProbes: map[bool][]network.Probe{ consts.IPVersionIPv4: { - getTestProbe("Tcp", "/", ptr.To(int32(5)), ptr.To(int32(80)), ptr.To(int32(10080)), ptr.To(int32(2)), consts.IPVersionIPv4), + getTestProbe("Tcp", "/", to.Ptr(int32(5)), to.Ptr(int32(80)), to.Ptr(int32(10080)), to.Ptr(int32(2)), consts.IPVersionIPv4), }, consts.IPVersionIPv6: { - getTestProbe("Tcp", "/", ptr.To(int32(5)), ptr.To(int32(80)), ptr.To(int32(10080)), ptr.To(int32(2)), consts.IPVersionIPv6), + getTestProbe("Tcp", "/", to.Ptr(int32(5)), to.Ptr(int32(80)), to.Ptr(int32(10080)), to.Ptr(int32(2)), consts.IPVersionIPv6), }, }, }, @@ -2876,12 +2876,12 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { }, expectedProbes: map[bool][]network.Probe{ consts.IPVersionIPv4: { - getTestProbe("Tcp", "/", ptr.To(int32(5)), ptr.To(int32(80)), ptr.To(int32(10080)), ptr.To(int32(2)), consts.IPVersionIPv4), - getTestProbe("Tcp", "/", ptr.To(int32(5)), ptr.To(int32(8000)), ptr.To(int32(5080)), ptr.To(int32(2)), consts.IPVersionIPv4), + getTestProbe("Tcp", "/", to.Ptr(int32(5)), to.Ptr(int32(80)), to.Ptr(int32(10080)), to.Ptr(int32(2)), consts.IPVersionIPv4), + getTestProbe("Tcp", "/", to.Ptr(int32(5)), to.Ptr(int32(8000)), to.Ptr(int32(5080)), to.Ptr(int32(2)), consts.IPVersionIPv4), }, consts.IPVersionIPv6: { - getTestProbe("Tcp", "/", ptr.To(int32(5)), ptr.To(int32(80)), ptr.To(int32(10080)), ptr.To(int32(2)), consts.IPVersionIPv6), - getTestProbe("Tcp", "/", ptr.To(int32(5)), ptr.To(int32(8000)), ptr.To(int32(5080)), ptr.To(int32(2)), consts.IPVersionIPv6), + getTestProbe("Tcp", "/", to.Ptr(int32(5)), to.Ptr(int32(80)), to.Ptr(int32(10080)), to.Ptr(int32(2)), consts.IPVersionIPv6), + getTestProbe("Tcp", "/", to.Ptr(int32(5)), to.Ptr(int32(8000)), to.Ptr(int32(5080)), to.Ptr(int32(2)), consts.IPVersionIPv6), }, }, }, @@ -2889,7 +2889,7 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { rulesDualStack := getDefaultTestRules(true) for _, rules := range rulesDualStack { for _, rule := range rules { - rule.IdleTimeoutInMinutes = ptr.To(int32(5)) + rule.IdleTimeoutInMinutes = to.Ptr(int32(5)) } } testCases = append(testCases, struct { @@ -2910,7 +2910,7 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { }, 80), loadBalancerSku: "standard", probeProtocol: "Tcp", - expectedProbes: getTestProbes("Tcp", "", ptr.To(int32(10)), ptr.To(int32(80)), ptr.To(int32(10080)), ptr.To(int32(10))), + expectedProbes: getTestProbes("Tcp", "", to.Ptr(int32(10)), to.Ptr(int32(80)), to.Ptr(int32(10080)), to.Ptr(int32(10))), expectedRules: rulesDualStack, }) rules1DualStack := map[bool][]network.LoadBalancingRule{ @@ -2926,10 +2926,10 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { }, } for _, rule := range rules1DualStack[consts.IPVersionIPv4] { - rule.Probe.ID = ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lbname/probes/atest1-TCP-34567") + rule.Probe.ID = to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lbname/probes/atest1-TCP-34567") } for _, rule := range rules1DualStack[consts.IPVersionIPv6] { - rule.Probe.ID = ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lbname/probes/atest1-TCP-34567-IPv6") + rule.Probe.ID = to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lbname/probes/atest1-TCP-34567-IPv6") } // When the service spec externalTrafficPolicy is Local all of these annotations should be ignored @@ -2943,7 +2943,7 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { }, 80, 443, 421) svc.Spec.ExternalTrafficPolicy = v1.ServiceExternalTrafficPolicyTypeLocal svc.Spec.HealthCheckNodePort = 34567 - probes := getTestProbes("Http", "/healthz", ptr.To(int32(5)), ptr.To(int32(34567)), ptr.To(int32(34567)), ptr.To(int32(2))) + probes := getTestProbes("Http", "/healthz", to.Ptr(int32(5)), to.Ptr(int32(34567)), to.Ptr(int32(34567)), to.Ptr(int32(2))) testCases = append(testCases, struct { desc string service v1.Service @@ -2982,7 +2982,7 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { }, 80) svc.Spec.ExternalTrafficPolicy = v1.ServiceExternalTrafficPolicyTypeLocal svc.Spec.HealthCheckNodePort = 34567 - probes = getTestProbes("Https", "/broken/local/path", ptr.To(int32(7)), ptr.To(int32(80)), ptr.To(int32(10080)), ptr.To(int32(15))) + probes = getTestProbes("Https", "/broken/local/path", to.Ptr(int32(7)), to.Ptr(int32(80)), to.Ptr(int32(10080)), to.Ptr(int32(15))) testCases = append(testCases, struct { desc string service v1.Service @@ -3014,7 +3014,7 @@ func TestReconcileLoadBalancerRuleCommon(t *testing.T) { }, 80) svc.Spec.ExternalTrafficPolicy = v1.ServiceExternalTrafficPolicyTypeLocal svc.Spec.HealthCheckNodePort = 34567 - probes = getTestProbes("Https", "/broken/local/path", ptr.To(int32(7)), ptr.To(int32(80)), ptr.To(int32(421)), ptr.To(int32(15))) + probes = getTestProbes("Https", "/broken/local/path", to.Ptr(int32(7)), to.Ptr(int32(80)), to.Ptr(int32(421)), to.Ptr(int32(15))) testCases = append(testCases, struct { desc string service v1.Service @@ -3115,9 +3115,9 @@ func getDefaultTestRules(enableTCPReset bool) map[bool][]network.LoadBalancingRu // getDefaultInternalIPv6Rules returns a rule for IPv6 single stack. func getDefaultInternalIPv6Rules(enableTCPReset bool) map[bool][]network.LoadBalancingRule { rule := getTestRule(enableTCPReset, 80, false) - rule.EnableFloatingIP = ptr.To(false) - rule.BackendPort = ptr.To(getBackendPort(*rule.FrontendPort)) - rule.BackendAddressPool.ID = ptr.To("backendPoolID-IPv6") + rule.EnableFloatingIP = to.Ptr(false) + rule.BackendPort = to.Ptr(getBackendPort(*rule.FrontendPort)) + rule.BackendAddressPool.ID = to.Ptr("backendPoolID-IPv6") return map[bool][]network.LoadBalancingRule{ true: {rule}, } @@ -3127,8 +3127,8 @@ func getDefaultInternalIPv6Rules(enableTCPReset bool) map[bool][]network.LoadBal func getTCPResetTestRules(enableTCPReset bool) map[bool][]network.LoadBalancingRule { IPv4Rule := getTestRule(enableTCPReset, 80, consts.IPVersionIPv4) IPv6Rule := getTestRule(enableTCPReset, 80, consts.IPVersionIPv6) - IPv4Rule.EnableTCPReset = ptr.To(enableTCPReset) - IPv6Rule.EnableTCPReset = ptr.To(enableTCPReset) + IPv4Rule.EnableTCPReset = to.Ptr(enableTCPReset) + IPv6Rule.EnableTCPReset = to.Ptr(enableTCPReset) return map[bool][]network.LoadBalancingRule{ consts.IPVersionIPv4: {IPv4Rule}, consts.IPVersionIPv6: {IPv6Rule}, @@ -3142,29 +3142,29 @@ func getTestRule(enableTCPReset bool, port int32, isIPv6 bool) network.LoadBalan suffix = "-" + consts.IPVersionIPv6String } expectedRules := network.LoadBalancingRule{ - Name: ptr.To(fmt.Sprintf("atest1-TCP-%d", port) + suffix), + Name: to.Ptr(fmt.Sprintf("atest1-TCP-%d", port) + suffix), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ Protocol: network.TransportProtocol("Tcp"), FrontendIPConfiguration: &network.SubResource{ - ID: ptr.To("frontendIPConfigID" + suffix), + ID: to.Ptr("frontendIPConfigID" + suffix), }, BackendAddressPool: &network.SubResource{ - ID: ptr.To("backendPoolID" + suffix), + ID: to.Ptr("backendPoolID" + suffix), }, LoadDistribution: "Default", - FrontendPort: ptr.To(port), - BackendPort: ptr.To(port), - EnableFloatingIP: ptr.To(true), - DisableOutboundSnat: ptr.To(false), - IdleTimeoutInMinutes: ptr.To(int32(4)), + FrontendPort: to.Ptr(port), + BackendPort: to.Ptr(port), + EnableFloatingIP: to.Ptr(true), + DisableOutboundSnat: to.Ptr(false), + IdleTimeoutInMinutes: to.Ptr(int32(4)), Probe: &network.SubResource{ - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/" + + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/" + fmt.Sprintf("Microsoft.Network/loadBalancers/lbname/probes/atest1-TCP-%d%s", port, suffix)), }, }, } if enableTCPReset { - expectedRules.EnableTCPReset = ptr.To(true) + expectedRules.EnableTCPReset = to.Ptr(true) } return expectedRules } @@ -3181,28 +3181,28 @@ func getHATestRules(_, hasProbe bool, protocol v1.Protocol, isIPv6, isInternal b expectedRules := []network.LoadBalancingRule{ { - Name: ptr.To(fmt.Sprintf("atest1-%s-80%s", string(protocol), suffix)), + Name: to.Ptr(fmt.Sprintf("atest1-%s-80%s", string(protocol), suffix)), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ Protocol: network.TransportProtocol("All"), FrontendIPConfiguration: &network.SubResource{ - ID: ptr.To("frontendIPConfigID" + suffix), + ID: to.Ptr("frontendIPConfigID" + suffix), }, BackendAddressPool: &network.SubResource{ - ID: ptr.To("backendPoolID" + suffix), + ID: to.Ptr("backendPoolID" + suffix), }, LoadDistribution: "Default", - FrontendPort: ptr.To(int32(0)), - BackendPort: ptr.To(int32(0)), - EnableFloatingIP: ptr.To(enableFloatingIP), - DisableOutboundSnat: ptr.To(false), - IdleTimeoutInMinutes: ptr.To(int32(4)), - EnableTCPReset: ptr.To(true), + FrontendPort: to.Ptr(int32(0)), + BackendPort: to.Ptr(int32(0)), + EnableFloatingIP: to.Ptr(enableFloatingIP), + DisableOutboundSnat: to.Ptr(false), + IdleTimeoutInMinutes: to.Ptr(int32(4)), + EnableTCPReset: to.Ptr(true), }, }, } if hasProbe { expectedRules[0].Probe = &network.SubResource{ - ID: ptr.To(fmt.Sprintf("/subscriptions/subscription/resourceGroups/rg/providers/"+ + ID: to.Ptr(fmt.Sprintf("/subscriptions/subscription/resourceGroups/rg/providers/"+ "Microsoft.Network/loadBalancers/lbname/probes/atest1-%s-80%s", string(protocol), suffix)), } } @@ -3215,29 +3215,29 @@ func getFloatingIPTestRule(enableTCPReset, enableFloatingIP bool, port int32, is suffix = "-" + consts.IPVersionIPv6String } expectedRules := network.LoadBalancingRule{ - Name: ptr.To(fmt.Sprintf("atest1-TCP-%d%s", port, suffix)), + Name: to.Ptr(fmt.Sprintf("atest1-TCP-%d%s", port, suffix)), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ Protocol: network.TransportProtocol("Tcp"), FrontendIPConfiguration: &network.SubResource{ - ID: ptr.To("frontendIPConfigID" + suffix), + ID: to.Ptr("frontendIPConfigID" + suffix), }, BackendAddressPool: &network.SubResource{ - ID: ptr.To("backendPoolID" + suffix), + ID: to.Ptr("backendPoolID" + suffix), }, LoadDistribution: "Default", - FrontendPort: ptr.To(port), - BackendPort: ptr.To(getBackendPort(port)), - EnableFloatingIP: ptr.To(enableFloatingIP), - DisableOutboundSnat: ptr.To(false), - IdleTimeoutInMinutes: ptr.To(int32(4)), + FrontendPort: to.Ptr(port), + BackendPort: to.Ptr(getBackendPort(port)), + EnableFloatingIP: to.Ptr(enableFloatingIP), + DisableOutboundSnat: to.Ptr(false), + IdleTimeoutInMinutes: to.Ptr(int32(4)), Probe: &network.SubResource{ - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/" + + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/" + fmt.Sprintf("Microsoft.Network/loadBalancers/lbname/probes/atest1-TCP-%d%s", port, suffix)), }, }, } if enableTCPReset { - expectedRules.EnableTCPReset = ptr.To(true) + expectedRules.EnableTCPReset = to.Ptr(true) } return expectedRules } @@ -3253,10 +3253,10 @@ func getTestLoadBalancer(name, rgName, clusterName, identifier *string, service FrontendIPConfigurations: &[]network.FrontendIPConfiguration{ { Name: identifier, - ID: ptr.To("/subscriptions/subscription/resourceGroups/" + *rgName + "/providers/" + + ID: to.Ptr("/subscriptions/subscription/resourceGroups/" + *rgName + "/providers/" + "Microsoft.Network/loadBalancers/" + *name + "/frontendIPConfigurations/" + *identifier), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-aservice1")}, }, }, }, @@ -3265,39 +3265,39 @@ func getTestLoadBalancer(name, rgName, clusterName, identifier *string, service }, Probes: &[]network.Probe{ { - Name: ptr.To(*identifier + "-" + string(service.Spec.Ports[0].Protocol) + + Name: to.Ptr(*identifier + "-" + string(service.Spec.Ports[0].Protocol) + "-" + strconv.Itoa(int(service.Spec.Ports[0].Port))), ProbePropertiesFormat: &network.ProbePropertiesFormat{ - Port: ptr.To(int32(10080)), + Port: to.Ptr(int32(10080)), Protocol: network.ProbeProtocolTCP, - IntervalInSeconds: ptr.To(int32(5)), - ProbeThreshold: ptr.To(int32(2)), + IntervalInSeconds: to.Ptr(int32(5)), + ProbeThreshold: to.Ptr(int32(2)), }, }, }, LoadBalancingRules: &[]network.LoadBalancingRule{ { - Name: ptr.To(*identifier + "-" + string(service.Spec.Ports[0].Protocol) + + Name: to.Ptr(*identifier + "-" + string(service.Spec.Ports[0].Protocol) + "-" + strconv.Itoa(int(service.Spec.Ports[0].Port))), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ Protocol: network.TransportProtocol(caser.String((strings.ToLower(string(service.Spec.Ports[0].Protocol))))), FrontendIPConfiguration: &network.SubResource{ - ID: ptr.To("/subscriptions/subscription/resourceGroups/" + *rgName + "/providers/" + + ID: to.Ptr("/subscriptions/subscription/resourceGroups/" + *rgName + "/providers/" + "Microsoft.Network/loadBalancers/" + *name + "/frontendIPConfigurations/aservice1"), }, BackendAddressPool: &network.SubResource{ - ID: ptr.To("/subscriptions/subscription/resourceGroups/" + *rgName + "/providers/" + + ID: to.Ptr("/subscriptions/subscription/resourceGroups/" + *rgName + "/providers/" + "Microsoft.Network/loadBalancers/" + *name + "/backendAddressPools/" + *clusterName), }, LoadDistribution: network.LoadDistribution("Default"), - FrontendPort: ptr.To(service.Spec.Ports[0].Port), - BackendPort: ptr.To(service.Spec.Ports[0].Port), - EnableFloatingIP: ptr.To(true), - EnableTCPReset: ptr.To(strings.EqualFold(lbSku, "standard")), - DisableOutboundSnat: ptr.To(false), - IdleTimeoutInMinutes: ptr.To(int32(4)), + FrontendPort: to.Ptr(service.Spec.Ports[0].Port), + BackendPort: to.Ptr(service.Spec.Ports[0].Port), + EnableFloatingIP: to.Ptr(true), + EnableTCPReset: to.Ptr(strings.EqualFold(lbSku, "standard")), + DisableOutboundSnat: to.Ptr(false), + IdleTimeoutInMinutes: to.Ptr(int32(4)), Probe: &network.SubResource{ - ID: ptr.To("/subscriptions/subscription/resourceGroups/" + *rgName + "/providers/Microsoft.Network/loadBalancers/testCluster/probes/aservice1-TCP-80"), + ID: to.Ptr("/subscriptions/subscription/resourceGroups/" + *rgName + "/providers/Microsoft.Network/loadBalancers/testCluster/probes/aservice1-TCP-80"), }, }, }, @@ -3311,50 +3311,50 @@ func getTestLoadBalancerDualStack(name, rgName, clusterName, identifier *string, caser := cases.Title(language.English) lb := getTestLoadBalancer(name, rgName, clusterName, identifier, service, lbSku) *lb.LoadBalancerPropertiesFormat.FrontendIPConfigurations = append(*lb.LoadBalancerPropertiesFormat.FrontendIPConfigurations, network.FrontendIPConfiguration{ - Name: ptr.To(*identifier + ipv6Suffix), - ID: ptr.To("/subscriptions/subscription/resourceGroups/" + *rgName + "/providers/" + + Name: to.Ptr(*identifier + ipv6Suffix), + ID: to.Ptr("/subscriptions/subscription/resourceGroups/" + *rgName + "/providers/" + "Microsoft.Network/loadBalancers/" + *name + "/frontendIPConfigurations/" + *identifier + ipv6Suffix), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PublicIPAddress: &network.PublicIPAddress{ - ID: ptr.To("testCluster-aservice1-IPv6"), + ID: to.Ptr("testCluster-aservice1-IPv6"), }, }, }) *lb.LoadBalancerPropertiesFormat.BackendAddressPools = append(*lb.LoadBalancerPropertiesFormat.BackendAddressPools, network.BackendAddressPool{ - Name: ptr.To(*clusterName + ipv6Suffix), + Name: to.Ptr(*clusterName + ipv6Suffix), }) *lb.LoadBalancerPropertiesFormat.Probes = append(*lb.LoadBalancerPropertiesFormat.Probes, network.Probe{ - Name: ptr.To(*identifier + "-" + string(service.Spec.Ports[0].Protocol) + + Name: to.Ptr(*identifier + "-" + string(service.Spec.Ports[0].Protocol) + "-" + strconv.Itoa(int(service.Spec.Ports[0].Port)) + ipv6Suffix), ProbePropertiesFormat: &network.ProbePropertiesFormat{ - Port: ptr.To(int32(10080)), + Port: to.Ptr(int32(10080)), Protocol: network.ProbeProtocolTCP, - IntervalInSeconds: ptr.To(int32(5)), - ProbeThreshold: ptr.To(int32(2)), + IntervalInSeconds: to.Ptr(int32(5)), + ProbeThreshold: to.Ptr(int32(2)), }, }) *lb.LoadBalancerPropertiesFormat.LoadBalancingRules = append(*lb.LoadBalancerPropertiesFormat.LoadBalancingRules, network.LoadBalancingRule{ - Name: ptr.To(*identifier + "-" + string(service.Spec.Ports[0].Protocol) + + Name: to.Ptr(*identifier + "-" + string(service.Spec.Ports[0].Protocol) + "-" + strconv.Itoa(int(service.Spec.Ports[0].Port)) + ipv6Suffix), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ Protocol: network.TransportProtocol(caser.String((strings.ToLower(string(service.Spec.Ports[0].Protocol))))), FrontendIPConfiguration: &network.SubResource{ - ID: ptr.To("/subscriptions/subscription/resourceGroups/" + *rgName + "/providers/" + + ID: to.Ptr("/subscriptions/subscription/resourceGroups/" + *rgName + "/providers/" + "Microsoft.Network/loadBalancers/" + *name + "/frontendIPConfigurations/aservice1-IPv6"), }, BackendAddressPool: &network.SubResource{ - ID: ptr.To("/subscriptions/subscription/resourceGroups/" + *rgName + "/providers/" + + ID: to.Ptr("/subscriptions/subscription/resourceGroups/" + *rgName + "/providers/" + "Microsoft.Network/loadBalancers/" + *name + "/backendAddressPools/" + *clusterName + ipv6Suffix), }, LoadDistribution: network.LoadDistribution("Default"), - FrontendPort: ptr.To(service.Spec.Ports[0].Port), - BackendPort: ptr.To(service.Spec.Ports[0].Port), - EnableFloatingIP: ptr.To(true), - EnableTCPReset: ptr.To(strings.EqualFold(lbSku, "standard")), - DisableOutboundSnat: ptr.To(false), - IdleTimeoutInMinutes: ptr.To(int32(4)), + FrontendPort: to.Ptr(service.Spec.Ports[0].Port), + BackendPort: to.Ptr(service.Spec.Ports[0].Port), + EnableFloatingIP: to.Ptr(true), + EnableTCPReset: to.Ptr(strings.EqualFold(lbSku, "standard")), + DisableOutboundSnat: to.Ptr(false), + IdleTimeoutInMinutes: to.Ptr(int32(4)), Probe: &network.SubResource{ - ID: ptr.To("/subscriptions/subscription/resourceGroups/" + *rgName + "/providers/Microsoft.Network/loadBalancers/testCluster/probes/aservice1-TCP-80-IPv6"), + ID: to.Ptr("/subscriptions/subscription/resourceGroups/" + *rgName + "/providers/Microsoft.Network/loadBalancers/testCluster/probes/aservice1-TCP-80-IPv6"), }, }, }) @@ -3366,24 +3366,24 @@ func TestReconcileLoadBalancerCommon(t *testing.T) { defer ctrl.Finish() service1 := getTestServiceDualStack("service1", v1.ProtocolTCP, nil, 80) - basicLb1 := getTestLoadBalancerDualStack(ptr.To("testCluster"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("aservice1"), service1, "Basic") + basicLb1 := getTestLoadBalancerDualStack(to.Ptr("testCluster"), to.Ptr("rg"), to.Ptr("testCluster"), to.Ptr("aservice1"), service1, "Basic") service2 := getTestServiceDualStack("test1", v1.ProtocolTCP, nil, 80) - basicLb2 := getTestLoadBalancerDualStack(ptr.To("lb1"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("bservice1"), service2, "Basic") - basicLb2.Name = ptr.To("testCluster") + basicLb2 := getTestLoadBalancerDualStack(to.Ptr("lb1"), to.Ptr("rg"), to.Ptr("testCluster"), to.Ptr("bservice1"), service2, "Basic") + basicLb2.Name = to.Ptr("testCluster") basicLb2.FrontendIPConfigurations = &[]network.FrontendIPConfiguration{ { - Name: ptr.To("bservice1"), - ID: ptr.To("bservice1"), + Name: to.Ptr("bservice1"), + ID: to.Ptr("bservice1"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-bservice1")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-bservice1")}, }, }, { - Name: ptr.To("bservice1-IPv6"), - ID: ptr.To("bservice1-IPv6"), + Name: to.Ptr("bservice1-IPv6"), + ID: to.Ptr("bservice1-IPv6"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-bservice1-IPv6")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-bservice1-IPv6")}, }, }, } @@ -3391,309 +3391,309 @@ func TestReconcileLoadBalancerCommon(t *testing.T) { service3 := getTestServiceDualStack("service1", v1.ProtocolTCP, nil, 80) modifiedLbs := make([]network.LoadBalancer, 2) for i := range modifiedLbs { - modifiedLbs[i] = getTestLoadBalancerDualStack(ptr.To("testCluster"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("aservice1"), service3, "Basic") + modifiedLbs[i] = getTestLoadBalancerDualStack(to.Ptr("testCluster"), to.Ptr("rg"), to.Ptr("testCluster"), to.Ptr("aservice1"), service3, "Basic") modifiedLbs[i].FrontendIPConfigurations = &[]network.FrontendIPConfiguration{ { - Name: ptr.To("aservice1"), - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1"), + Name: to.Ptr("aservice1"), + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-aservice1")}, }, }, { - Name: ptr.To("bservice1"), - ID: ptr.To("bservice1"), + Name: to.Ptr("bservice1"), + ID: to.Ptr("bservice1"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-bservice1")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-bservice1")}, }, }, { - Name: ptr.To("aservice1-IPv6"), - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1-IPv6"), + Name: to.Ptr("aservice1-IPv6"), + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1-IPv6"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1-IPv6")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-aservice1-IPv6")}, }, }, { - Name: ptr.To("bservice1-IPv6"), - ID: ptr.To("bservice1-IPv6"), + Name: to.Ptr("bservice1-IPv6"), + ID: to.Ptr("bservice1-IPv6"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-bservice1-IPv6")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-bservice1-IPv6")}, }, }, } modifiedLbs[i].Probes = &[]network.Probe{ { - Name: ptr.To(svcPrefix + string(service3.Spec.Ports[0].Protocol) + + Name: to.Ptr(svcPrefix + string(service3.Spec.Ports[0].Protocol) + "-" + strconv.Itoa(int(service3.Spec.Ports[0].Port))), ProbePropertiesFormat: &network.ProbePropertiesFormat{ - Port: ptr.To(int32(10080)), + Port: to.Ptr(int32(10080)), }, }, { - Name: ptr.To(svcPrefix + string(service3.Spec.Ports[0].Protocol) + + Name: to.Ptr(svcPrefix + string(service3.Spec.Ports[0].Protocol) + "-" + strconv.Itoa(int(service3.Spec.Ports[0].Port))), ProbePropertiesFormat: &network.ProbePropertiesFormat{ - Port: ptr.To(int32(10081)), + Port: to.Ptr(int32(10081)), }, }, { - Name: ptr.To(svcPrefix + string(service3.Spec.Ports[0].Protocol) + + Name: to.Ptr(svcPrefix + string(service3.Spec.Ports[0].Protocol) + "-" + strconv.Itoa(int(service3.Spec.Ports[0].Port)) + ipv6Suffix), ProbePropertiesFormat: &network.ProbePropertiesFormat{ - Port: ptr.To(int32(10080)), + Port: to.Ptr(int32(10080)), }, }, { - Name: ptr.To(svcPrefix + string(service3.Spec.Ports[0].Protocol) + + Name: to.Ptr(svcPrefix + string(service3.Spec.Ports[0].Protocol) + "-" + strconv.Itoa(int(service3.Spec.Ports[0].Port)) + ipv6Suffix), ProbePropertiesFormat: &network.ProbePropertiesFormat{ - Port: ptr.To(int32(10081)), + Port: to.Ptr(int32(10081)), }, }, } } - expectedLb1 := getTestLoadBalancerDualStack(ptr.To("testCluster"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("aservice1"), service3, "Basic") + expectedLb1 := getTestLoadBalancerDualStack(to.Ptr("testCluster"), to.Ptr("rg"), to.Ptr("testCluster"), to.Ptr("aservice1"), service3, "Basic") expectedLb1.FrontendIPConfigurations = &[]network.FrontendIPConfiguration{ { - Name: ptr.To("aservice1"), - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1"), + Name: to.Ptr("aservice1"), + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-aservice1")}, }, }, { - Name: ptr.To("bservice1"), - ID: ptr.To("bservice1"), + Name: to.Ptr("bservice1"), + ID: to.Ptr("bservice1"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-bservice1")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-bservice1")}, }, }, { - Name: ptr.To("aservice1-IPv6"), - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1-IPv6"), + Name: to.Ptr("aservice1-IPv6"), + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1-IPv6"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1-IPv6")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-aservice1-IPv6")}, }, }, { - Name: ptr.To("bservice1-IPv6"), - ID: ptr.To("bservice1-IPv6"), + Name: to.Ptr("bservice1-IPv6"), + ID: to.Ptr("bservice1-IPv6"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-bservice1-IPv6")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-bservice1-IPv6")}, }, }, } service4 := getTestServiceDualStack("service1", v1.ProtocolTCP, map[string]string{}, 80) - existingSLB := getTestLoadBalancerDualStack(ptr.To("testCluster"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("aservice1"), service4, "Standard") + existingSLB := getTestLoadBalancerDualStack(to.Ptr("testCluster"), to.Ptr("rg"), to.Ptr("testCluster"), to.Ptr("aservice1"), service4, "Standard") existingSLB.FrontendIPConfigurations = &[]network.FrontendIPConfiguration{ { - Name: ptr.To("aservice1"), - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1"), + Name: to.Ptr("aservice1"), + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-aservice1")}, }, }, { - Name: ptr.To("bservice1"), - ID: ptr.To("bservice1"), + Name: to.Ptr("bservice1"), + ID: to.Ptr("bservice1"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-bservice1")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-bservice1")}, }, }, { - Name: ptr.To("aservice1-IPv6"), - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1-IPv6"), + Name: to.Ptr("aservice1-IPv6"), + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1-IPv6"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1-IPv6")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-aservice1-IPv6")}, }, }, { - Name: ptr.To("bservice1-IPv6"), - ID: ptr.To("bservice1-IPv6"), + Name: to.Ptr("bservice1-IPv6"), + ID: to.Ptr("bservice1-IPv6"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-bservice1-IPv6")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-bservice1-IPv6")}, }, }, } existingSLB.Probes = &[]network.Probe{ { - Name: ptr.To(svcPrefix + string(service4.Spec.Ports[0].Protocol) + + Name: to.Ptr(svcPrefix + string(service4.Spec.Ports[0].Protocol) + "-" + strconv.Itoa(int(service4.Spec.Ports[0].Port))), ProbePropertiesFormat: &network.ProbePropertiesFormat{ - Port: ptr.To(int32(10080)), + Port: to.Ptr(int32(10080)), }, }, { - Name: ptr.To(svcPrefix + string(service4.Spec.Ports[0].Protocol) + + Name: to.Ptr(svcPrefix + string(service4.Spec.Ports[0].Protocol) + "-" + strconv.Itoa(int(service4.Spec.Ports[0].Port))), ProbePropertiesFormat: &network.ProbePropertiesFormat{ - Port: ptr.To(int32(10081)), + Port: to.Ptr(int32(10081)), }, }, { - Name: ptr.To(svcPrefix + string(service4.Spec.Ports[0].Protocol) + + Name: to.Ptr(svcPrefix + string(service4.Spec.Ports[0].Protocol) + "-" + strconv.Itoa(int(service4.Spec.Ports[0].Port)) + ipv6Suffix), ProbePropertiesFormat: &network.ProbePropertiesFormat{ - Port: ptr.To(int32(10080)), + Port: to.Ptr(int32(10080)), }, }, { - Name: ptr.To(svcPrefix + string(service4.Spec.Ports[0].Protocol) + + Name: to.Ptr(svcPrefix + string(service4.Spec.Ports[0].Protocol) + "-" + strconv.Itoa(int(service4.Spec.Ports[0].Port)) + ipv6Suffix), ProbePropertiesFormat: &network.ProbePropertiesFormat{ - Port: ptr.To(int32(10081)), + Port: to.Ptr(int32(10081)), }, }, } - expectedSLb := getTestLoadBalancerDualStack(ptr.To("testCluster"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("aservice1"), service4, "Standard") - (*expectedSLb.LoadBalancerPropertiesFormat.LoadBalancingRules)[0].DisableOutboundSnat = ptr.To(true) - (*expectedSLb.LoadBalancerPropertiesFormat.LoadBalancingRules)[0].EnableTCPReset = ptr.To(true) - (*expectedSLb.LoadBalancerPropertiesFormat.LoadBalancingRules)[0].IdleTimeoutInMinutes = ptr.To(int32(4)) - (*expectedSLb.LoadBalancerPropertiesFormat.LoadBalancingRules)[1].DisableOutboundSnat = ptr.To(true) - (*expectedSLb.LoadBalancerPropertiesFormat.LoadBalancingRules)[1].EnableTCPReset = ptr.To(true) - (*expectedSLb.LoadBalancerPropertiesFormat.LoadBalancingRules)[1].IdleTimeoutInMinutes = ptr.To(int32(4)) + expectedSLb := getTestLoadBalancerDualStack(to.Ptr("testCluster"), to.Ptr("rg"), to.Ptr("testCluster"), to.Ptr("aservice1"), service4, "Standard") + (*expectedSLb.LoadBalancerPropertiesFormat.LoadBalancingRules)[0].DisableOutboundSnat = to.Ptr(true) + (*expectedSLb.LoadBalancerPropertiesFormat.LoadBalancingRules)[0].EnableTCPReset = to.Ptr(true) + (*expectedSLb.LoadBalancerPropertiesFormat.LoadBalancingRules)[0].IdleTimeoutInMinutes = to.Ptr(int32(4)) + (*expectedSLb.LoadBalancerPropertiesFormat.LoadBalancingRules)[1].DisableOutboundSnat = to.Ptr(true) + (*expectedSLb.LoadBalancerPropertiesFormat.LoadBalancingRules)[1].EnableTCPReset = to.Ptr(true) + (*expectedSLb.LoadBalancerPropertiesFormat.LoadBalancingRules)[1].IdleTimeoutInMinutes = to.Ptr(int32(4)) expectedSLb.FrontendIPConfigurations = &[]network.FrontendIPConfiguration{ { - Name: ptr.To("aservice1"), - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1"), + Name: to.Ptr("aservice1"), + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-aservice1")}, }, }, { - Name: ptr.To("bservice1"), - ID: ptr.To("bservice1"), + Name: to.Ptr("bservice1"), + ID: to.Ptr("bservice1"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-bservice1")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-bservice1")}, }, }, { - Name: ptr.To("aservice1-IPv6"), - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1-IPv6"), + Name: to.Ptr("aservice1-IPv6"), + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1-IPv6"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1-IPv6")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-aservice1-IPv6")}, }, }, { - Name: ptr.To("bservice1-IPv6"), - ID: ptr.To("bservice1-IPv6"), + Name: to.Ptr("bservice1-IPv6"), + ID: to.Ptr("bservice1-IPv6"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-bservice1-IPv6")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-bservice1-IPv6")}, }, }, } service5 := getTestServiceDualStack("service1", v1.ProtocolTCP, nil, 80) - slb5 := getTestLoadBalancerDualStack(ptr.To("testCluster"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("aservice1"), service5, "Standard") + slb5 := getTestLoadBalancerDualStack(to.Ptr("testCluster"), to.Ptr("rg"), to.Ptr("testCluster"), to.Ptr("aservice1"), service5, "Standard") slb5.FrontendIPConfigurations = &[]network.FrontendIPConfiguration{ { - Name: ptr.To("aservice1"), - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1"), + Name: to.Ptr("aservice1"), + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-aservice1")}, }, }, { - Name: ptr.To("bservice1"), - ID: ptr.To("bservice1"), + Name: to.Ptr("bservice1"), + ID: to.Ptr("bservice1"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-bservice1")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-bservice1")}, }, }, { - Name: ptr.To("aservice1-IPv6"), - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1-IPv6"), + Name: to.Ptr("aservice1-IPv6"), + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1-IPv6"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1-IPv6")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-aservice1-IPv6")}, }, }, { - Name: ptr.To("bservice1-IPv6"), - ID: ptr.To("bservice1-IPv6"), + Name: to.Ptr("bservice1-IPv6"), + ID: to.Ptr("bservice1-IPv6"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-bservice1-IPv6")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-bservice1-IPv6")}, }, }, } slb5.Probes = &[]network.Probe{ { - Name: ptr.To(svcPrefix + string(service4.Spec.Ports[0].Protocol) + + Name: to.Ptr(svcPrefix + string(service4.Spec.Ports[0].Protocol) + "-" + strconv.Itoa(int(service4.Spec.Ports[0].Port))), ProbePropertiesFormat: &network.ProbePropertiesFormat{ - Port: ptr.To(int32(10080)), + Port: to.Ptr(int32(10080)), }, }, { - Name: ptr.To(svcPrefix + string(service4.Spec.Ports[0].Protocol) + + Name: to.Ptr(svcPrefix + string(service4.Spec.Ports[0].Protocol) + "-" + strconv.Itoa(int(service4.Spec.Ports[0].Port))), ProbePropertiesFormat: &network.ProbePropertiesFormat{ - Port: ptr.To(int32(10081)), + Port: to.Ptr(int32(10081)), }, }, { - Name: ptr.To(svcPrefix + string(service4.Spec.Ports[0].Protocol) + + Name: to.Ptr(svcPrefix + string(service4.Spec.Ports[0].Protocol) + "-" + strconv.Itoa(int(service4.Spec.Ports[0].Port)) + ipv6Suffix), ProbePropertiesFormat: &network.ProbePropertiesFormat{ - Port: ptr.To(int32(10080)), + Port: to.Ptr(int32(10080)), }, }, { - Name: ptr.To(svcPrefix + string(service4.Spec.Ports[0].Protocol) + + Name: to.Ptr(svcPrefix + string(service4.Spec.Ports[0].Protocol) + "-" + strconv.Itoa(int(service4.Spec.Ports[0].Port)) + ipv6Suffix), ProbePropertiesFormat: &network.ProbePropertiesFormat{ - Port: ptr.To(int32(10081)), + Port: to.Ptr(int32(10081)), }, }, } // change to false to test that reconciliation will fix it (despite the fact that disable-tcp-reset was removed in 1.20) - (*slb5.LoadBalancerPropertiesFormat.LoadBalancingRules)[0].EnableTCPReset = ptr.To(false) - (*slb5.LoadBalancerPropertiesFormat.LoadBalancingRules)[1].EnableTCPReset = ptr.To(false) - - expectedSLb5 := getTestLoadBalancerDualStack(ptr.To("testCluster"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("aservice1"), service5, "Standard") - (*expectedSLb5.LoadBalancerPropertiesFormat.LoadBalancingRules)[0].DisableOutboundSnat = ptr.To(true) - (*expectedSLb5.LoadBalancerPropertiesFormat.LoadBalancingRules)[0].IdleTimeoutInMinutes = ptr.To(int32(4)) - (*expectedSLb5.LoadBalancerPropertiesFormat.LoadBalancingRules)[1].DisableOutboundSnat = ptr.To(true) - (*expectedSLb5.LoadBalancerPropertiesFormat.LoadBalancingRules)[1].IdleTimeoutInMinutes = ptr.To(int32(4)) + (*slb5.LoadBalancerPropertiesFormat.LoadBalancingRules)[0].EnableTCPReset = to.Ptr(false) + (*slb5.LoadBalancerPropertiesFormat.LoadBalancingRules)[1].EnableTCPReset = to.Ptr(false) + + expectedSLb5 := getTestLoadBalancerDualStack(to.Ptr("testCluster"), to.Ptr("rg"), to.Ptr("testCluster"), to.Ptr("aservice1"), service5, "Standard") + (*expectedSLb5.LoadBalancerPropertiesFormat.LoadBalancingRules)[0].DisableOutboundSnat = to.Ptr(true) + (*expectedSLb5.LoadBalancerPropertiesFormat.LoadBalancingRules)[0].IdleTimeoutInMinutes = to.Ptr(int32(4)) + (*expectedSLb5.LoadBalancerPropertiesFormat.LoadBalancingRules)[1].DisableOutboundSnat = to.Ptr(true) + (*expectedSLb5.LoadBalancerPropertiesFormat.LoadBalancingRules)[1].IdleTimeoutInMinutes = to.Ptr(int32(4)) expectedSLb5.FrontendIPConfigurations = &[]network.FrontendIPConfiguration{ { - Name: ptr.To("aservice1"), - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1"), + Name: to.Ptr("aservice1"), + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-aservice1")}, }, }, { - Name: ptr.To("bservice1"), - ID: ptr.To("bservice1"), + Name: to.Ptr("bservice1"), + ID: to.Ptr("bservice1"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-bservice1")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-bservice1")}, }, }, { - Name: ptr.To("aservice1-IPv6"), - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1-IPv6"), + Name: to.Ptr("aservice1-IPv6"), + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1-IPv6"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1-IPv6")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-aservice1-IPv6")}, }, }, { - Name: ptr.To("bservice1-IPv6"), - ID: ptr.To("bservice1-IPv6"), + Name: to.Ptr("bservice1-IPv6"), + ID: to.Ptr("bservice1-IPv6"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-bservice1-IPv6")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-bservice1-IPv6")}, }, }, } service6 := getTestServiceDualStack("service1", v1.ProtocolUDP, nil, 80) - lb6 := getTestLoadBalancerDualStack(ptr.To("testCluster"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("aservice1"), service6, "basic") + lb6 := getTestLoadBalancerDualStack(to.Ptr("testCluster"), to.Ptr("rg"), to.Ptr("testCluster"), to.Ptr("aservice1"), service6, "basic") lb6.FrontendIPConfigurations = &[]network.FrontendIPConfiguration{} lb6.Probes = &[]network.Probe{} - expectedLB6 := getTestLoadBalancerDualStack(ptr.To("testCluster"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("aservice1"), service6, "basic") + expectedLB6 := getTestLoadBalancerDualStack(to.Ptr("testCluster"), to.Ptr("rg"), to.Ptr("testCluster"), to.Ptr("aservice1"), service6, "basic") expectedLB6.Probes = &[]network.Probe{} (*expectedLB6.LoadBalancerPropertiesFormat.LoadBalancingRules)[0].Probe = nil (*expectedLB6.LoadBalancerPropertiesFormat.LoadBalancingRules)[0].EnableTCPReset = nil @@ -3701,17 +3701,17 @@ func TestReconcileLoadBalancerCommon(t *testing.T) { (*expectedLB6.LoadBalancerPropertiesFormat.LoadBalancingRules)[1].EnableTCPReset = nil expectedLB6.FrontendIPConfigurations = &[]network.FrontendIPConfiguration{ { - Name: ptr.To("aservice1"), - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1"), + Name: to.Ptr("aservice1"), + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-aservice1")}, }, }, { - Name: ptr.To("aservice1-IPv6"), - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1-IPv6"), + Name: to.Ptr("aservice1-IPv6"), + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1-IPv6"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1-IPv6")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-aservice1-IPv6")}, }, }, } @@ -3719,103 +3719,103 @@ func TestReconcileLoadBalancerCommon(t *testing.T) { service7 := getTestServiceDualStack("service1", v1.ProtocolUDP, nil, 80) service7.Spec.HealthCheckNodePort = 10081 service7.Spec.ExternalTrafficPolicy = v1.ServiceExternalTrafficPolicyTypeLocal - lb7 := getTestLoadBalancerDualStack(ptr.To("testCluster"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("aservice1"), service7, "basic") + lb7 := getTestLoadBalancerDualStack(to.Ptr("testCluster"), to.Ptr("rg"), to.Ptr("testCluster"), to.Ptr("aservice1"), service7, "basic") lb7.FrontendIPConfigurations = &[]network.FrontendIPConfiguration{} lb7.Probes = &[]network.Probe{} - expectedLB7 := getTestLoadBalancerDualStack(ptr.To("testCluster"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("aservice1"), service7, "basic") + expectedLB7 := getTestLoadBalancerDualStack(to.Ptr("testCluster"), to.Ptr("rg"), to.Ptr("testCluster"), to.Ptr("aservice1"), service7, "basic") (*expectedLB7.LoadBalancerPropertiesFormat.LoadBalancingRules)[0].Probe = &network.SubResource{ - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/probes/aservice1-TCP-10081"), + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/probes/aservice1-TCP-10081"), } (*expectedLB7.LoadBalancerPropertiesFormat.LoadBalancingRules)[1].Probe = &network.SubResource{ - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/probes/aservice1-TCP-10081-IPv6"), + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/probes/aservice1-TCP-10081-IPv6"), } (*expectedLB7.LoadBalancerPropertiesFormat.LoadBalancingRules)[0].EnableTCPReset = nil - (*lb7.LoadBalancerPropertiesFormat.LoadBalancingRules)[0].DisableOutboundSnat = ptr.To(true) + (*lb7.LoadBalancerPropertiesFormat.LoadBalancingRules)[0].DisableOutboundSnat = to.Ptr(true) (*expectedLB7.LoadBalancerPropertiesFormat.LoadBalancingRules)[1].EnableTCPReset = nil - (*lb7.LoadBalancerPropertiesFormat.LoadBalancingRules)[1].DisableOutboundSnat = ptr.To(true) + (*lb7.LoadBalancerPropertiesFormat.LoadBalancingRules)[1].DisableOutboundSnat = to.Ptr(true) expectedLB7.FrontendIPConfigurations = &[]network.FrontendIPConfiguration{ { - Name: ptr.To("aservice1"), - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1"), + Name: to.Ptr("aservice1"), + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-aservice1")}, }, }, { - Name: ptr.To("aservice1-IPv6"), - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1-IPv6"), + Name: to.Ptr("aservice1-IPv6"), + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1-IPv6"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1-IPv6")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-aservice1-IPv6")}, }, }, } expectedLB7.Probes = &[]network.Probe{ { - Name: ptr.To(svcPrefix + string(v1.ProtocolTCP) + + Name: to.Ptr(svcPrefix + string(v1.ProtocolTCP) + "-" + strconv.Itoa(int(service7.Spec.HealthCheckNodePort))), ProbePropertiesFormat: &network.ProbePropertiesFormat{ - Port: ptr.To(int32(10081)), - RequestPath: ptr.To("/healthz"), + Port: to.Ptr(int32(10081)), + RequestPath: to.Ptr("/healthz"), Protocol: network.ProbeProtocolHTTP, - IntervalInSeconds: ptr.To(int32(5)), - ProbeThreshold: ptr.To(int32(2)), + IntervalInSeconds: to.Ptr(int32(5)), + ProbeThreshold: to.Ptr(int32(2)), }, }, { - Name: ptr.To(svcPrefix + string(v1.ProtocolTCP) + + Name: to.Ptr(svcPrefix + string(v1.ProtocolTCP) + "-" + strconv.Itoa(int(service7.Spec.HealthCheckNodePort)) + ipv6Suffix), ProbePropertiesFormat: &network.ProbePropertiesFormat{ - Port: ptr.To(int32(10081)), - RequestPath: ptr.To("/healthz"), + Port: to.Ptr(int32(10081)), + RequestPath: to.Ptr("/healthz"), Protocol: network.ProbeProtocolHTTP, - IntervalInSeconds: ptr.To(int32(5)), - ProbeThreshold: ptr.To(int32(2)), + IntervalInSeconds: to.Ptr(int32(5)), + ProbeThreshold: to.Ptr(int32(2)), }, }, } service8 := getTestServiceDualStack("service1", v1.ProtocolTCP, nil, 80) - lb8 := getTestLoadBalancerDualStack(ptr.To("testCluster"), ptr.To("anotherRG"), ptr.To("testCluster"), ptr.To("aservice1"), service8, "Standard") + lb8 := getTestLoadBalancerDualStack(to.Ptr("testCluster"), to.Ptr("anotherRG"), to.Ptr("testCluster"), to.Ptr("aservice1"), service8, "Standard") lb8.FrontendIPConfigurations = &[]network.FrontendIPConfiguration{} lb8.Probes = &[]network.Probe{} - expectedLB8 := getTestLoadBalancerDualStack(ptr.To("testCluster"), ptr.To("anotherRG"), ptr.To("testCluster"), ptr.To("aservice1"), service8, "Standard") - (*expectedLB8.LoadBalancerPropertiesFormat.LoadBalancingRules)[0].DisableOutboundSnat = ptr.To(false) - (*expectedLB8.LoadBalancerPropertiesFormat.LoadBalancingRules)[1].DisableOutboundSnat = ptr.To(false) + expectedLB8 := getTestLoadBalancerDualStack(to.Ptr("testCluster"), to.Ptr("anotherRG"), to.Ptr("testCluster"), to.Ptr("aservice1"), service8, "Standard") + (*expectedLB8.LoadBalancerPropertiesFormat.LoadBalancingRules)[0].DisableOutboundSnat = to.Ptr(false) + (*expectedLB8.LoadBalancerPropertiesFormat.LoadBalancingRules)[1].DisableOutboundSnat = to.Ptr(false) expectedLB8.FrontendIPConfigurations = &[]network.FrontendIPConfiguration{ { - Name: ptr.To("aservice1"), - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1"), + Name: to.Ptr("aservice1"), + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-aservice1")}, }, }, { - Name: ptr.To("aservice1-IPv6"), - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1-IPv6"), + Name: to.Ptr("aservice1-IPv6"), + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/testCluster/frontendIPConfigurations/aservice1-IPv6"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1-IPv6")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-aservice1-IPv6")}, }, }, } expectedLB8.Probes = &[]network.Probe{ { - Name: ptr.To(svcPrefix + string(service8.Spec.Ports[0].Protocol) + + Name: to.Ptr(svcPrefix + string(service8.Spec.Ports[0].Protocol) + "-" + strconv.Itoa(int(service7.Spec.Ports[0].Port))), ProbePropertiesFormat: &network.ProbePropertiesFormat{ - Port: ptr.To(int32(10080)), + Port: to.Ptr(int32(10080)), Protocol: network.ProbeProtocolTCP, - IntervalInSeconds: ptr.To(int32(5)), - ProbeThreshold: ptr.To(int32(2)), + IntervalInSeconds: to.Ptr(int32(5)), + ProbeThreshold: to.Ptr(int32(2)), }, }, { - Name: ptr.To(svcPrefix + string(service8.Spec.Ports[0].Protocol) + + Name: to.Ptr(svcPrefix + string(service8.Spec.Ports[0].Protocol) + "-" + strconv.Itoa(int(service7.Spec.Ports[0].Port)) + ipv6Suffix), ProbePropertiesFormat: &network.ProbePropertiesFormat{ - Port: ptr.To(int32(10080)), + Port: to.Ptr(int32(10080)), Protocol: network.ProbeProtocolTCP, - IntervalInSeconds: ptr.To(int32(5)), - ProbeThreshold: ptr.To(int32(2)), + IntervalInSeconds: to.Ptr(int32(5)), + ProbeThreshold: to.Ptr(int32(2)), }, }, } @@ -3880,7 +3880,7 @@ func TestReconcileLoadBalancerCommon(t *testing.T) { desc: "reconcileLoadBalancer shall remove and reconstruct the corresponding field of lb and set enableTcpReset to true in lbRule", loadBalancerSku: "standard", service: service4, - disableOutboundSnat: ptr.To(true), + disableOutboundSnat: to.Ptr(true), existingLB: existingSLB, wantLb: true, expectedLB: expectedSLb, @@ -3891,7 +3891,7 @@ func TestReconcileLoadBalancerCommon(t *testing.T) { desc: "reconcileLoadBalancer shall remove and reconstruct the corresponding field of lb and set enableTcpReset (false => true) in lbRule", loadBalancerSku: "standard", service: service5, - disableOutboundSnat: ptr.To(true), + disableOutboundSnat: to.Ptr(true), existingLB: slb5, wantLb: true, expectedLB: expectedSLb5, @@ -3969,17 +3969,17 @@ func TestReconcileLoadBalancerCommon(t *testing.T) { setServiceLoadBalancerIP(&service, "fd00::eef0") err := az.PublicIPAddressesClient.CreateOrUpdate(context.TODO(), "rg", "pipName", network.PublicIPAddress{ - Name: ptr.To("pipName"), + Name: to.Ptr("pipName"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), PublicIPAddressVersion: network.IPv4, }, }) assert.NoError(t, err.Error()) err = az.PublicIPAddressesClient.CreateOrUpdate(context.TODO(), "rg", "pipName-IPv6", network.PublicIPAddress{ - Name: ptr.To("pipName-IPv6"), + Name: to.Ptr("pipName-IPv6"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("fd00::eef0"), + IPAddress: to.Ptr("fd00::eef0"), PublicIPAddressVersion: network.IPv6, }, }) @@ -4029,61 +4029,61 @@ func TestGetServiceLoadBalancerStatus(t *testing.T) { setMockPublicIPs(az, ctrl, 1, v4Enabled, v6Enabled) - lb1 := getTestLoadBalancer(ptr.To("lb1"), ptr.To("rg"), ptr.To("testCluster"), - ptr.To("aservice1"), internalService, "Basic") + lb1 := getTestLoadBalancer(to.Ptr("lb1"), to.Ptr("rg"), to.Ptr("testCluster"), + to.Ptr("aservice1"), internalService, "Basic") lb1.FrontendIPConfigurations = nil - lb2 := getTestLoadBalancer(ptr.To("lb2"), ptr.To("rg"), ptr.To("testCluster"), - ptr.To("aservice1"), internalService, "Basic") + lb2 := getTestLoadBalancer(to.Ptr("lb2"), to.Ptr("rg"), to.Ptr("testCluster"), + to.Ptr("aservice1"), internalService, "Basic") lb2.FrontendIPConfigurations = &[]network.FrontendIPConfiguration{ { - Name: ptr.To("aservice1"), + Name: to.Ptr("aservice1"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, - PrivateIPAddress: ptr.To("private"), + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-aservice1")}, + PrivateIPAddress: to.Ptr("private"), }, }, } - lb3 := getTestLoadBalancer(ptr.To("lb3"), ptr.To("rg"), ptr.To("testCluster"), - ptr.To("test1"), internalService, "Basic") + lb3 := getTestLoadBalancer(to.Ptr("lb3"), to.Ptr("rg"), to.Ptr("testCluster"), + to.Ptr("test1"), internalService, "Basic") lb3.FrontendIPConfigurations = &[]network.FrontendIPConfiguration{ { - Name: ptr.To("bservice1"), + Name: to.Ptr("bservice1"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-bservice1")}, - PrivateIPAddress: ptr.To("private"), + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-bservice1")}, + PrivateIPAddress: to.Ptr("private"), }, }, } - lb4 := getTestLoadBalancer(ptr.To("lb4"), ptr.To("rg"), ptr.To("testCluster"), - ptr.To("aservice1"), service, "Basic") + lb4 := getTestLoadBalancer(to.Ptr("lb4"), to.Ptr("rg"), to.Ptr("testCluster"), + to.Ptr("aservice1"), service, "Basic") lb4.FrontendIPConfigurations = &[]network.FrontendIPConfiguration{ { - Name: ptr.To("aservice1"), + Name: to.Ptr("aservice1"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PublicIPAddress: &network.PublicIPAddress{ID: nil}, - PrivateIPAddress: ptr.To("private"), + PrivateIPAddress: to.Ptr("private"), }, }, } - lb5 := getTestLoadBalancer(ptr.To("lb5"), ptr.To("rg"), ptr.To("testCluster"), - ptr.To("aservice1"), service, "Basic") + lb5 := getTestLoadBalancer(to.Ptr("lb5"), to.Ptr("rg"), to.Ptr("testCluster"), + to.Ptr("aservice1"), service, "Basic") lb5.FrontendIPConfigurations = &[]network.FrontendIPConfiguration{ { - Name: ptr.To("aservice1"), + Name: to.Ptr("aservice1"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PublicIPAddress: nil, - PrivateIPAddress: ptr.To("private"), + PrivateIPAddress: to.Ptr("private"), }, }, } - lb6 := getTestLoadBalancer(ptr.To("lb6"), ptr.To("rg"), ptr.To("testCluster"), - ptr.To("aservice1"), service, "Basic") + lb6 := getTestLoadBalancer(to.Ptr("lb6"), to.Ptr("rg"), to.Ptr("testCluster"), + to.Ptr("aservice1"), service, "Basic") lb6.FrontendIPConfigurations = &[]network.FrontendIPConfiguration{ { - Name: ptr.To("aservice1"), + Name: to.Ptr("aservice1"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("illegal/id/")}, - PrivateIPAddress: ptr.To("private"), + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("illegal/id/")}, + PrivateIPAddress: to.Ptr("private"), }, }, } @@ -4168,35 +4168,35 @@ func TestSafeDeletePublicIP(t *testing.T) { { desc: "safeDeletePublicIP shall delete corresponding ip configurations and lb rules", pip: &network.PublicIPAddress{ - Name: ptr.To("pip1"), + Name: to.Ptr("pip1"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ IPConfiguration: &network.IPConfiguration{ - ID: ptr.To("id1"), + ID: to.Ptr("id1"), }, }, }, lb: &network.LoadBalancer{ - Name: ptr.To("lb1"), + Name: to.Ptr("lb1"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ FrontendIPConfigurations: &[]network.FrontendIPConfiguration{ { - ID: ptr.To("id1"), + ID: to.Ptr("id1"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - LoadBalancingRules: &[]network.SubResource{{ID: ptr.To("rules1")}}, + LoadBalancingRules: &[]network.SubResource{{ID: to.Ptr("rules1")}}, }, }, }, - LoadBalancingRules: &[]network.LoadBalancingRule{{ID: ptr.To("rules1")}}, + LoadBalancingRules: &[]network.LoadBalancingRule{{ID: to.Ptr("rules1")}}, }, }, }, { desc: "safeDeletePublicIP should return error if failed to list pip", pip: &network.PublicIPAddress{ - Name: ptr.To("pip1"), + Name: to.Ptr("pip1"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ IPConfiguration: &network.IPConfiguration{ - ID: ptr.To("id1"), + ID: to.Ptr("id1"), }, }, }, @@ -4217,10 +4217,10 @@ func TestSafeDeletePublicIP(t *testing.T) { mockPIPsClient.EXPECT().CreateOrUpdate(gomock.Any(), "rg", "pip1", gomock.Any()).Return(nil).AnyTimes() mockPIPsClient.EXPECT().Delete(gomock.Any(), "rg", "pip1").Return(nil).AnyTimes() err := az.PublicIPAddressesClient.CreateOrUpdate(context.TODO(), "rg", "pip1", network.PublicIPAddress{ - Name: ptr.To("pip1"), + Name: to.Ptr("pip1"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ IPConfiguration: &network.IPConfiguration{ - ID: ptr.To("id1"), + ID: to.Ptr("id1"), }, }, }) @@ -4245,11 +4245,11 @@ func TestSafeDeletePublicIP(t *testing.T) { func TestReconcilePublicIPsCommon(t *testing.T) { deleteUnwantedPIPsAndCreateANewOneclientGet := func(client *mockpublicipclient.MockInterface) { - client.EXPECT().Get(gomock.Any(), "rg", "testCluster-atest1", gomock.Any()).Return(network.PublicIPAddress{ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testCluster-atest1")}, nil).Times(1) - client.EXPECT().Get(gomock.Any(), "rg", "testCluster-atest1-IPv6", gomock.Any()).Return(network.PublicIPAddress{ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testCluster-atest1-IPv6")}, nil).Times(1) + client.EXPECT().Get(gomock.Any(), "rg", "testCluster-atest1", gomock.Any()).Return(network.PublicIPAddress{ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testCluster-atest1")}, nil).Times(1) + client.EXPECT().Get(gomock.Any(), "rg", "testCluster-atest1-IPv6", gomock.Any()).Return(network.PublicIPAddress{ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testCluster-atest1-IPv6")}, nil).Times(1) } getPIPAddMissingOne := func(client *mockpublicipclient.MockInterface) { - client.EXPECT().Get(gomock.Any(), "rg", "testCluster-atest1-IPv6", gomock.Any()).Return(network.PublicIPAddress{ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testCluster-atest1-IPv6")}, nil).Times(1) + client.EXPECT().Get(gomock.Any(), "rg", "testCluster-atest1-IPv6", gomock.Any()).Return(network.PublicIPAddress{ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testCluster-atest1-IPv6")}, nil).Times(1) } testCases := []struct { @@ -4275,7 +4275,7 @@ func TestReconcilePublicIPsCommon(t *testing.T) { wantLb: false, existingPIPs: []network.PublicIPAddress{ { - Name: ptr.To("pip1"), + Name: to.Ptr("pip1"), }, }, expectedCreateOrUpdateCount: 0, @@ -4286,17 +4286,17 @@ func TestReconcilePublicIPsCommon(t *testing.T) { wantLb: true, existingPIPs: []network.PublicIPAddress{ { - Name: ptr.To("pip1"), - Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, + Name: to.Ptr("pip1"), + Tags: map[string]*string{consts.ServiceTagKey: to.Ptr("default/test1")}, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, { - Name: ptr.To("pip1-IPv6"), - Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, + Name: to.Ptr("pip1-IPv6"), + Tags: map[string]*string{consts.ServiceTagKey: to.Ptr("default/test1")}, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("fd00::eef0"), + IPAddress: to.Ptr("fd00::eef0"), }, }, }, @@ -4316,12 +4316,12 @@ func TestReconcilePublicIPsCommon(t *testing.T) { annotations: map[string]string{consts.ServiceAnnotationPIPNameDualStack[false]: "testPIP"}, existingPIPs: []network.PublicIPAddress{ { - Name: ptr.To("pip1"), - Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, + Name: to.Ptr("pip1"), + Tags: map[string]*string{consts.ServiceTagKey: to.Ptr("default/test1")}, }, { - Name: ptr.To("pip2"), - Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, + Name: to.Ptr("pip2"), + Tags: map[string]*string{consts.ServiceTagKey: to.Ptr("default/test1")}, }, }, expectedError: true, @@ -4337,57 +4337,57 @@ func TestReconcilePublicIPsCommon(t *testing.T) { }, existingPIPs: []network.PublicIPAddress{ { - Name: ptr.To("pip1"), - Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, + Name: to.Ptr("pip1"), + Tags: map[string]*string{consts.ServiceTagKey: to.Ptr("default/test1")}, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv4, - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, { - Name: ptr.To("pip2"), - Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, + Name: to.Ptr("pip2"), + Tags: map[string]*string{consts.ServiceTagKey: to.Ptr("default/test1")}, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv4, - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, { - Name: ptr.To("testPIP"), - Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, + Name: to.Ptr("testPIP"), + Tags: map[string]*string{consts.ServiceTagKey: to.Ptr("default/test1")}, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv4, - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, { - Name: ptr.To("testPIP-IPv6"), - Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, + Name: to.Ptr("testPIP-IPv6"), + Tags: map[string]*string{consts.ServiceTagKey: to.Ptr("default/test1")}, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv6, PublicIPAllocationMethod: network.Dynamic, - IPAddress: ptr.To("fd00::eef0"), + IPAddress: to.Ptr("fd00::eef0"), }, }, }, expectedPIPs: []*network.PublicIPAddress{ { - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP"), - Name: ptr.To("testPIP"), - Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP"), + Name: to.Ptr("testPIP"), + Tags: map[string]*string{consts.ServiceTagKey: to.Ptr("default/test1")}, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv4, - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, { - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP-IPv6"), - Name: ptr.To("testPIP-IPv6"), - Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP-IPv6"), + Name: to.Ptr("testPIP-IPv6"), + Tags: map[string]*string{consts.ServiceTagKey: to.Ptr("default/test1")}, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv6, PublicIPAllocationMethod: network.Dynamic, - IPAddress: ptr.To("fd00::eef0"), + IPAddress: to.Ptr("fd00::eef0"), }, }, }, @@ -4403,73 +4403,73 @@ func TestReconcilePublicIPsCommon(t *testing.T) { }, existingPIPs: []network.PublicIPAddress{ { - Name: ptr.To("pip1"), - Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, + Name: to.Ptr("pip1"), + Tags: map[string]*string{consts.ServiceTagKey: to.Ptr("default/test1")}, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv4, - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, { - Name: ptr.To("pip2"), - Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1,default/test2")}, + Name: to.Ptr("pip2"), + Tags: map[string]*string{consts.ServiceTagKey: to.Ptr("default/test1,default/test2")}, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv4, - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, { - Name: ptr.To("pip1-IPv6"), - Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, + Name: to.Ptr("pip1-IPv6"), + Tags: map[string]*string{consts.ServiceTagKey: to.Ptr("default/test1")}, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv6, - IPAddress: ptr.To("fd00::eef0"), + IPAddress: to.Ptr("fd00::eef0"), }, }, { - Name: ptr.To("pip2-IPv6"), - Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1,default/test2")}, + Name: to.Ptr("pip2-IPv6"), + Tags: map[string]*string{consts.ServiceTagKey: to.Ptr("default/test1,default/test2")}, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv6, - IPAddress: ptr.To("fd00::eef0"), + IPAddress: to.Ptr("fd00::eef0"), }, }, { - Name: ptr.To("testPIP"), - Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, + Name: to.Ptr("testPIP"), + Tags: map[string]*string{consts.ServiceTagKey: to.Ptr("default/test1")}, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv4, - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, { - Name: ptr.To("testPIP-IPv6"), - Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, + Name: to.Ptr("testPIP-IPv6"), + Tags: map[string]*string{consts.ServiceTagKey: to.Ptr("default/test1")}, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv6, PublicIPAllocationMethod: network.Dynamic, - IPAddress: ptr.To("fd00::eef0"), + IPAddress: to.Ptr("fd00::eef0"), }, }, }, expectedPIPs: []*network.PublicIPAddress{ { - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP"), - Name: ptr.To("testPIP"), - Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP"), + Name: to.Ptr("testPIP"), + Tags: map[string]*string{consts.ServiceTagKey: to.Ptr("default/test1")}, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv4, - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, { - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP-IPv6"), - Name: ptr.To("testPIP-IPv6"), - Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP-IPv6"), + Name: to.Ptr("testPIP-IPv6"), + Tags: map[string]*string{consts.ServiceTagKey: to.Ptr("default/test1")}, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv6, PublicIPAllocationMethod: network.Dynamic, - IPAddress: ptr.To("fd00::eef0"), + IPAddress: to.Ptr("fd00::eef0"), }, }, }, @@ -4486,69 +4486,69 @@ func TestReconcilePublicIPsCommon(t *testing.T) { }, existingPIPs: []network.PublicIPAddress{ { - Name: ptr.To("pip1"), + Name: to.Ptr("pip1"), Tags: map[string]*string{ - consts.ServiceTagKey: ptr.To("default/test1"), - consts.LegacyServiceTagKey: ptr.To("foo"), // It should be ignored when ServiceTagKey is present. + consts.ServiceTagKey: to.Ptr("default/test1"), + consts.LegacyServiceTagKey: to.Ptr("foo"), // It should be ignored when ServiceTagKey is present. }, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv4, - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, { - Name: ptr.To("pip2"), - Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, + Name: to.Ptr("pip2"), + Tags: map[string]*string{consts.ServiceTagKey: to.Ptr("default/test1")}, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv4, - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, { - Name: ptr.To("testPIP"), - Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, + Name: to.Ptr("testPIP"), + Tags: map[string]*string{consts.ServiceTagKey: to.Ptr("default/test1")}, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv4, - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, { - Name: ptr.To("testPIP-IPv6"), - Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, + Name: to.Ptr("testPIP-IPv6"), + Tags: map[string]*string{consts.ServiceTagKey: to.Ptr("default/test1")}, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv6, PublicIPAllocationMethod: network.Dynamic, - IPAddress: ptr.To("fd00::eef0"), + IPAddress: to.Ptr("fd00::eef0"), }, }, }, expectedPIPs: []*network.PublicIPAddress{ { - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP"), - Name: ptr.To("testPIP"), - Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP"), + Name: to.Ptr("testPIP"), + Tags: map[string]*string{consts.ServiceTagKey: to.Ptr("default/test1")}, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv4, PublicIPAllocationMethod: network.Static, IPTags: &[]network.IPTag{ { - IPTagType: ptr.To("tag1"), - Tag: ptr.To("tag1value"), + IPTagType: to.Ptr("tag1"), + Tag: to.Ptr("tag1value"), }, }, }, }, { - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP-IPv6"), - Name: ptr.To("testPIP-IPv6"), - Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP-IPv6"), + Name: to.Ptr("testPIP-IPv6"), + Tags: map[string]*string{consts.ServiceTagKey: to.Ptr("default/test1")}, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv6, PublicIPAllocationMethod: network.Dynamic, IPTags: &[]network.IPTag{ { - IPTagType: ptr.To("tag1"), - Tag: ptr.To("tag1value"), + IPTagType: to.Ptr("tag1"), + Tag: to.Ptr("tag1value"), }, }, }, @@ -4567,67 +4567,67 @@ func TestReconcilePublicIPsCommon(t *testing.T) { }, existingPIPs: []network.PublicIPAddress{ { - Name: ptr.To("testPIP"), - Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, + Name: to.Ptr("testPIP"), + Tags: map[string]*string{consts.ServiceTagKey: to.Ptr("default/test1")}, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv4, PublicIPAllocationMethod: network.Static, IPTags: &[]network.IPTag{ { - IPTagType: ptr.To("tag1"), - Tag: ptr.To("tag1value"), + IPTagType: to.Ptr("tag1"), + Tag: to.Ptr("tag1value"), }, }, - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, { - Name: ptr.To("testPIP-IPv6"), - Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, + Name: to.Ptr("testPIP-IPv6"), + Tags: map[string]*string{consts.ServiceTagKey: to.Ptr("default/test1")}, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv6, PublicIPAllocationMethod: network.Dynamic, IPTags: &[]network.IPTag{ { - IPTagType: ptr.To("tag1"), - Tag: ptr.To("tag1value"), + IPTagType: to.Ptr("tag1"), + Tag: to.Ptr("tag1value"), }, }, - IPAddress: ptr.To("fd00::eef0"), + IPAddress: to.Ptr("fd00::eef0"), }, }, }, expectedPIPs: []*network.PublicIPAddress{ { - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP"), - Name: ptr.To("testPIP"), - Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP"), + Name: to.Ptr("testPIP"), + Tags: map[string]*string{consts.ServiceTagKey: to.Ptr("default/test1")}, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv4, PublicIPAllocationMethod: network.Static, IPTags: &[]network.IPTag{ { - IPTagType: ptr.To("tag1"), - Tag: ptr.To("tag1value"), + IPTagType: to.Ptr("tag1"), + Tag: to.Ptr("tag1value"), }, }, - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, { - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP-IPv6"), - Name: ptr.To("testPIP-IPv6"), - Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP-IPv6"), + Name: to.Ptr("testPIP-IPv6"), + Tags: map[string]*string{consts.ServiceTagKey: to.Ptr("default/test1")}, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv6, PublicIPAllocationMethod: network.Dynamic, IPTags: &[]network.IPTag{ { - IPTagType: ptr.To("tag1"), - Tag: ptr.To("tag1value"), + IPTagType: to.Ptr("tag1"), + Tag: to.Ptr("tag1value"), }, }, - IPAddress: ptr.To("fd00::eef0"), + IPAddress: to.Ptr("fd00::eef0"), }, }, }, @@ -4643,61 +4643,61 @@ func TestReconcilePublicIPsCommon(t *testing.T) { }, existingPIPs: []network.PublicIPAddress{ { - Name: ptr.To("pip1"), + Name: to.Ptr("pip1"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv4, - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, { - Name: ptr.To("pip2"), - Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, + Name: to.Ptr("pip2"), + Tags: map[string]*string{consts.ServiceTagKey: to.Ptr("default/test1")}, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv4, - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, { - Name: ptr.To("testPIP"), + Name: to.Ptr("testPIP"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv4, - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, { - Name: ptr.To("pip2-IPv6"), - Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, + Name: to.Ptr("pip2-IPv6"), + Tags: map[string]*string{consts.ServiceTagKey: to.Ptr("default/test1")}, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv6, PublicIPAllocationMethod: network.Dynamic, - IPAddress: ptr.To("fd00::eef0"), + IPAddress: to.Ptr("fd00::eef0"), }, }, { - Name: ptr.To("testPIP-IPv6"), + Name: to.Ptr("testPIP-IPv6"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv6, PublicIPAllocationMethod: network.Dynamic, - IPAddress: ptr.To("fd00::eef0"), + IPAddress: to.Ptr("fd00::eef0"), }, }, }, expectedPIPs: []*network.PublicIPAddress{ { - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP"), - Name: ptr.To("testPIP"), + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP"), + Name: to.Ptr("testPIP"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv4, - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, { - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP-IPv6"), - Name: ptr.To("testPIP-IPv6"), + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testPIP-IPv6"), + Name: to.Ptr("testPIP-IPv6"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv6, PublicIPAllocationMethod: network.Dynamic, - IPAddress: ptr.To("fd00::eef0"), + IPAddress: to.Ptr("fd00::eef0"), }, }, }, @@ -4709,18 +4709,18 @@ func TestReconcilePublicIPsCommon(t *testing.T) { wantLb: false, existingPIPs: []network.PublicIPAddress{ { - Name: ptr.To("pip1"), - Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1,default/test2")}, + Name: to.Ptr("pip1"), + Tags: map[string]*string{consts.ServiceTagKey: to.Ptr("default/test1,default/test2")}, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), PublicIPAddressVersion: network.IPv4, }, }, { - Name: ptr.To("pip1-IPv6"), - Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1,default/test2")}, + Name: to.Ptr("pip1-IPv6"), + Tags: map[string]*string{consts.ServiceTagKey: to.Ptr("default/test1,default/test2")}, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("fd00::eef0"), + IPAddress: to.Ptr("fd00::eef0"), PublicIPAllocationMethod: network.Dynamic, PublicIPAddressVersion: network.IPv6, }, @@ -4733,12 +4733,12 @@ func TestReconcilePublicIPsCommon(t *testing.T) { wantLb: true, existingPIPs: []network.PublicIPAddress{ { - Name: ptr.To("testCluster-atest1"), - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testCluster-atest1"), - Tags: map[string]*string{consts.ServiceTagKey: ptr.To("default/test1")}, + Name: to.Ptr("testCluster-atest1"), + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/testCluster-atest1"), + Tags: map[string]*string{consts.ServiceTagKey: to.Ptr("default/test1")}, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv4, - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, }, @@ -4803,7 +4803,7 @@ func TestReconcilePublicIPsCommon(t *testing.T) { return nil }) - err := az.PublicIPAddressesClient.CreateOrUpdate(context.TODO(), "rg", ptr.Deref(pip.Name, ""), pip) + err := az.PublicIPAddressesClient.CreateOrUpdate(context.TODO(), "rg", lo.FromPtrOr(pip.Name, ""), pip) assert.NoError(t, err.Error()) // Clear create or update count to prepare for main execution @@ -4830,7 +4830,7 @@ func TestReconcilePublicIPsCommon(t *testing.T) { if len(test.expectedIDs) != 0 { ids := []string{} for _, pip := range pips { - ids = append(ids, ptr.Deref(pip.ID, "")) + ids = append(ids, lo.FromPtrOr(pip.ID, "")) } assert.Truef(t, compareStrings(test.expectedIDs, ids), "expectedIDs %q, IDs %q", test.expectedIDs, ids) @@ -4839,7 +4839,7 @@ func TestReconcilePublicIPsCommon(t *testing.T) { if len(test.expectedPIPs) != 0 { pipsNames := []string{} for _, pip := range pips { - pipsNames = append(pipsNames, ptr.Deref(pip.Name, "")) + pipsNames = append(pipsNames, lo.FromPtrOr(pip.Name, "")) } assert.Equal(t, len(test.expectedPIPs), len(pips), pipsNames) pipsOrdered := []*network.PublicIPAddress{} @@ -4847,7 +4847,7 @@ func TestReconcilePublicIPsCommon(t *testing.T) { pipsOrdered = append(pipsOrdered, pips[0]) } else { // len(test.expectedPIPs) == 2 - if ptr.Deref(test.expectedPIPs[0].Name, "") == ptr.Deref(pips[0].Name, "") { + if lo.FromPtrOr(test.expectedPIPs[0].Name, "") == lo.FromPtrOr(pips[0].Name, "") { pipsOrdered = append(pipsOrdered, pips...) } else { pipsOrdered = append(pipsOrdered, pips[1], pips[0]) @@ -4912,10 +4912,10 @@ func TestEnsurePublicIPExistsCommon(t *testing.T) { { desc: "shall return existed IPv4 PIP if there is any", pipName: "pip1", - existingPIPs: []network.PublicIPAddress{{Name: ptr.To("pip1")}}, + existingPIPs: []network.PublicIPAddress{{Name: to.Ptr("pip1")}}, expectedPIP: &network.PublicIPAddress{ - Name: ptr.To("pip1"), - ID: ptr.To(expectedPIPID), + Name: to.Ptr("pip1"), + ID: to.Ptr(expectedPIPID), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv4, PublicIPAllocationMethod: network.Static, @@ -4927,10 +4927,10 @@ func TestEnsurePublicIPExistsCommon(t *testing.T) { { desc: "shall return existed IPv6 PIP if there is any", pipName: "pip1-IPv6", - existingPIPs: []network.PublicIPAddress{{Name: ptr.To("pip1-IPv6")}}, + existingPIPs: []network.PublicIPAddress{{Name: to.Ptr("pip1-IPv6")}}, expectedPIP: &network.PublicIPAddress{ - Name: ptr.To("pip1-IPv6"), - ID: ptr.To(rgprefix + + Name: to.Ptr("pip1-IPv6"), + ID: to.Ptr(rgprefix + "/providers/Microsoft.Network/publicIPAddresses/pip1-IPv6"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv6, @@ -4954,19 +4954,19 @@ func TestEnsurePublicIPExistsCommon(t *testing.T) { inputDNSLabel: "newdns", foundDNSLabelAnnotation: true, existingPIPs: []network.PublicIPAddress{{ - Name: ptr.To("pip1"), + Name: to.Ptr("pip1"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{}, }}, expectedPIP: &network.PublicIPAddress{ - Name: ptr.To("pip1"), - ID: ptr.To(expectedPIPID), + Name: to.Ptr("pip1"), + ID: to.Ptr(expectedPIPID), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ DNSSettings: &network.PublicIPAddressDNSSettings{ - DomainNameLabel: ptr.To("newdns"), + DomainNameLabel: to.Ptr("newdns"), }, PublicIPAddressVersion: network.IPv4, }, - Tags: map[string]*string{consts.ServiceUsingDNSKey: ptr.To("default/test1")}, + Tags: map[string]*string{consts.ServiceUsingDNSKey: to.Ptr("default/test1")}, }, shouldPutPIP: true, }, @@ -4975,16 +4975,16 @@ func TestEnsurePublicIPExistsCommon(t *testing.T) { pipName: "pip1", foundDNSLabelAnnotation: true, existingPIPs: []network.PublicIPAddress{{ - Name: ptr.To("pip1"), + Name: to.Ptr("pip1"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ DNSSettings: &network.PublicIPAddressDNSSettings{ - DomainNameLabel: ptr.To("previousdns"), + DomainNameLabel: to.Ptr("previousdns"), }, }, }}, expectedPIP: &network.PublicIPAddress{ - Name: ptr.To("pip1"), - ID: ptr.To(expectedPIPID), + Name: to.Ptr("pip1"), + ID: to.Ptr(expectedPIPID), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ DNSSettings: nil, PublicIPAddressVersion: network.IPv4, @@ -4998,19 +4998,19 @@ func TestEnsurePublicIPExistsCommon(t *testing.T) { pipName: "pip1", foundDNSLabelAnnotation: false, existingPIPs: []network.PublicIPAddress{{ - Name: ptr.To("pip1"), + Name: to.Ptr("pip1"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ DNSSettings: &network.PublicIPAddressDNSSettings{ - DomainNameLabel: ptr.To("previousdns"), + DomainNameLabel: to.Ptr("previousdns"), }, }, }}, expectedPIP: &network.PublicIPAddress{ - Name: ptr.To("pip1"), - ID: ptr.To(expectedPIPID), + Name: to.Ptr("pip1"), + ID: to.Ptr(expectedPIPID), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ DNSSettings: &network.PublicIPAddressDNSSettings{ - DomainNameLabel: ptr.To("previousdns"), + DomainNameLabel: to.Ptr("previousdns"), }, PublicIPAddressVersion: network.IPv4, }, @@ -5023,20 +5023,20 @@ func TestEnsurePublicIPExistsCommon(t *testing.T) { foundDNSLabelAnnotation: true, isIPv6: true, existingPIPs: []network.PublicIPAddress{{ - Name: ptr.To("pip1"), + Name: to.Ptr("pip1"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{}, }}, expectedPIP: &network.PublicIPAddress{ - Name: ptr.To("pip1"), - ID: ptr.To(expectedPIPID), + Name: to.Ptr("pip1"), + ID: to.Ptr(expectedPIPID), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ DNSSettings: &network.PublicIPAddressDNSSettings{ - DomainNameLabel: ptr.To("newdns"), + DomainNameLabel: to.Ptr("newdns"), }, PublicIPAllocationMethod: network.Dynamic, PublicIPAddressVersion: network.IPv6, }, - Tags: map[string]*string{consts.ServiceUsingDNSKey: ptr.To("default/test1")}, + Tags: map[string]*string{consts.ServiceUsingDNSKey: to.Ptr("default/test1")}, }, shouldPutPIP: true, }, @@ -5047,25 +5047,25 @@ func TestEnsurePublicIPExistsCommon(t *testing.T) { foundDNSLabelAnnotation: true, isIPv6: true, existingPIPs: []network.PublicIPAddress{{ - Name: ptr.To("pip1"), + Name: to.Ptr("pip1"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ DNSSettings: &network.PublicIPAddressDNSSettings{ - DomainNameLabel: ptr.To("previousdns"), + DomainNameLabel: to.Ptr("previousdns"), }, }, }}, expectedPIP: &network.PublicIPAddress{ - Name: ptr.To("pip1"), - ID: ptr.To(expectedPIPID), + Name: to.Ptr("pip1"), + ID: to.Ptr(expectedPIPID), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ DNSSettings: &network.PublicIPAddressDNSSettings{ - DomainNameLabel: ptr.To("newdns"), + DomainNameLabel: to.Ptr("newdns"), }, PublicIPAllocationMethod: network.Dynamic, PublicIPAddressVersion: network.IPv6, }, Tags: map[string]*string{ - "k8s-azure-dns-label-service": ptr.To("default/test1"), + "k8s-azure-dns-label-service": to.Ptr("default/test1"), }, }, shouldPutPIP: true, @@ -5077,27 +5077,27 @@ func TestEnsurePublicIPExistsCommon(t *testing.T) { foundDNSLabelAnnotation: true, isIPv6: false, existingPIPs: []network.PublicIPAddress{{ - Name: ptr.To("pip1"), + Name: to.Ptr("pip1"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ DNSSettings: &network.PublicIPAddressDNSSettings{ - DomainNameLabel: ptr.To("previousdns"), + DomainNameLabel: to.Ptr("previousdns"), }, PublicIPAllocationMethod: network.Dynamic, PublicIPAddressVersion: network.IPv4, }, }}, expectedPIP: &network.PublicIPAddress{ - Name: ptr.To("pip1"), - ID: ptr.To(expectedPIPID), + Name: to.Ptr("pip1"), + ID: to.Ptr(expectedPIPID), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ DNSSettings: &network.PublicIPAddressDNSSettings{ - DomainNameLabel: ptr.To("newdns"), + DomainNameLabel: to.Ptr("newdns"), }, PublicIPAllocationMethod: network.Dynamic, PublicIPAddressVersion: network.IPv4, }, Tags: map[string]*string{ - "k8s-azure-dns-label-service": ptr.To("default/test1"), + "k8s-azure-dns-label-service": to.Ptr("default/test1"), }, }, shouldPutPIP: true, @@ -5108,11 +5108,11 @@ func TestEnsurePublicIPExistsCommon(t *testing.T) { inputDNSLabel: "test", foundDNSLabelAnnotation: true, existingPIPs: []network.PublicIPAddress{{ - Name: ptr.To("pip1"), - Tags: map[string]*string{consts.ServiceUsingDNSKey: ptr.To("test1")}, + Name: to.Ptr("pip1"), + Tags: map[string]*string{consts.ServiceUsingDNSKey: to.Ptr("test1")}, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ DNSSettings: &network.PublicIPAddressDNSSettings{ - DomainNameLabel: ptr.To("previousdns"), + DomainNameLabel: to.Ptr("previousdns"), }, }, }}, @@ -5124,15 +5124,15 @@ func TestEnsurePublicIPExistsCommon(t *testing.T) { inputDNSLabel: "test", existingPIPs: []network.PublicIPAddress{ { - Name: ptr.To("pip1"), - ID: ptr.To(expectedPIPID), + Name: to.Ptr("pip1"), + ID: to.Ptr(expectedPIPID), Tags: map[string]*string{ - consts.ServiceUsingDNSKey: ptr.To("default/test1"), - consts.ServiceTagKey: ptr.To("default/test1"), + consts.ServiceUsingDNSKey: to.Ptr("default/test1"), + consts.ServiceTagKey: to.Ptr("default/test1"), }, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ DNSSettings: &network.PublicIPAddressDNSSettings{ - DomainNameLabel: ptr.To("test"), + DomainNameLabel: to.Ptr("test"), }, PublicIPAllocationMethod: network.Static, PublicIPAddressVersion: network.IPv4, @@ -5140,15 +5140,15 @@ func TestEnsurePublicIPExistsCommon(t *testing.T) { }, }, expectedPIP: &network.PublicIPAddress{ - Name: ptr.To("pip1"), - ID: ptr.To(expectedPIPID), + Name: to.Ptr("pip1"), + ID: to.Ptr(expectedPIPID), Tags: map[string]*string{ - consts.ServiceUsingDNSKey: ptr.To("default/test1"), - consts.ServiceTagKey: ptr.To("default/test1"), + consts.ServiceUsingDNSKey: to.Ptr("default/test1"), + consts.ServiceTagKey: to.Ptr("default/test1"), }, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ DNSSettings: &network.PublicIPAddressDNSSettings{ - DomainNameLabel: ptr.To("test"), + DomainNameLabel: to.Ptr("test"), }, PublicIPAllocationMethod: network.Static, PublicIPAddressVersion: network.IPv4, @@ -5159,11 +5159,11 @@ func TestEnsurePublicIPExistsCommon(t *testing.T) { desc: "shall tag the service name to the pip correctly", pipName: "pip1", existingPIPs: []network.PublicIPAddress{ - {Name: ptr.To("pip1")}, + {Name: to.Ptr("pip1")}, }, expectedPIP: &network.PublicIPAddress{ - Name: ptr.To("pip1"), - ID: ptr.To(expectedPIPID), + Name: to.Ptr("pip1"), + ID: to.Ptr(expectedPIPID), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv4, PublicIPAllocationMethod: network.Static, @@ -5179,7 +5179,7 @@ func TestEnsurePublicIPExistsCommon(t *testing.T) { useSLB: true, existingPIPs: []network.PublicIPAddress{ { - Name: ptr.To("pip1"), + Name: to.Ptr("pip1"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv6, PublicIPAllocationMethod: network.Static, @@ -5187,8 +5187,8 @@ func TestEnsurePublicIPExistsCommon(t *testing.T) { }, }, expectedPIP: &network.PublicIPAddress{ - Name: ptr.To("pip1"), - ID: ptr.To(expectedPIPID), + Name: to.Ptr("pip1"), + ID: to.Ptr(expectedPIPID), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv6, PublicIPAllocationMethod: network.Static, @@ -5200,11 +5200,11 @@ func TestEnsurePublicIPExistsCommon(t *testing.T) { { desc: "shall update pip tags if there is any change", pipName: "pip1", - existingPIPs: []network.PublicIPAddress{{Name: ptr.To("pip1"), Tags: map[string]*string{"a": ptr.To("b")}}}, + existingPIPs: []network.PublicIPAddress{{Name: to.Ptr("pip1"), Tags: map[string]*string{"a": to.Ptr("b")}}}, expectedPIP: &network.PublicIPAddress{ - Name: ptr.To("pip1"), - Tags: map[string]*string{"a": ptr.To("c")}, - ID: ptr.To(expectedPIPID), + Name: to.Ptr("pip1"), + Tags: map[string]*string{"a": to.Ptr("c")}, + ID: to.Ptr(expectedPIPID), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv4, PublicIPAllocationMethod: network.Static, @@ -5220,21 +5220,21 @@ func TestEnsurePublicIPExistsCommon(t *testing.T) { pipName: "pip1", existingPIPs: []network.PublicIPAddress{ { - Name: ptr.To("pip1"), + Name: to.Ptr("pip1"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv4, - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, - Tags: map[string]*string{"a": ptr.To("b")}, + Tags: map[string]*string{"a": to.Ptr("b")}, }, }, expectedPIP: &network.PublicIPAddress{ - Name: ptr.To("pip1"), - Tags: map[string]*string{"a": ptr.To("b")}, - ID: ptr.To(expectedPIPID), + Name: to.Ptr("pip1"), + Tags: map[string]*string{"a": to.Ptr("b")}, + ID: to.Ptr(expectedPIPID), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv4, - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, additionalAnnotations: map[string]string{ @@ -5270,13 +5270,13 @@ func TestEnsurePublicIPExistsCommon(t *testing.T) { var basicPIP *network.PublicIPAddress if len(test.existingPIPs) == 0 { basicPIP = &network.PublicIPAddress{ - Name: ptr.To(test.pipName), + Name: to.Ptr(test.pipName), } } else { basicPIP = &test.existingPIPs[0] } - basicPIP.ID = ptr.To(rgprefix + + basicPIP.ID = to.Ptr(rgprefix + "/providers/Microsoft.Network/publicIPAddresses/" + test.pipName) if basicPIP.PublicIPAddressPropertiesFormat == nil { @@ -5296,7 +5296,7 @@ func TestEnsurePublicIPExistsCommon(t *testing.T) { pip, err := az.ensurePublicIPExists(context.TODO(), &service, test.pipName, test.inputDNSLabel, "", false, test.foundDNSLabelAnnotation, test.isIPv6) assert.Equal(t, test.expectedError, err != nil, "unexpectedly encountered (or not) error: %v", err) if test.expectedID != "" { - assert.Equal(t, test.expectedID, ptr.Deref(pip.ID, "")) + assert.Equal(t, test.expectedID, lo.FromPtrOr(pip.ID, "")) } else { assert.Equal(t, test.expectedPIP, pip) } @@ -5324,10 +5324,10 @@ func TestEnsurePublicIPExistsWithExtendedLocation(t *testing.T) { desc: "should create a pip with extended location", pipName: "pip1", expectedPIP: &network.PublicIPAddress{ - Name: ptr.To("pip1"), + Name: to.Ptr("pip1"), Location: &az.Location, ExtendedLocation: &network.ExtendedLocation{ - Name: ptr.To("microsoftlosangeles1"), + Name: to.Ptr("microsoftlosangeles1"), Type: network.EdgeZone, }, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ @@ -5336,8 +5336,8 @@ func TestEnsurePublicIPExistsWithExtendedLocation(t *testing.T) { ProvisioningState: "", }, Tags: map[string]*string{ - consts.ServiceTagKey: ptr.To("default/test1"), - consts.ClusterNameKey: ptr.To(""), + consts.ServiceTagKey: to.Ptr("default/test1"), + consts.ClusterNameKey: to.Ptr(""), }, }, isIPv6: false, @@ -5346,10 +5346,10 @@ func TestEnsurePublicIPExistsWithExtendedLocation(t *testing.T) { desc: "should create a pip with extended location for IPv6", pipName: "pip1-IPv6", expectedPIP: &network.PublicIPAddress{ - Name: ptr.To("pip1-IPv6"), + Name: to.Ptr("pip1-IPv6"), Location: &az.Location, ExtendedLocation: &network.ExtendedLocation{ - Name: ptr.To("microsoftlosangeles1"), + Name: to.Ptr("microsoftlosangeles1"), Type: network.EdgeZone, }, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ @@ -5358,8 +5358,8 @@ func TestEnsurePublicIPExistsWithExtendedLocation(t *testing.T) { ProvisioningState: "", }, Tags: map[string]*string{ - consts.ServiceTagKey: ptr.To("default/test1"), - consts.ClusterNameKey: ptr.To(""), + consts.ServiceTagKey: to.Ptr("default/test1"), + consts.ClusterNameKey: to.Ptr(""), }, }, isIPv6: true, @@ -5456,13 +5456,13 @@ func TestShouldUpdateLoadBalancer(t *testing.T) { } if test.existsLb { lb := network.LoadBalancer{ - Name: ptr.To("vmas"), + Name: to.Ptr("vmas"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ FrontendIPConfigurations: &[]network.FrontendIPConfiguration{ { - Name: ptr.To("atest1"), + Name: to.Ptr("atest1"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To("testCluster-aservice1")}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr("testCluster-aservice1")}, }, }, }, @@ -5578,10 +5578,10 @@ func TestIsBackendPoolPreConfigured(t *testing.T) { func TestParsePIPServiceTag(t *testing.T) { tags := []*string{ - ptr.To("ns1/svc1,ns2/svc2"), - ptr.To(" ns1/svc1, ns2/svc2 "), - ptr.To("ns1/svc1,"), - ptr.To(""), + to.Ptr("ns1/svc1,ns2/svc2"), + to.Ptr(" ns1/svc1, ns2/svc2 "), + to.Ptr("ns1/svc1,"), + to.Ptr(""), nil, } expectedNames := [][]string{ @@ -5602,17 +5602,17 @@ func TestBindServicesToPIP(t *testing.T) { pips := []*network.PublicIPAddress{ {Tags: nil}, {Tags: map[string]*string{}}, - {Tags: map[string]*string{consts.ServiceTagKey: ptr.To("ns1/svc1")}}, - {Tags: map[string]*string{consts.ServiceTagKey: ptr.To("ns1/svc1,ns2/svc2")}}, - {Tags: map[string]*string{consts.ServiceTagKey: ptr.To("ns2/svc2,ns3/svc3")}}, + {Tags: map[string]*string{consts.ServiceTagKey: to.Ptr("ns1/svc1")}}, + {Tags: map[string]*string{consts.ServiceTagKey: to.Ptr("ns1/svc1,ns2/svc2")}}, + {Tags: map[string]*string{consts.ServiceTagKey: to.Ptr("ns2/svc2,ns3/svc3")}}, } serviceNames := []string{"ns2/svc2", "ns3/svc3"} expectedTags := []map[string]*string{ - {consts.ServiceTagKey: ptr.To("ns2/svc2,ns3/svc3")}, - {consts.ServiceTagKey: ptr.To("ns2/svc2,ns3/svc3")}, - {consts.ServiceTagKey: ptr.To("ns1/svc1,ns2/svc2,ns3/svc3")}, - {consts.ServiceTagKey: ptr.To("ns1/svc1,ns2/svc2,ns3/svc3")}, - {consts.ServiceTagKey: ptr.To("ns2/svc2,ns3/svc3")}, + {consts.ServiceTagKey: to.Ptr("ns2/svc2,ns3/svc3")}, + {consts.ServiceTagKey: to.Ptr("ns2/svc2,ns3/svc3")}, + {consts.ServiceTagKey: to.Ptr("ns1/svc1,ns2/svc2,ns3/svc3")}, + {consts.ServiceTagKey: to.Ptr("ns1/svc1,ns2/svc2,ns3/svc3")}, + {consts.ServiceTagKey: to.Ptr("ns2/svc2,ns3/svc3")}, } flags := []bool{true, true, true, true, false} @@ -5646,30 +5646,30 @@ func TestUnbindServiceFromPIP(t *testing.T) { { Name: "Single service", InputTags: map[string]*string{ - consts.ServiceTagKey: ptr.To("ns1/svc1"), + consts.ServiceTagKey: to.Ptr("ns1/svc1"), }, ExpectedTags: map[string]*string{ - consts.ServiceTagKey: ptr.To("ns1/svc1"), + consts.ServiceTagKey: to.Ptr("ns1/svc1"), }, ExpectedServiceReferences: []string{"ns1/svc1"}, }, { Name: "Multiple services #1", InputTags: map[string]*string{ - consts.ServiceTagKey: ptr.To("ns1/svc1,ns2/svc2"), + consts.ServiceTagKey: to.Ptr("ns1/svc1,ns2/svc2"), }, ExpectedTags: map[string]*string{ - consts.ServiceTagKey: ptr.To("ns1/svc1"), + consts.ServiceTagKey: to.Ptr("ns1/svc1"), }, ExpectedServiceReferences: []string{"ns1/svc1"}, }, { Name: "Multiple services #2", InputTags: map[string]*string{ - consts.ServiceTagKey: ptr.To("ns1/svc1,ns2/svc2,ns3/svc3"), + consts.ServiceTagKey: to.Ptr("ns1/svc1,ns2/svc2,ns3/svc3"), }, ExpectedTags: map[string]*string{ - consts.ServiceTagKey: ptr.To("ns1/svc1,ns3/svc3"), + consts.ServiceTagKey: to.Ptr("ns1/svc1,ns3/svc3"), }, ExpectedServiceReferences: []string{"ns1/svc1", "ns3/svc3"}, }, @@ -5702,7 +5702,7 @@ func TestIsFrontendIPConfigIsUnsafeToDelete(t *testing.T) { service := getTestService("service1", v1.ProtocolTCP, nil, false, 80) az := GetTestCloud(ctrl) - fipID := ptr.To("fip") + fipID := to.Ptr("fip") testCases := []struct { desc string @@ -5713,13 +5713,13 @@ func TestIsFrontendIPConfigIsUnsafeToDelete(t *testing.T) { desc: "isFrontendIPConfigUnsafeToDelete should return true if there is a " + "loadBalancing rule from other service referencing the frontend IP config", existingLB: &network.LoadBalancer{ - Name: ptr.To("lb"), + Name: to.Ptr("lb"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ LoadBalancingRules: &[]network.LoadBalancingRule{ { - Name: ptr.To("aservice2-rule"), + Name: to.Ptr("aservice2-rule"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - FrontendIPConfiguration: &network.SubResource{ID: ptr.To("fip")}, + FrontendIPConfiguration: &network.SubResource{ID: to.Ptr("fip")}, }, }, }, @@ -5731,14 +5731,14 @@ func TestIsFrontendIPConfigIsUnsafeToDelete(t *testing.T) { desc: "isFrontendIPConfigUnsafeToDelete should return true if there is a " + "outbound rule referencing the frontend IP config", existingLB: &network.LoadBalancer{ - Name: ptr.To("lb"), + Name: to.Ptr("lb"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ OutboundRules: &[]network.OutboundRule{ { - Name: ptr.To("aservice1-rule"), + Name: to.Ptr("aservice1-rule"), OutboundRulePropertiesFormat: &network.OutboundRulePropertiesFormat{ FrontendIPConfigurations: &[]network.SubResource{ - {ID: ptr.To("fip")}, + {ID: to.Ptr("fip")}, }, }, }, @@ -5751,13 +5751,13 @@ func TestIsFrontendIPConfigIsUnsafeToDelete(t *testing.T) { desc: "isFrontendIPConfigUnsafeToDelete should return false if there is a " + "loadBalancing rule from this service referencing the frontend IP config", existingLB: &network.LoadBalancer{ - Name: ptr.To("lb"), + Name: to.Ptr("lb"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ LoadBalancingRules: &[]network.LoadBalancingRule{ { - Name: ptr.To("aservice1-rule"), + Name: to.Ptr("aservice1-rule"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - FrontendIPConfiguration: &network.SubResource{ID: ptr.To("fip")}, + FrontendIPConfiguration: &network.SubResource{ID: to.Ptr("fip")}, }, }, }, @@ -5768,13 +5768,13 @@ func TestIsFrontendIPConfigIsUnsafeToDelete(t *testing.T) { desc: "isFrontendIPConfigUnsafeToDelete should return true if there is a " + "inbound NAT rule referencing the frontend IP config", existingLB: &network.LoadBalancer{ - Name: ptr.To("lb"), + Name: to.Ptr("lb"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ InboundNatRules: &[]network.InboundNatRule{ { - Name: ptr.To("aservice2-rule"), + Name: to.Ptr("aservice2-rule"), InboundNatRulePropertiesFormat: &network.InboundNatRulePropertiesFormat{ - FrontendIPConfiguration: &network.SubResource{ID: ptr.To("fip")}, + FrontendIPConfiguration: &network.SubResource{ID: to.Ptr("fip")}, }, }, }, @@ -5786,13 +5786,13 @@ func TestIsFrontendIPConfigIsUnsafeToDelete(t *testing.T) { desc: "isFrontendIPConfigUnsafeToDelete should return true if there is a " + "inbound NAT pool referencing the frontend IP config", existingLB: &network.LoadBalancer{ - Name: ptr.To("lb"), + Name: to.Ptr("lb"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ InboundNatPools: &[]network.InboundNatPool{ { - Name: ptr.To("aservice2-rule"), + Name: to.Ptr("aservice2-rule"), InboundNatPoolPropertiesFormat: &network.InboundNatPoolPropertiesFormat{ - FrontendIPConfiguration: &network.SubResource{ID: ptr.To("fip")}, + FrontendIPConfiguration: &network.SubResource{ID: to.Ptr("fip")}, }, }, }, @@ -5826,22 +5826,22 @@ func TestCheckLoadBalancerResourcesConflicted(t *testing.T) { "there is a conflicted loadBalancing rule - IPv4", fipID: "fip", existingLB: &network.LoadBalancer{ - Name: ptr.To("lb"), + Name: to.Ptr("lb"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ LoadBalancingRules: &[]network.LoadBalancingRule{ { - Name: ptr.To("aservice2-rule"), + Name: to.Ptr("aservice2-rule"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - FrontendIPConfiguration: &network.SubResource{ID: ptr.To("fip")}, - FrontendPort: ptr.To(int32(80)), + FrontendIPConfiguration: &network.SubResource{ID: to.Ptr("fip")}, + FrontendPort: to.Ptr(int32(80)), Protocol: network.TransportProtocol(v1.ProtocolTCP), }, }, { - Name: ptr.To("aservice2-rule-IPv6"), + Name: to.Ptr("aservice2-rule-IPv6"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - FrontendIPConfiguration: &network.SubResource{ID: ptr.To("fip-IPv6")}, - FrontendPort: ptr.To(int32(80)), + FrontendIPConfiguration: &network.SubResource{ID: to.Ptr("fip-IPv6")}, + FrontendPort: to.Ptr(int32(80)), Protocol: network.TransportProtocol(v1.ProtocolTCP), }, }, @@ -5855,22 +5855,22 @@ func TestCheckLoadBalancerResourcesConflicted(t *testing.T) { "there is a conflicted loadBalancing rule - IPv6", fipID: "fip-IPv6", existingLB: &network.LoadBalancer{ - Name: ptr.To("lb"), + Name: to.Ptr("lb"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ LoadBalancingRules: &[]network.LoadBalancingRule{ { - Name: ptr.To("aservice2-rule"), + Name: to.Ptr("aservice2-rule"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - FrontendIPConfiguration: &network.SubResource{ID: ptr.To("fip")}, - FrontendPort: ptr.To(int32(80)), + FrontendIPConfiguration: &network.SubResource{ID: to.Ptr("fip")}, + FrontendPort: to.Ptr(int32(80)), Protocol: network.TransportProtocol(v1.ProtocolTCP), }, }, { - Name: ptr.To("aservice2-rule-IPv6"), + Name: to.Ptr("aservice2-rule-IPv6"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - FrontendIPConfiguration: &network.SubResource{ID: ptr.To("fip-IPv6")}, - FrontendPort: ptr.To(int32(80)), + FrontendIPConfiguration: &network.SubResource{ID: to.Ptr("fip-IPv6")}, + FrontendPort: to.Ptr(int32(80)), Protocol: network.TransportProtocol(v1.ProtocolTCP), }, }, @@ -5884,14 +5884,14 @@ func TestCheckLoadBalancerResourcesConflicted(t *testing.T) { "there is a conflicted inbound NAT rule", fipID: "fip", existingLB: &network.LoadBalancer{ - Name: ptr.To("lb"), + Name: to.Ptr("lb"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ InboundNatRules: &[]network.InboundNatRule{ { - Name: ptr.To("aservice1-rule"), + Name: to.Ptr("aservice1-rule"), InboundNatRulePropertiesFormat: &network.InboundNatRulePropertiesFormat{ - FrontendIPConfiguration: &network.SubResource{ID: ptr.To("fip")}, - FrontendPort: ptr.To(int32(80)), + FrontendIPConfiguration: &network.SubResource{ID: to.Ptr("fip")}, + FrontendPort: to.Ptr(int32(80)), Protocol: network.TransportProtocol(v1.ProtocolTCP), }, }, @@ -5905,15 +5905,15 @@ func TestCheckLoadBalancerResourcesConflicted(t *testing.T) { "there is a conflicted inbound NAT pool", fipID: "fip", existingLB: &network.LoadBalancer{ - Name: ptr.To("lb"), + Name: to.Ptr("lb"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ InboundNatPools: &[]network.InboundNatPool{ { - Name: ptr.To("aservice1-rule"), + Name: to.Ptr("aservice1-rule"), InboundNatPoolPropertiesFormat: &network.InboundNatPoolPropertiesFormat{ - FrontendIPConfiguration: &network.SubResource{ID: ptr.To("fip")}, - FrontendPortRangeStart: ptr.To(int32(80)), - FrontendPortRangeEnd: ptr.To(int32(90)), + FrontendIPConfiguration: &network.SubResource{ID: to.Ptr("fip")}, + FrontendPortRangeStart: to.Ptr(int32(80)), + FrontendPortRangeEnd: to.Ptr(int32(90)), Protocol: network.TransportProtocol(v1.ProtocolTCP), }, }, @@ -5927,35 +5927,35 @@ func TestCheckLoadBalancerResourcesConflicted(t *testing.T) { "is no conflicted loadBalancer resources", fipID: "fip", existingLB: &network.LoadBalancer{ - Name: ptr.To("lb"), + Name: to.Ptr("lb"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ LoadBalancingRules: &[]network.LoadBalancingRule{ { - Name: ptr.To("aservice2-rule"), + Name: to.Ptr("aservice2-rule"), LoadBalancingRulePropertiesFormat: &network.LoadBalancingRulePropertiesFormat{ - FrontendIPConfiguration: &network.SubResource{ID: ptr.To("fip")}, - FrontendPort: ptr.To(int32(90)), + FrontendIPConfiguration: &network.SubResource{ID: to.Ptr("fip")}, + FrontendPort: to.Ptr(int32(90)), Protocol: network.TransportProtocol(v1.ProtocolTCP), }, }, }, InboundNatRules: &[]network.InboundNatRule{ { - Name: ptr.To("aservice1-rule"), + Name: to.Ptr("aservice1-rule"), InboundNatRulePropertiesFormat: &network.InboundNatRulePropertiesFormat{ - FrontendIPConfiguration: &network.SubResource{ID: ptr.To("fip")}, - FrontendPort: ptr.To(int32(90)), + FrontendIPConfiguration: &network.SubResource{ID: to.Ptr("fip")}, + FrontendPort: to.Ptr(int32(90)), Protocol: network.TransportProtocol(v1.ProtocolTCP), }, }, }, InboundNatPools: &[]network.InboundNatPool{ { - Name: ptr.To("aservice1-rule"), + Name: to.Ptr("aservice1-rule"), InboundNatPoolPropertiesFormat: &network.InboundNatPoolPropertiesFormat{ - FrontendIPConfiguration: &network.SubResource{ID: ptr.To("fip")}, - FrontendPortRangeStart: ptr.To(int32(800)), - FrontendPortRangeEnd: ptr.To(int32(900)), + FrontendIPConfiguration: &network.SubResource{ID: to.Ptr("fip")}, + FrontendPortRangeStart: to.Ptr(int32(800)), + FrontendPortRangeEnd: to.Ptr(int32(900)), Protocol: network.TransportProtocol(v1.ProtocolTCP), }, }, @@ -5975,11 +5975,11 @@ func TestCheckLoadBalancerResourcesConflicted(t *testing.T) { func buildLBWithVMIPs(clusterName string, vmIPs []string) *network.LoadBalancer { lb := network.LoadBalancer{ - Name: ptr.To(clusterName), + Name: to.Ptr(clusterName), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ BackendAddressPools: &[]network.BackendAddressPool{ { - Name: ptr.To(clusterName), + Name: to.Ptr(clusterName), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{}, }, @@ -5994,7 +5994,7 @@ func buildLBWithVMIPs(clusterName string, vmIPs []string) *network.LoadBalancer LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ IPAddress: &vmIP, VirtualNetwork: &network.SubResource{ - ID: ptr.To("vnet"), + ID: to.Ptr("vnet"), }, }, }) @@ -6005,11 +6005,11 @@ func buildLBWithVMIPs(clusterName string, vmIPs []string) *network.LoadBalancer func buildDefaultTestLB(name string, backendIPConfigs []string) network.LoadBalancer { expectedLB := network.LoadBalancer{ - Name: ptr.To(name), + Name: to.Ptr(name), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ BackendAddressPools: &[]network.BackendAddressPool{ { - Name: ptr.To(name), + Name: to.Ptr(name), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ BackendIPConfigurations: &[]network.InterfaceIPConfiguration{}, }, @@ -6019,7 +6019,7 @@ func buildDefaultTestLB(name string, backendIPConfigs []string) network.LoadBala } backendIPConfigurations := make([]network.InterfaceIPConfiguration, 0) for _, ipConfig := range backendIPConfigs { - backendIPConfigurations = append(backendIPConfigurations, network.InterfaceIPConfiguration{ID: ptr.To(ipConfig)}) + backendIPConfigurations = append(backendIPConfigurations, network.InterfaceIPConfiguration{ID: to.Ptr(ipConfig)}) } (*expectedLB.BackendAddressPools)[0].BackendIPConfigurations = &backendIPConfigurations return expectedLB @@ -6041,27 +6041,27 @@ func TestEnsurePIPTagged(t *testing.T) { } pip := network.PublicIPAddress{ Tags: map[string]*string{ - consts.ClusterNameKey: ptr.To("testCluster"), - consts.ServiceTagKey: ptr.To("default/svc1,default/svc2"), - consts.ServiceUsingDNSKey: ptr.To("default/svc1"), - "foo": ptr.To("bar"), - "a": ptr.To("j"), - "m": ptr.To("n"), + consts.ClusterNameKey: to.Ptr("testCluster"), + consts.ServiceTagKey: to.Ptr("default/svc1,default/svc2"), + consts.ServiceUsingDNSKey: to.Ptr("default/svc1"), + "foo": to.Ptr("bar"), + "a": to.Ptr("j"), + "m": to.Ptr("n"), }, } t.Run("ensurePIPTagged should ensure the pip is tagged as configured", func(t *testing.T) { expectedPIP := network.PublicIPAddress{ Tags: map[string]*string{ - consts.ClusterNameKey: ptr.To("testCluster"), - consts.ServiceTagKey: ptr.To("default/svc1,default/svc2"), - consts.ServiceUsingDNSKey: ptr.To("default/svc1"), - "foo": ptr.To("bar"), - "a": ptr.To("b"), - "c": ptr.To("d"), - "y": ptr.To("z"), - "m": ptr.To("n"), - "e": ptr.To(""), + consts.ClusterNameKey: to.Ptr("testCluster"), + consts.ServiceTagKey: to.Ptr("default/svc1,default/svc2"), + consts.ServiceUsingDNSKey: to.Ptr("default/svc1"), + "foo": to.Ptr("bar"), + "a": to.Ptr("b"), + "c": to.Ptr("d"), + "y": to.Ptr("z"), + "m": to.Ptr("n"), + "e": to.Ptr(""), }, } changed := cloud.ensurePIPTagged(&service, &pip) @@ -6073,14 +6073,14 @@ func TestEnsurePIPTagged(t *testing.T) { cloud.SystemTags = "a,foo" expectedPIP := network.PublicIPAddress{ Tags: map[string]*string{ - consts.ClusterNameKey: ptr.To("testCluster"), - consts.ServiceTagKey: ptr.To("default/svc1,default/svc2"), - consts.ServiceUsingDNSKey: ptr.To("default/svc1"), - "foo": ptr.To("bar"), - "a": ptr.To("b"), - "c": ptr.To("d"), - "y": ptr.To("z"), - "e": ptr.To(""), + consts.ClusterNameKey: to.Ptr("testCluster"), + consts.ServiceTagKey: to.Ptr("default/svc1,default/svc2"), + consts.ServiceUsingDNSKey: to.Ptr("default/svc1"), + "foo": to.Ptr("bar"), + "a": to.Ptr("b"), + "c": to.Ptr("d"), + "y": to.Ptr("z"), + "e": to.Ptr(""), }, } changed := cloud.ensurePIPTagged(&service, &pip) @@ -6093,14 +6093,14 @@ func TestEnsurePIPTagged(t *testing.T) { cloud.TagsMap = map[string]string{"a": "c", "a=b": "c=d", "Y": "zz"} expectedPIP := network.PublicIPAddress{ Tags: map[string]*string{ - consts.ClusterNameKey: ptr.To("testCluster"), - consts.ServiceTagKey: ptr.To("default/svc1,default/svc2"), - consts.ServiceUsingDNSKey: ptr.To("default/svc1"), - "foo": ptr.To("bar"), - "a": ptr.To("b"), - "c": ptr.To("d"), - "a=b": ptr.To("c=d"), - "e": ptr.To(""), + consts.ClusterNameKey: to.Ptr("testCluster"), + consts.ServiceTagKey: to.Ptr("default/svc1,default/svc2"), + consts.ServiceUsingDNSKey: to.Ptr("default/svc1"), + "foo": to.Ptr("bar"), + "a": to.Ptr("b"), + "c": to.Ptr("d"), + "a=b": to.Ptr("c=d"), + "e": to.Ptr(""), }, } changed := cloud.ensurePIPTagged(&service, &pip) @@ -6121,17 +6121,17 @@ func TestEnsureLoadBalancerTagged(t *testing.T) { }{ { description: "ensureLoadBalancerTagged should not delete the old tags if SystemTags is not specified", - existedTags: map[string]*string{"a": ptr.To("b")}, + existedTags: map[string]*string{"a": to.Ptr("b")}, newTags: "c=d", - expectedTags: map[string]*string{"a": ptr.To("b"), "c": ptr.To("d")}, + expectedTags: map[string]*string{"a": to.Ptr("b"), "c": to.Ptr("d")}, expectedChanged: true, }, { description: "ensureLoadBalancerTagged should delete the old tags if SystemTags is specified", - existedTags: map[string]*string{"a": ptr.To("b"), "c": ptr.To("d"), "h": ptr.To("i")}, + existedTags: map[string]*string{"a": to.Ptr("b"), "c": to.Ptr("d"), "h": to.Ptr("i")}, newTags: "c=e,f=g", systemTags: "a,x,y,z", - expectedTags: map[string]*string{"a": ptr.To("b"), "c": ptr.To("e"), "f": ptr.To("g")}, + expectedTags: map[string]*string{"a": to.Ptr("b"), "c": to.Ptr("e"), "f": to.Ptr("g")}, expectedChanged: true, }, } { @@ -6153,11 +6153,11 @@ func TestRemoveFrontendIPConfigurationFromLoadBalancerDelete(t *testing.T) { defer ctrl.Finish() t.Run("removeFrontendIPConfigurationFromLoadBalancer should remove the unwanted frontend IP configuration and delete the orphaned LB", func(t *testing.T) { fip := &network.FrontendIPConfiguration{ - Name: ptr.To("testCluster"), - ID: ptr.To("testCluster-fip"), + Name: to.Ptr("testCluster"), + ID: to.Ptr("testCluster-fip"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PublicIPAddress: &network.PublicIPAddress{ - ID: ptr.To("pipID"), + ID: to.Ptr("pipID"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv4, }, @@ -6166,14 +6166,14 @@ func TestRemoveFrontendIPConfigurationFromLoadBalancerDelete(t *testing.T) { }, } service := getTestService("svc1", v1.ProtocolTCP, nil, false, 80) - lb := getTestLoadBalancer(ptr.To("lb"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("testCluster"), service, "standard") + lb := getTestLoadBalancer(to.Ptr("lb"), to.Ptr("rg"), to.Ptr("testCluster"), to.Ptr("testCluster"), service, "standard") bid := "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/k8s-agentpool1-00000000-nic-0/ipConfigurations/ipconfig1" lb.BackendAddressPools = &[]network.BackendAddressPool{ { - Name: ptr.To("testCluster"), + Name: to.Ptr("testCluster"), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ BackendIPConfigurations: &[]network.InterfaceIPConfiguration{ - {ID: ptr.To(bid)}, + {ID: to.Ptr(bid)}, }, }, }, @@ -6183,7 +6183,7 @@ func TestRemoveFrontendIPConfigurationFromLoadBalancerDelete(t *testing.T) { mockLBClient.EXPECT().Delete(gomock.Any(), "rg", "lb").Return(nil) mockPLSRepo := cloud.plsRepo.(*privatelinkservice.MockRepository) mockPLSRepo.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(&armnetwork.PrivateLinkService{ID: to.Ptr(consts.PrivateLinkServiceNotExistID)}, nil) - existingLBs := []network.LoadBalancer{{Name: ptr.To("lb")}} + existingLBs := []network.LoadBalancer{{Name: to.Ptr("lb")}} _, err := cloud.removeFrontendIPConfigurationFromLoadBalancer(context.TODO(), &lb, &existingLBs, []*network.FrontendIPConfiguration{fip}, "testCluster", &service) assert.NoError(t, err) }) @@ -6194,11 +6194,11 @@ func TestRemoveFrontendIPConfigurationFromLoadBalancerUpdate(t *testing.T) { defer ctrl.Finish() t.Run("removeFrontendIPConfigurationFromLoadBalancer should remove the unwanted frontend IP configuration and update the LB if there are remaining frontend IP configurations", func(t *testing.T) { fip := &network.FrontendIPConfiguration{ - Name: ptr.To("testCluster"), - ID: ptr.To("testCluster-fip"), + Name: to.Ptr("testCluster"), + ID: to.Ptr("testCluster-fip"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PublicIPAddress: &network.PublicIPAddress{ - ID: ptr.To("pipID"), + ID: to.Ptr("pipID"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv4, }, @@ -6207,8 +6207,8 @@ func TestRemoveFrontendIPConfigurationFromLoadBalancerUpdate(t *testing.T) { }, } service := getTestService("svc1", v1.ProtocolTCP, nil, false, 80) - lb := getTestLoadBalancer(ptr.To("lb"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("testCluster"), service, "standard") - *lb.FrontendIPConfigurations = append(*lb.FrontendIPConfigurations, network.FrontendIPConfiguration{Name: ptr.To("fip1")}) + lb := getTestLoadBalancer(to.Ptr("lb"), to.Ptr("rg"), to.Ptr("testCluster"), to.Ptr("testCluster"), service, "standard") + *lb.FrontendIPConfigurations = append(*lb.FrontendIPConfigurations, network.FrontendIPConfiguration{Name: to.Ptr("fip1")}) cloud := GetTestCloud(ctrl) mockLBClient := cloud.LoadBalancerClient.(*mockloadbalancerclient.MockInterface) mockLBClient.EXPECT().CreateOrUpdate(gomock.Any(), "rg", "lb", gomock.Any(), gomock.Any()).Return(nil) @@ -6241,10 +6241,10 @@ func TestCleanOrphanedLoadBalancerLBInUseByVMSS(t *testing.T) { mockVMSSClient.EXPECT().CreateOrUpdate(gomock.Any(), "rg", testVMSSName, gomock.Any()).Return(nil) service := getTestService("test", v1.ProtocolTCP, nil, false, 80) - lb := getTestLoadBalancer(ptr.To("test"), ptr.To("rg"), ptr.To("test"), ptr.To("test"), service, consts.LoadBalancerSkuStandard) - (*lb.BackendAddressPools)[0].ID = ptr.To(testLBBackendpoolID0) + lb := getTestLoadBalancer(to.Ptr("test"), to.Ptr("rg"), to.Ptr("test"), to.Ptr("test"), service, consts.LoadBalancerSkuStandard) + (*lb.BackendAddressPools)[0].ID = to.Ptr(testLBBackendpoolID0) - existingLBs := []network.LoadBalancer{{Name: ptr.To("test")}} + existingLBs := []network.LoadBalancer{{Name: to.Ptr("test")}} err = cloud.cleanOrphanedLoadBalancer(context.TODO(), &lb, existingLBs, &service, "test") assert.NoError(t, err) @@ -6258,8 +6258,8 @@ func TestCleanOrphanedLoadBalancerLBInUseByVMSS(t *testing.T) { cloud.LoadBalancerSku = consts.LoadBalancerSkuStandard service := getTestService("test", v1.ProtocolTCP, nil, false, 80) - lb := getTestLoadBalancer(ptr.To("test"), ptr.To("rg"), ptr.To("test"), ptr.To("test"), service, consts.LoadBalancerSkuStandard) - (*lb.BackendAddressPools)[0].ID = ptr.To(testLBBackendpoolID0) + lb := getTestLoadBalancer(to.Ptr("test"), to.Ptr("rg"), to.Ptr("test"), to.Ptr("test"), service, consts.LoadBalancerSkuStandard) + (*lb.BackendAddressPools)[0].ID = to.Ptr(testLBBackendpoolID0) existingLBs := []network.LoadBalancer{} @@ -6291,8 +6291,8 @@ func TestReconcileZonesForFrontendIPConfigs(t *testing.T) { description: "reconcileFrontendIPConfigs should reconcile the zones for the new fip config", service: getTestServiceDualStack("test", v1.ProtocolTCP, nil, 80), existingFrontendIPConfigs: []network.FrontendIPConfiguration{}, - existingPIPV4: network.PublicIPAddress{Name: ptr.To("testCluster-atest"), Location: ptr.To("eastus")}, - existingPIPV6: network.PublicIPAddress{Name: ptr.To("testCluster-atest-IPv6"), Location: ptr.To("eastus")}, + existingPIPV4: network.PublicIPAddress{Name: to.Ptr("testCluster-atest"), Location: to.Ptr("eastus")}, + existingPIPV6: network.PublicIPAddress{Name: to.Ptr("testCluster-atest-IPv6"), Location: to.Ptr("eastus")}, regionZonesMap: map[string][]string{"westus": {"1", "2", "3"}, "eastus": {"1", "2"}}, expectedDirty: true, }, @@ -6300,8 +6300,8 @@ func TestReconcileZonesForFrontendIPConfigs(t *testing.T) { description: "reconcileFrontendIPConfigs should reconcile the zones for the new internal fip config", service: getInternalTestServiceDualStack("test", 80), existingFrontendIPConfigs: []network.FrontendIPConfiguration{}, - existingPIPV4: network.PublicIPAddress{Name: ptr.To("testCluster-atest"), Location: ptr.To("eastus")}, - existingPIPV6: network.PublicIPAddress{Name: ptr.To("testCluster-atest-IPv6"), Location: ptr.To("eastus")}, + existingPIPV4: network.PublicIPAddress{Name: to.Ptr("testCluster-atest"), Location: to.Ptr("eastus")}, + existingPIPV6: network.PublicIPAddress{Name: to.Ptr("testCluster-atest-IPv6"), Location: to.Ptr("eastus")}, regionZonesMap: map[string][]string{"westus": {"1", "2", "3"}, "eastus": {"1", "2"}}, expectedZones: &[]string{"1", "2", "3"}, expectedDirty: true, @@ -6320,10 +6320,10 @@ func TestReconcileZonesForFrontendIPConfigs(t *testing.T) { }, true, 80), existingFrontendIPConfigs: []network.FrontendIPConfiguration{ { - Name: ptr.To("atest1"), + Name: to.Ptr("atest1"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ Subnet: &network.Subnet{ - Name: ptr.To("subnet-1"), + Name: to.Ptr("subnet-1"), }, }, }, @@ -6338,19 +6338,19 @@ func TestReconcileZonesForFrontendIPConfigs(t *testing.T) { }, true, 80), existingFrontendIPConfigs: []network.FrontendIPConfiguration{ { - Name: ptr.To("not-this-one"), + Name: to.Ptr("not-this-one"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ Subnet: &network.Subnet{ - Name: ptr.To("subnet-1"), + Name: to.Ptr("subnet-1"), }, }, Zones: &[]string{"2"}, }, { - Name: ptr.To("atest1"), + Name: to.Ptr("atest1"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ Subnet: &network.Subnet{ - Name: ptr.To("subnet-1"), + Name: to.Ptr("subnet-1"), }, }, Zones: &[]string{"1"}, @@ -6368,8 +6368,8 @@ func TestReconcileZonesForFrontendIPConfigs(t *testing.T) { {IP: "2001::1"}, }, }, - expectedIPv4: ptr.To("1.2.3.4"), - expectedIPv6: ptr.To("2001::1"), + expectedIPv4: to.Ptr("1.2.3.4"), + expectedIPv6: to.Ptr("2001::1"), expectedDirty: true, }, { @@ -6381,8 +6381,8 @@ func TestReconcileZonesForFrontendIPConfigs(t *testing.T) { {IP: "2001::3"}, }, }, - expectedIPv4: ptr.To(""), - expectedIPv6: ptr.To(""), + expectedIPv4: to.Ptr(""), + expectedIPv6: to.Ptr(""), expectedDirty: true, }, } { @@ -6391,7 +6391,7 @@ func TestReconcileZonesForFrontendIPConfigs(t *testing.T) { cloud.regionZonesMap = tc.regionZonesMap cloud.LoadBalancerSku = string(network.LoadBalancerSkuNameStandard) - lb := getTestLoadBalancer(ptr.To("lb"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("testCluster"), tc.service, "standard") + lb := getTestLoadBalancer(to.Ptr("lb"), to.Ptr("rg"), to.Ptr("testCluster"), to.Ptr("testCluster"), tc.service, "standard") existingFrontendIPConfigs := tc.existingFrontendIPConfigs lb.FrontendIPConfigurations = &existingFrontendIPConfigs @@ -6404,7 +6404,7 @@ func TestReconcileZonesForFrontendIPConfigs(t *testing.T) { subnetClient := cloud.SubnetsClient.(*mocksubnetclient.MockInterface) subnetClient.EXPECT().Get(gomock.Any(), "rg", "vnet", "subnet", gomock.Any()).Return( - network.Subnet{ID: ptr.To("subnet0"), SubnetPropertiesFormat: &network.SubnetPropertiesFormat{AddressPrefixes: &[]string{"1.2.3.4/31", "2001::1/127"}}}, nil).MaxTimes(1) + network.Subnet{ID: to.Ptr("subnet0"), SubnetPropertiesFormat: &network.SubnetPropertiesFormat{AddressPrefixes: &[]string{"1.2.3.4/31", "2001::1/127"}}}, nil).MaxTimes(1) zoneMock := zone.NewMockRepository(ctrl) zoneMock.EXPECT().ListZones(gomock.Any()).Return(map[string][]string{}, tc.getZoneError).MaxTimes(2) @@ -6426,7 +6426,7 @@ func TestReconcileZonesForFrontendIPConfigs(t *testing.T) { assert.Equal(t, tc.expectedDirty, dirty) for _, fip := range *lb.FrontendIPConfigurations { - if strings.EqualFold(ptr.Deref(fip.Name, ""), defaultLBFrontendIPConfigName) { + if strings.EqualFold(lo.FromPtrOr(fip.Name, ""), defaultLBFrontendIPConfigName) { assert.Equal(t, tc.expectedZones, fip.Zones) } } @@ -6434,8 +6434,8 @@ func TestReconcileZonesForFrontendIPConfigs(t *testing.T) { checkExpectedIP := func(isIPv6 bool, expectedIP *string) { if expectedIP != nil { for _, fip := range *lb.FrontendIPConfigurations { - if strings.EqualFold(ptr.Deref(fip.Name, ""), lbFrontendIPConfigNames[isIPv6]) { - assert.Equal(t, *expectedIP, ptr.Deref(fip.PrivateIPAddress, "")) + if strings.EqualFold(lo.FromPtrOr(fip.Name, ""), lbFrontendIPConfigNames[isIPv6]) { + assert.Equal(t, *expectedIP, lo.FromPtrOr(fip.PrivateIPAddress, "")) if *expectedIP != "" { assert.Equal(t, network.Static, (*lb.FrontendIPConfigurations)[0].PrivateIPAllocationMethod) } else { @@ -6471,79 +6471,79 @@ func TestReconcileFrontendIPConfigs(t *testing.T) { service: getTestServiceDualStack("test", v1.ProtocolTCP, nil, 80), existingFIPs: []network.FrontendIPConfiguration{ { - Name: ptr.To("fipV4"), + Name: to.Ptr("fipV4"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PublicIPAddress: &network.PublicIPAddress{ - Name: ptr.To("pipV4"), + Name: to.Ptr("pipV4"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv4, - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, }, }, { - Name: ptr.To("fipV6"), + Name: to.Ptr("fipV6"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PublicIPAddress: &network.PublicIPAddress{ - Name: ptr.To("pipV6"), + Name: to.Ptr("pipV6"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv6, - IPAddress: ptr.To("fe::1"), + IPAddress: to.Ptr("fe::1"), }, }, }, }, { - Name: ptr.To("atest"), - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lb/frontendIPConfigurations/atest"), + Name: to.Ptr("atest"), + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lb/frontendIPConfigurations/atest"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PublicIPAddress: &network.PublicIPAddress{ - ID: ptr.To("testCluster-atest-id"), + ID: to.Ptr("testCluster-atest-id"), }, }, }, { - Name: ptr.To("atest-IPv6"), - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lb/frontendIPConfigurations/atest-IPv6"), + Name: to.Ptr("atest-IPv6"), + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lb/frontendIPConfigurations/atest-IPv6"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PublicIPAddress: &network.PublicIPAddress{ - ID: ptr.To("testCluster-atest-id-IPv6"), + ID: to.Ptr("testCluster-atest-id-IPv6"), }, }, }, }, existingPIPs: []network.PublicIPAddress{ { - Name: ptr.To("testCluster-atest"), - ID: ptr.To("testCluster-atest-id"), + Name: to.Ptr("testCluster-atest"), + ID: to.Ptr("testCluster-atest-id"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv4, PublicIPAllocationMethod: network.Static, - IPAddress: ptr.To("1.2.3.5"), + IPAddress: to.Ptr("1.2.3.5"), }, }, { - Name: ptr.To("testCluster-atest-IPv6"), - ID: ptr.To("testCluster-atest-id-IPv6"), + Name: to.Ptr("testCluster-atest-IPv6"), + ID: to.Ptr("testCluster-atest-id-IPv6"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv6, PublicIPAllocationMethod: network.Static, - IPAddress: ptr.To("fe::2"), + IPAddress: to.Ptr("fe::2"), }, }, { - Name: ptr.To("pipV4"), + Name: to.Ptr("pipV4"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv4, - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, { - Name: ptr.To("pipV6"), + Name: to.Ptr("pipV6"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv6, - IPAddress: ptr.To("fe::1"), + IPAddress: to.Ptr("fe::1"), }, }, }, @@ -6552,44 +6552,44 @@ func TestReconcileFrontendIPConfigs(t *testing.T) { expectedDirty: false, expectedFIPs: []network.FrontendIPConfiguration{ { - Name: ptr.To("fipV4"), + Name: to.Ptr("fipV4"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PublicIPAddress: &network.PublicIPAddress{ - Name: ptr.To("pipV4"), + Name: to.Ptr("pipV4"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv4, - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, }, }, { - Name: ptr.To("fipV6"), + Name: to.Ptr("fipV6"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PublicIPAddress: &network.PublicIPAddress{ - Name: ptr.To("pipV6"), + Name: to.Ptr("pipV6"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv6, - IPAddress: ptr.To("fe::1"), + IPAddress: to.Ptr("fe::1"), }, }, }, }, { - Name: ptr.To("atest"), - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lb/frontendIPConfigurations/atest"), + Name: to.Ptr("atest"), + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lb/frontendIPConfigurations/atest"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PublicIPAddress: &network.PublicIPAddress{ - ID: ptr.To("testCluster-atest-id"), + ID: to.Ptr("testCluster-atest-id"), }, }, }, { - Name: ptr.To("atest-IPv6"), - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lb/frontendIPConfigurations/atest-IPv6"), + Name: to.Ptr("atest-IPv6"), + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lb/frontendIPConfigurations/atest-IPv6"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PublicIPAddress: &network.PublicIPAddress{ - ID: ptr.To("testCluster-atest-id-IPv6"), + ID: to.Ptr("testCluster-atest-id-IPv6"), }, }, }, @@ -6600,19 +6600,19 @@ func TestReconcileFrontendIPConfigs(t *testing.T) { service: getTestServiceDualStack("test", v1.ProtocolTCP, nil, 80), existingFIPs: []network.FrontendIPConfiguration{ { - Name: ptr.To("atest"), + Name: to.Ptr("atest"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PublicIPAddress: &network.PublicIPAddress{ - ID: ptr.To("testCluster-atest-id"), + ID: to.Ptr("testCluster-atest-id"), }, }, }, { - Name: ptr.To("atest-IPv6"), - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lb/frontendIPConfigurations/atest-IPv6"), + Name: to.Ptr("atest-IPv6"), + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lb/frontendIPConfigurations/atest-IPv6"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PublicIPAddress: &network.PublicIPAddress{ - ID: ptr.To("testCluster-atest-id-IPv6"), + ID: to.Ptr("testCluster-atest-id-IPv6"), }, }, }, @@ -6626,13 +6626,13 @@ func TestReconcileFrontendIPConfigs(t *testing.T) { service: getTestService("test", v1.ProtocolTCP, nil, true, 80), existingFIPs: []network.FrontendIPConfiguration{ { - Name: ptr.To("fipV4"), + Name: to.Ptr("fipV4"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PublicIPAddress: &network.PublicIPAddress{ - Name: ptr.To("pipV4"), + Name: to.Ptr("pipV4"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv4, - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, }, @@ -6640,19 +6640,19 @@ func TestReconcileFrontendIPConfigs(t *testing.T) { }, existingPIPs: []network.PublicIPAddress{ { - Name: ptr.To("testCluster-atest"), - ID: ptr.To("testCluster-atest-id"), + Name: to.Ptr("testCluster-atest"), + ID: to.Ptr("testCluster-atest-id"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv6, PublicIPAllocationMethod: network.Static, - IPAddress: ptr.To("fe::1"), + IPAddress: to.Ptr("fe::1"), }, }, { - Name: ptr.To("pipV4"), + Name: to.Ptr("pipV4"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv4, - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, }, @@ -6661,23 +6661,23 @@ func TestReconcileFrontendIPConfigs(t *testing.T) { expectedDirty: true, expectedFIPs: []network.FrontendIPConfiguration{ { - Name: ptr.To("fipV4"), + Name: to.Ptr("fipV4"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PublicIPAddress: &network.PublicIPAddress{ - Name: ptr.To("pipV4"), + Name: to.Ptr("pipV4"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv4, - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, }, }, { - Name: ptr.To("atest"), - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lb/frontendIPConfigurations/atest"), + Name: to.Ptr("atest"), + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lb/frontendIPConfigurations/atest"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PublicIPAddress: &network.PublicIPAddress{ - ID: ptr.To("testCluster-atest-id"), + ID: to.Ptr("testCluster-atest-id"), }, }, }, @@ -6690,7 +6690,7 @@ func TestReconcileFrontendIPConfigs(t *testing.T) { cloud := GetTestCloud(ctrl) cloud.LoadBalancerSku = string(network.LoadBalancerSkuNameStandard) - lb := getTestLoadBalancer(ptr.To("lb"), ptr.To("rg"), ptr.To("testCluster"), ptr.To("testCluster"), tc.service, "standard") + lb := getTestLoadBalancer(to.Ptr("lb"), to.Ptr("rg"), to.Ptr("testCluster"), to.Ptr("testCluster"), tc.service, "standard") existingFIPs := tc.existingFIPs lb.FrontendIPConfigurations = &existingFIPs @@ -6799,7 +6799,7 @@ func TestReconcileIPSettings(t *testing.T) { az := GetTestCloud(ctrl) az.LoadBalancerSku = tc.sku pip := tc.pip - pip.Name = ptr.To("pip") + pip.Name = to.Ptr("pip") service := tc.service changed := az.reconcileIPSettings(pip, &service, tc.isIPv6) assert.Equal(t, tc.expectedChanged, changed) @@ -6824,12 +6824,12 @@ func TestGetServiceFromPIPDNSTags(t *testing.T) { }, { desc: "Expected service should be returned when tags contain dns label tag", - tags: map[string]*string{consts.ServiceUsingDNSKey: ptr.To("test-service")}, + tags: map[string]*string{consts.ServiceUsingDNSKey: to.Ptr("test-service")}, expected: "test-service", }, { desc: "Expected service should be returned when tags contain legacy dns label tag", - tags: map[string]*string{consts.LegacyServiceUsingDNSKey: ptr.To("test-service")}, + tags: map[string]*string{consts.LegacyServiceUsingDNSKey: to.Ptr("test-service")}, expected: "test-service", }, } @@ -6853,12 +6853,12 @@ func TestGetServiceFromPIPServiceTags(t *testing.T) { }, { desc: "Expected service should be returned when tags contain service tag", - tags: map[string]*string{consts.ServiceTagKey: ptr.To("test-service")}, + tags: map[string]*string{consts.ServiceTagKey: to.Ptr("test-service")}, expected: "test-service", }, { desc: "Expected service should be returned when tags contain legacy service tag", - tags: map[string]*string{consts.LegacyServiceTagKey: ptr.To("test-service")}, + tags: map[string]*string{consts.LegacyServiceTagKey: to.Ptr("test-service")}, expected: "test-service", }, } @@ -6882,12 +6882,12 @@ func TestGetClusterFromPIPClusterTags(t *testing.T) { }, { desc: "Expected service should be returned when tags contain cluster name tag", - tags: map[string]*string{consts.ClusterNameKey: ptr.To("test-cluster")}, + tags: map[string]*string{consts.ClusterNameKey: to.Ptr("test-cluster")}, expected: "test-cluster", }, { desc: "Expected service should be returned when tags contain legacy cluster name tag", - tags: map[string]*string{consts.LegacyClusterNameKey: ptr.To("test-cluster")}, + tags: map[string]*string{consts.LegacyClusterNameKey: to.Ptr("test-cluster")}, expected: "test-cluster", }, } @@ -6988,7 +6988,7 @@ func TestSafeDeleteLoadBalancer(t *testing.T) { } svc := getTestService("svc", v1.ProtocolTCP, nil, false, 80) lb := network.LoadBalancer{ - Name: ptr.To("test"), + Name: to.Ptr("test"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ BackendAddressPools: &[]network.BackendAddressPool{}, }, @@ -7029,8 +7029,8 @@ func TestEqualSubResource(t *testing.T) { }, { desc: "equal", - subResource1: &network.SubResource{ID: ptr.To("id")}, - subResource2: &network.SubResource{ID: ptr.To("id")}, + subResource1: &network.SubResource{ID: to.Ptr("id")}, + subResource2: &network.SubResource{ID: to.Ptr("id")}, expected: true, }, } @@ -7271,7 +7271,7 @@ func TestGetEligibleLoadBalancers(t *testing.T) { { Name: "d", MultipleStandardLoadBalancerConfigurationSpec: config.MultipleStandardLoadBalancerConfigurationSpec{ - AllowServicePlacement: ptr.To(false), + AllowServicePlacement: to.Ptr(false), ServiceNamespaceSelector: &metav1.LabelSelector{ MatchLabels: map[string]string{"k2": "v2"}, }, @@ -7341,7 +7341,7 @@ func TestGetEligibleLoadBalancers(t *testing.T) { { Name: "a", MultipleStandardLoadBalancerConfigurationSpec: config.MultipleStandardLoadBalancerConfigurationSpec{ - AllowServicePlacement: ptr.To(false), + AllowServicePlacement: to.Ptr(false), }, MultipleStandardLoadBalancerConfigurationStatus: config.MultipleStandardLoadBalancerConfigurationStatus{ ActiveServices: utilsets.NewString("default/test"), @@ -7574,7 +7574,7 @@ func TestGetMostEligibleLBName(t *testing.T) { eligibleLBs: []string{"lb2", "lb3"}, existingLBs: &[]network.LoadBalancer{ { - Name: ptr.To("lb2"), + Name: to.Ptr("lb2"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ LoadBalancingRules: &[]network.LoadBalancingRule{ {}, @@ -7584,7 +7584,7 @@ func TestGetMostEligibleLBName(t *testing.T) { }, }, { - Name: ptr.To("lb3"), + Name: to.Ptr("lb3"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ LoadBalancingRules: &[]network.LoadBalancingRule{ {}, @@ -7593,7 +7593,7 @@ func TestGetMostEligibleLBName(t *testing.T) { }, }, { - Name: ptr.To("lb4"), + Name: to.Ptr("lb4"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ LoadBalancingRules: &[]network.LoadBalancingRule{ {}, @@ -7613,7 +7613,7 @@ func TestGetMostEligibleLBName(t *testing.T) { eligibleLBs: []string{"lb1", "lb2", "lb3"}, existingLBs: &[]network.LoadBalancer{ { - Name: ptr.To("lb3"), + Name: to.Ptr("lb3"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ LoadBalancingRules: &[]network.LoadBalancingRule{}, }, @@ -7626,7 +7626,7 @@ func TestGetMostEligibleLBName(t *testing.T) { eligibleLBs: []string{"lb1", "lb2", "lb3"}, existingLBs: &[]network.LoadBalancer{ { - Name: ptr.To("lb1-internal"), + Name: to.Ptr("lb1-internal"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ LoadBalancingRules: &[]network.LoadBalancingRule{ {}, @@ -7634,13 +7634,13 @@ func TestGetMostEligibleLBName(t *testing.T) { }, }, { - Name: ptr.To("lb2-internal"), + Name: to.Ptr("lb2-internal"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ LoadBalancingRules: &[]network.LoadBalancingRule{}, }, }, { - Name: ptr.To("lb3-internal"), + Name: to.Ptr("lb3-internal"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ LoadBalancingRules: &[]network.LoadBalancingRule{}, }, @@ -7734,7 +7734,7 @@ func TestReconcileMultipleStandardLoadBalancerConfigurations(t *testing.T) { lbSvcOnLB1RuleName := az.getLoadBalancerRuleName(&existingSvcs[2], v1.ProtocolTCP, 80, false) existingLBs := []network.LoadBalancer{ { - Name: ptr.To("kubernetes-internal"), + Name: to.Ptr("kubernetes-internal"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ LoadBalancingRules: &[]network.LoadBalancingRule{ {Name: &lbSvcOnKubernetesRuleName}, @@ -7742,7 +7742,7 @@ func TestReconcileMultipleStandardLoadBalancerConfigurations(t *testing.T) { }, }, { - Name: ptr.To("lb1"), + Name: to.Ptr("lb1"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ LoadBalancingRules: &[]network.LoadBalancingRule{ {Name: &lbSvcOnLB1RuleName}, @@ -7750,7 +7750,7 @@ func TestReconcileMultipleStandardLoadBalancerConfigurations(t *testing.T) { }, }, { - Name: ptr.To("lb2"), + Name: to.Ptr("lb2"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ LoadBalancingRules: &[]network.LoadBalancingRule{}, }, @@ -7938,7 +7938,7 @@ func TestServiceOwnsFrontendIP(t *testing.T) { { desc: "serviceOwnsFrontendIP should detect the primary service", fip: network.FrontendIPConfiguration{ - Name: ptr.To("auid"), + Name: to.Ptr("auid"), }, service: &v1.Service{ ObjectMeta: metav1.ObjectMeta{ @@ -7951,7 +7951,7 @@ func TestServiceOwnsFrontendIP(t *testing.T) { { desc: "serviceOwnsFrontendIP should return false if the secondary external service doesn't set it's loadBalancer IP", fip: network.FrontendIPConfiguration{ - Name: ptr.To("auid"), + Name: to.Ptr("auid"), }, service: &v1.Service{ ObjectMeta: metav1.ObjectMeta{ @@ -7964,17 +7964,17 @@ func TestServiceOwnsFrontendIP(t *testing.T) { "found according to the external service's loadBalancer IP but do not return the error", existingPIPs: []network.PublicIPAddress{ { - ID: ptr.To("pip"), + ID: to.Ptr("pip"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("4.3.2.1"), + IPAddress: to.Ptr("4.3.2.1"), }, }, }, fip: network.FrontendIPConfiguration{ - Name: ptr.To("auid"), + Name: to.Ptr("auid"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PublicIPAddress: &network.PublicIPAddress{ - ID: ptr.To("pip"), + ID: to.Ptr("pip"), }, }, }, @@ -7989,18 +7989,18 @@ func TestServiceOwnsFrontendIP(t *testing.T) { desc: "serviceOwnsFrontendIP should return correct FIP IP version", existingPIPs: []network.PublicIPAddress{ { - ID: ptr.To("pip"), + ID: to.Ptr("pip"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("4.3.2.1"), + IPAddress: to.Ptr("4.3.2.1"), PublicIPAddressVersion: network.IPv4, }, }, }, fip: network.FrontendIPConfiguration{ - Name: ptr.To("auid"), + Name: to.Ptr("auid"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PublicIPAddress: &network.PublicIPAddress{ - ID: ptr.To("pip"), + ID: to.Ptr("pip"), }, }, }, @@ -8018,17 +8018,17 @@ func TestServiceOwnsFrontendIP(t *testing.T) { "the counterpart on the frontend IP config", existingPIPs: []network.PublicIPAddress{ { - ID: ptr.To("pip"), + ID: to.Ptr("pip"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("4.3.2.1"), + IPAddress: to.Ptr("4.3.2.1"), }, }, }, fip: network.FrontendIPConfiguration{ - Name: ptr.To("auid"), + Name: to.Ptr("auid"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PublicIPAddress: &network.PublicIPAddress{ - ID: ptr.To("pip1"), + ID: to.Ptr("pip1"), }, }, }, @@ -8043,17 +8043,17 @@ func TestServiceOwnsFrontendIP(t *testing.T) { desc: "serviceOwnsFrontendIP should return false if there is no public IP address in the frontend IP config", existingPIPs: []network.PublicIPAddress{ { - ID: ptr.To("pip"), + ID: to.Ptr("pip"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("4.3.2.1"), + IPAddress: to.Ptr("4.3.2.1"), }, }, }, fip: network.FrontendIPConfiguration{ - Name: ptr.To("auid"), + Name: to.Ptr("auid"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PublicIPPrefix: &network.SubResource{ - ID: ptr.To("pip1"), + ID: to.Ptr("pip1"), }, }, }, @@ -8070,17 +8070,17 @@ func TestServiceOwnsFrontendIP(t *testing.T) { desc: "serviceOwnsFrontendIP should detect the secondary external service", existingPIPs: []network.PublicIPAddress{ { - ID: ptr.To("pip"), + ID: to.Ptr("pip"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("4.3.2.1"), + IPAddress: to.Ptr("4.3.2.1"), }, }, }, fip: network.FrontendIPConfiguration{ - Name: ptr.To("auid"), + Name: to.Ptr("auid"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PublicIPAddress: &network.PublicIPAddress{ - ID: ptr.To("pip"), + ID: to.Ptr("pip"), }, }, }, @@ -8099,30 +8099,30 @@ func TestServiceOwnsFrontendIP(t *testing.T) { desc: "serviceOwnsFrontendIP should detect the secondary external service dual-stack", existingPIPs: []network.PublicIPAddress{ { - Name: ptr.To("pip"), - ID: ptr.To("pip"), + Name: to.Ptr("pip"), + ID: to.Ptr("pip"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv4, - IPAddress: ptr.To("4.3.2.1"), + IPAddress: to.Ptr("4.3.2.1"), }, }, { - Name: ptr.To("pip1"), - ID: ptr.To("pip1"), + Name: to.Ptr("pip1"), + ID: to.Ptr("pip1"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv6, - IPAddress: ptr.To("fd00::eef0"), + IPAddress: to.Ptr("fd00::eef0"), }, }, }, fip: network.FrontendIPConfiguration{ - Name: ptr.To("auid"), + Name: to.Ptr("auid"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PublicIPAddress: &network.PublicIPAddress{ PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv6, }, - ID: ptr.To("pip1"), + ID: to.Ptr("pip1"), }, }, }, @@ -8141,9 +8141,9 @@ func TestServiceOwnsFrontendIP(t *testing.T) { { desc: "serviceOwnsFrontendIP should detect the secondary internal service", fip: network.FrontendIPConfiguration{ - Name: ptr.To("auid"), + Name: to.Ptr("auid"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PrivateIPAddress: ptr.To("4.3.2.1"), + PrivateIPAddress: to.Ptr("4.3.2.1"), }, }, service: &v1.Service{ @@ -8160,9 +8160,9 @@ func TestServiceOwnsFrontendIP(t *testing.T) { { desc: "serviceOwnsFrontendIP should detect the secondary internal service - dualstack", fip: network.FrontendIPConfiguration{ - Name: ptr.To("auid"), + Name: to.Ptr("auid"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ - PrivateIPAddress: ptr.To("fd00::eef0"), + PrivateIPAddress: to.Ptr("fd00::eef0"), }, }, service: &v1.Service{ @@ -8191,18 +8191,18 @@ func TestServiceOwnsFrontendIP(t *testing.T) { }, existingPIPs: []network.PublicIPAddress{ { - Name: ptr.To("pip1"), - ID: ptr.To("pip1"), + Name: to.Ptr("pip1"), + ID: to.Ptr("pip1"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, }, }, fip: network.FrontendIPConfiguration{ - Name: ptr.To("test"), + Name: to.Ptr("test"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PublicIPAddress: &network.PublicIPAddress{ - ID: ptr.To("pip1"), + ID: to.Ptr("pip1"), }, }, }, @@ -8271,23 +8271,23 @@ func TestReconcileMultipleStandardLoadBalancerNodes(t *testing.T) { }, existingLBs: []network.LoadBalancer{ { - Name: ptr.To("lb1-internal"), + Name: to.Ptr("lb1-internal"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ BackendAddressPools: &[]network.BackendAddressPool{ { - Name: ptr.To("kubernetes"), + Name: to.Ptr("kubernetes"), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ { - Name: ptr.To("node1"), + Name: to.Ptr("node1"), LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To("10.1.0.1"), + IPAddress: to.Ptr("10.1.0.1"), }, }, { - Name: ptr.To("node2"), + Name: to.Ptr("node2"), LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To("10.1.0.2"), + IPAddress: to.Ptr("10.1.0.2"), }, }, }, @@ -8297,23 +8297,23 @@ func TestReconcileMultipleStandardLoadBalancerNodes(t *testing.T) { }, }, { - Name: ptr.To("lb2"), + Name: to.Ptr("lb2"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ BackendAddressPools: &[]network.BackendAddressPool{ { - Name: ptr.To("kubernetes"), + Name: to.Ptr("kubernetes"), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ { - Name: ptr.To("node3"), + Name: to.Ptr("node3"), LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To("10.1.0.3"), + IPAddress: to.Ptr("10.1.0.3"), }, }, { - Name: ptr.To("node4"), + Name: to.Ptr("node4"), LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To("10.1.0.4"), + IPAddress: to.Ptr("10.1.0.4"), }, }, }, @@ -8382,23 +8382,23 @@ func TestReconcileMultipleStandardLoadBalancerNodes(t *testing.T) { }, existingLBs: []network.LoadBalancer{ { - Name: ptr.To("lb1-internal"), + Name: to.Ptr("lb1-internal"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ BackendAddressPools: &[]network.BackendAddressPool{ { - Name: ptr.To("kubernetes"), + Name: to.Ptr("kubernetes"), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ { - Name: ptr.To("node1"), + Name: to.Ptr("node1"), LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To("10.1.0.1"), + IPAddress: to.Ptr("10.1.0.1"), }, }, { - Name: ptr.To("node2"), + Name: to.Ptr("node2"), LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To("10.1.0.2"), + IPAddress: to.Ptr("10.1.0.2"), }, }, }, @@ -8408,21 +8408,21 @@ func TestReconcileMultipleStandardLoadBalancerNodes(t *testing.T) { }, }, { - Name: ptr.To("lb3"), + Name: to.Ptr("lb3"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ BackendAddressPools: &[]network.BackendAddressPool{ { - Name: ptr.To("kubernetes"), + Name: to.Ptr("kubernetes"), }, }, }, }, { - Name: ptr.To("lb4"), + Name: to.Ptr("lb4"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ BackendAddressPools: &[]network.BackendAddressPool{ { - Name: ptr.To("kubernetes"), + Name: to.Ptr("kubernetes"), }, }, }, @@ -8494,19 +8494,19 @@ func TestReconcileMultipleStandardLoadBalancerNodes(t *testing.T) { }, existingLBs: []network.LoadBalancer{ { - Name: ptr.To("lb2-internal"), + Name: to.Ptr("lb2-internal"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ BackendAddressPools: &[]network.BackendAddressPool{ - {Name: ptr.To("kubernetes")}, + {Name: to.Ptr("kubernetes")}, }, }, }, { - Name: ptr.To("lb4"), + Name: to.Ptr("lb4"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ BackendAddressPools: &[]network.BackendAddressPool{ { - Name: ptr.To("kubernetes"), + Name: to.Ptr("kubernetes"), }, }, }, @@ -8562,10 +8562,10 @@ func TestReconcileMultipleStandardLoadBalancerNodes(t *testing.T) { }, existingLBs: []network.LoadBalancer{ { - Name: ptr.To("lb2-internal"), + Name: to.Ptr("lb2-internal"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ BackendAddressPools: &[]network.BackendAddressPool{ - {Name: ptr.To("kubernetes")}, + {Name: to.Ptr("kubernetes")}, }, }, }, @@ -8610,17 +8610,17 @@ func TestReconcileMultipleStandardLoadBalancerNodes(t *testing.T) { }, existingLBs: []network.LoadBalancer{ { - Name: ptr.To("lb1-internal"), + Name: to.Ptr("lb1-internal"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ BackendAddressPools: &[]network.BackendAddressPool{ { - Name: ptr.To("kubernetes"), + Name: to.Ptr("kubernetes"), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ { - Name: ptr.To("node2"), + Name: to.Ptr("node2"), LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To("10.1.0.2"), + IPAddress: to.Ptr("10.1.0.2"), }, }, }, @@ -8630,29 +8630,29 @@ func TestReconcileMultipleStandardLoadBalancerNodes(t *testing.T) { }, }, { - Name: ptr.To("lb2"), + Name: to.Ptr("lb2"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ BackendAddressPools: &[]network.BackendAddressPool{ { - Name: ptr.To("kubernetes"), + Name: to.Ptr("kubernetes"), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{ { - Name: ptr.To("node3"), + Name: to.Ptr("node3"), LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To("10.1.0.3"), + IPAddress: to.Ptr("10.1.0.3"), }, }, { - Name: ptr.To("node4"), + Name: to.Ptr("node4"), LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To("10.1.0.4"), + IPAddress: to.Ptr("10.1.0.4"), }, }, { - Name: ptr.To("node5"), + Name: to.Ptr("node5"), LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To("10.1.0.5"), + IPAddress: to.Ptr("10.1.0.5"), }, }, }, @@ -8719,44 +8719,44 @@ func getTestNodeWithMetadata(nodeName, vmssName string, labels map[string]string func TestAddOrUpdateLBInList(t *testing.T) { existingLBs := []network.LoadBalancer{ { - Name: ptr.To("lb1"), + Name: to.Ptr("lb1"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ BackendAddressPools: &[]network.BackendAddressPool{ - {Name: ptr.To("kubernetes")}, + {Name: to.Ptr("kubernetes")}, }, }, }, { - Name: ptr.To("lb2"), + Name: to.Ptr("lb2"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ BackendAddressPools: &[]network.BackendAddressPool{ - {Name: ptr.To("kubernetes")}, + {Name: to.Ptr("kubernetes")}, }, }, }, } targetLB := network.LoadBalancer{ - Name: ptr.To("lb1"), + Name: to.Ptr("lb1"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ BackendAddressPools: &[]network.BackendAddressPool{ - {Name: ptr.To("lb1")}, + {Name: to.Ptr("lb1")}, }, }, } expectedLBs := []network.LoadBalancer{ { - Name: ptr.To("lb1"), + Name: to.Ptr("lb1"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ BackendAddressPools: &[]network.BackendAddressPool{ - {Name: ptr.To("lb1")}, + {Name: to.Ptr("lb1")}, }, }, }, { - Name: ptr.To("lb2"), + Name: to.Ptr("lb2"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ BackendAddressPools: &[]network.BackendAddressPool{ - {Name: ptr.To("kubernetes")}, + {Name: to.Ptr("kubernetes")}, }, }, }, @@ -8766,26 +8766,26 @@ func TestAddOrUpdateLBInList(t *testing.T) { assert.Equal(t, expectedLBs, existingLBs) targetLB = network.LoadBalancer{ - Name: ptr.To("lb3"), + Name: to.Ptr("lb3"), } expectedLBs = []network.LoadBalancer{ { - Name: ptr.To("lb1"), + Name: to.Ptr("lb1"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ BackendAddressPools: &[]network.BackendAddressPool{ - {Name: ptr.To("lb1")}, + {Name: to.Ptr("lb1")}, }, }, }, { - Name: ptr.To("lb2"), + Name: to.Ptr("lb2"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ BackendAddressPools: &[]network.BackendAddressPool{ - {Name: ptr.To("kubernetes")}, + {Name: to.Ptr("kubernetes")}, }, }, }, - {Name: ptr.To("lb3")}, + {Name: to.Ptr("lb3")}, } addOrUpdateLBInList(&existingLBs, &targetLB) @@ -8805,19 +8805,19 @@ func TestReconcileBackendPoolHosts(t *testing.T) { ips = []string{"10.0.0.2", "10.0.0.3"} bp3 := buildTestLoadBalancerBackendPoolWithIPs(clusterName, ips) lb1 := &network.LoadBalancer{ - Name: ptr.To(clusterName), + Name: to.Ptr(clusterName), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ BackendAddressPools: &[]network.BackendAddressPool{bp1}, }, } lb2 := &network.LoadBalancer{ - Name: ptr.To("lb2"), + Name: to.Ptr("lb2"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ BackendAddressPools: &[]network.BackendAddressPool{bp2}, }, } expectedLB := &network.LoadBalancer{ - Name: ptr.To(clusterName), + Name: to.Ptr(clusterName), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ BackendAddressPools: &[]network.BackendAddressPool{bp3}, }, @@ -8845,12 +8845,12 @@ func fakeEnsureHostsInPool() func(context.Context, *v1.Service, []*v1.Node, stri backendPool.LoadBalancerBackendAddresses = &[]network.LoadBalancerBackendAddress{ { LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To("10.0.0.2"), + IPAddress: to.Ptr("10.0.0.2"), }, }, { LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To("10.0.0.3"), + IPAddress: to.Ptr("10.0.0.3"), }, }, } diff --git a/pkg/provider/azure_local_services.go b/pkg/provider/azure_local_services.go index 0febc94edb..5040bfcd21 100644 --- a/pkg/provider/azure_local_services.go +++ b/pkg/provider/azure_local_services.go @@ -24,7 +24,7 @@ import ( "time" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - + "github.com/samber/lo" v1 "k8s.io/api/core/v1" discovery_v1 "k8s.io/api/discovery/v1" "k8s.io/apimachinery/pkg/util/sets" @@ -33,7 +33,6 @@ import ( "k8s.io/client-go/tools/cache" "k8s.io/klog/v2" utilnet "k8s.io/utils/net" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/consts" "sigs.k8s.io/cloud-provider-azure/pkg/retry" @@ -222,7 +221,7 @@ func (updater *loadBalancerBackendPoolUpdater) process(ctx context.Context) { // but the backend pool object is not changed after multiple times of removal and re-adding. if changed { klog.V(2).Infof("loadBalancerBackendPoolUpdater.process: updating backend pool %s/%s", lbName, poolName) - rerr = updater.az.LoadBalancerClient.CreateOrUpdateBackendPools(ctx, updater.az.ResourceGroup, lbName, poolName, bp, ptr.Deref(bp.Etag, "")) + rerr = updater.az.LoadBalancerClient.CreateOrUpdateBackendPools(ctx, updater.az.ResourceGroup, lbName, poolName, bp, lo.FromPtrOr(bp.Etag, "")) if rerr != nil { updater.processError(rerr, operationName, ops...) continue @@ -319,12 +318,12 @@ func (az *Cloud) setUpEndpointSlicesInformer(informerFactory informers.SharedInf var previousIPs, currentIPs, previousNodeNames, currentNodeNames []string if previousES != nil { for _, ep := range previousES.Endpoints { - previousNodeNames = append(previousNodeNames, ptr.Deref(ep.NodeName, "")) + previousNodeNames = append(previousNodeNames, lo.FromPtrOr(ep.NodeName, "")) } } if newES != nil { for _, ep := range newES.Endpoints { - currentNodeNames = append(currentNodeNames, ptr.Deref(ep.NodeName, "")) + currentNodeNames = append(currentNodeNames, lo.FromPtrOr(ep.NodeName, "")) } } for _, previousNodeName := range previousNodeNames { @@ -482,8 +481,8 @@ func (az *Cloud) getLocalServiceEndpointsNodeNames(service *v1.Service) *utilset var nodeNames []string for _, ep := range eps { for _, endpoint := range ep.Endpoints { - klog.V(4).Infof("EndpointSlice %s/%s has endpoint %s on node %s", ep.Namespace, ep.Name, endpoint.Addresses, ptr.Deref(endpoint.NodeName, "")) - nodeNames = append(nodeNames, ptr.Deref(endpoint.NodeName, "")) + klog.V(4).Infof("EndpointSlice %s/%s has endpoint %s on node %s", ep.Namespace, ep.Name, endpoint.Addresses, lo.FromPtrOr(endpoint.NodeName, "")) + nodeNames = append(nodeNames, lo.FromPtrOr(endpoint.NodeName, "")) } } @@ -502,10 +501,10 @@ func (az *Cloud) cleanupLocalServiceBackendPool( var changed bool if lbs != nil { for _, lb := range *lbs { - lbName := ptr.Deref(lb.Name, "") + lbName := lo.FromPtrOr(lb.Name, "") if lb.BackendAddressPools != nil { for _, bp := range *lb.BackendAddressPools { - bpName := ptr.Deref(bp.Name, "") + bpName := lo.FromPtrOr(bp.Name, "") if localServiceOwnsBackendPool(getServiceName(svc), bpName) { if err := az.DeleteLBBackendPool(ctx, lbName, bpName); err != nil { return nil, err @@ -543,7 +542,7 @@ func (az *Cloud) checkAndApplyLocalServiceBackendPoolUpdates(lb network.LoadBala } currentIPsInBackendPools := make(map[string][]string) for _, bp := range *lb.BackendAddressPools { - bpName := ptr.Deref(bp.Name, "") + bpName := lo.FromPtrOr(bp.Name, "") if localServiceOwnsBackendPool(serviceName, bpName) { var currentIPs []string for _, address := range *bp.LoadBalancerBackendAddresses { diff --git a/pkg/provider/azure_local_services_test.go b/pkg/provider/azure_local_services_test.go index f248467990..8027d0e23d 100644 --- a/pkg/provider/azure_local_services_test.go +++ b/pkg/provider/azure_local_services_test.go @@ -25,17 +25,15 @@ import ( "testing" "time" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" "github.com/stretchr/testify/assert" - "go.uber.org/mock/gomock" - v1 "k8s.io/api/core/v1" discovery_v1 "k8s.io/api/discovery/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/informers" "k8s.io/client-go/kubernetes/fake" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/loadbalancerclient/mockloadbalancerclient" "sigs.k8s.io/cloud-provider-azure/pkg/consts" @@ -395,22 +393,22 @@ func TestLoadBalancerBackendPoolUpdaterFailed(t *testing.T) { func getTestBackendAddressPoolWithIPs(lbName, bpName string, ips []string) network.BackendAddressPool { bp := network.BackendAddressPool{ - ID: ptr.To(fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/%s/backendAddressPools/%s", lbName, bpName)), - Name: ptr.To(bpName), + ID: to.Ptr(fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/%s/backendAddressPools/%s", lbName, bpName)), + Name: to.Ptr(bpName), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ VirtualNetwork: &network.SubResource{ - ID: ptr.To("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks/vnet"), + ID: to.Ptr("/subscriptions/subscriptionID/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks/vnet"), }, - Location: ptr.To("eastus"), + Location: to.Ptr("eastus"), LoadBalancerBackendAddresses: &[]network.LoadBalancerBackendAddress{}, }, } for _, ip := range ips { if len(ip) > 0 { *bp.LoadBalancerBackendAddresses = append(*bp.LoadBalancerBackendAddresses, network.LoadBalancerBackendAddress{ - Name: ptr.To(""), + Name: to.Ptr(""), LoadBalancerBackendAddressPropertiesFormat: &network.LoadBalancerBackendAddressPropertiesFormat{ - IPAddress: ptr.To(ip), + IPAddress: to.Ptr(ip), }, }) } @@ -582,7 +580,7 @@ func TestCheckAndApplyLocalServiceBackendPoolUpdates(t *testing.T) { existingBackendPool := getTestBackendAddressPoolWithIPs("lb1", "default-svc1", []string{"10.0.0.1"}) existingBackendPoolIPv6 := getTestBackendAddressPoolWithIPs("lb1", "default-svc1-ipv6", []string{"fd00::1"}) existingLB := network.LoadBalancer{ - Name: ptr.To("lb1"), + Name: to.Ptr("lb1"), LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ BackendAddressPools: &[]network.BackendAddressPool{ existingBackendPool, diff --git a/pkg/provider/azure_lock.go b/pkg/provider/azure_lock.go index d58a5103f7..ed581fafc1 100644 --- a/pkg/provider/azure_lock.go +++ b/pkg/provider/azure_lock.go @@ -22,12 +22,13 @@ import ( "strings" "time" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/samber/lo" v1 "k8s.io/api/coordination/v1" k8sapierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" "k8s.io/klog/v2" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/consts" ) @@ -97,7 +98,7 @@ func createLeaseIfNotExists( Namespace: leaseNamespace, }, Spec: v1.LeaseSpec{ - LeaseDurationSeconds: ptr.To(leaseDurationSeconds), + LeaseDurationSeconds: to.Ptr(leaseDurationSeconds), }, } @@ -140,7 +141,7 @@ func (l *AzureResourceLocker) acquireLease( // it means the same previous operation failed and the releaseLease // also failed. In this case we should continue acquiring the lease. // This should be a rare case, otherwise we should not acquire the lease. - prevHolder := ptr.Deref(lease.Spec.HolderIdentity, "") + prevHolder := lo.FromPtrOr(lease.Spec.HolderIdentity, "") if !strings.EqualFold(prevHolder, holder) { errMsg := "Lease has not expired yet, another component such as aks rp may be processing another request. This would be automatically recovered after the lease expires." err := errors.New(errMsg) @@ -149,7 +150,7 @@ func (l *AzureResourceLocker) acquireLease( } } - lease.Spec.HolderIdentity = ptr.To(holder) + lease.Spec.HolderIdentity = to.Ptr(holder) now := &metav1.MicroTime{Time: time.Now()} lease.Spec.AcquireTime = now lease.Spec.RenewTime = now @@ -180,12 +181,12 @@ func (l *AzureResourceLocker) acquireLease( } func hasExpired(lease *v1.Lease) bool { - if ptr.Deref(lease.Spec.HolderIdentity, "") == "" { + if lo.FromPtrOr(lease.Spec.HolderIdentity, "") == "" { return true // No holder, hence expired } // Calculate the expiration time - leaseDuration := time.Duration(ptr.Deref(lease.Spec.LeaseDurationSeconds, 0)) * time.Second + leaseDuration := time.Duration(lo.FromPtrOr(lease.Spec.LeaseDurationSeconds, 0)) * time.Second var expirationTime time.Time if lease.Spec.RenewTime != nil { expirationTime = lease.Spec.RenewTime.Add(leaseDuration) @@ -213,7 +214,7 @@ func releaseLease( return err } - prevHolder := ptr.Deref(lease.Spec.HolderIdentity, "") + prevHolder := lo.FromPtrOr(lease.Spec.HolderIdentity, "") if !strings.EqualFold(prevHolder, holder) { logger.Info( "%s is holding the lease instead of %s, no need to release it.", @@ -227,7 +228,7 @@ func releaseLease( return nil } - lease.Spec.HolderIdentity = ptr.To("") + lease.Spec.HolderIdentity = to.Ptr("") if lease.Annotations == nil { lease.Annotations = make(map[string]string) } diff --git a/pkg/provider/azure_privatelinkservice.go b/pkg/provider/azure_privatelinkservice.go index a4c386268e..1f470cdb50 100644 --- a/pkg/provider/azure_privatelinkservice.go +++ b/pkg/provider/azure_privatelinkservice.go @@ -28,15 +28,13 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - + "github.com/samber/lo" v1 "k8s.io/api/core/v1" "k8s.io/klog/v2" - "k8s.io/utils/ptr" azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" "sigs.k8s.io/cloud-provider-azure/pkg/metrics" - fnutil "sigs.k8s.io/cloud-provider-azure/pkg/util/collectionutil" ) // reconcilePrivateLinkService() function makes sure a PLS is created or deleted on @@ -72,7 +70,7 @@ func (az *Cloud) reconcilePrivateLinkService( } fipConfigID := fipConfig.ID - klog.V(2).Infof("reconcilePrivateLinkService for service(%s) - LB fipConfigID(%s) - wantPLS(%t) - createPLS(%t)", serviceName, ptr.Deref(fipConfig.Name, ""), wantPLS, createPLS) + klog.V(2).Infof("reconcilePrivateLinkService for service(%s) - LB fipConfigID(%s) - wantPLS(%t) - createPLS(%t)", serviceName, lo.FromPtrOr(fipConfig.Name, ""), wantPLS, createPLS) request := "ensure_privatelinkservice" if !wantPLS { @@ -94,19 +92,19 @@ func (az *Cloud) reconcilePrivateLinkService( // Secondly, check if there is a private link service already created existingPLS, err := az.plsRepo.Get(ctx, az.getPLSResourceGroup(service), *fipConfigID, azcache.CacheReadTypeDefault) if err != nil { - klog.Errorf("reconcilePrivateLinkService for service(%s): getPrivateLinkService(%s) failed: %v", serviceName, ptr.Deref(fipConfigID, ""), err) + klog.Errorf("reconcilePrivateLinkService for service(%s): getPrivateLinkService(%s) failed: %v", serviceName, lo.FromPtrOr(fipConfigID, ""), err) return err } - exists := !strings.EqualFold(ptr.Deref(existingPLS.ID, ""), consts.PrivateLinkServiceNotExistID) + exists := !strings.EqualFold(lo.FromPtrOr(existingPLS.ID, ""), consts.PrivateLinkServiceNotExistID) if exists { - klog.V(4).Infof("reconcilePrivateLinkService for service(%s): found existing private link service attached(%s)", serviceName, ptr.Deref(existingPLS.Name, "")) + klog.V(4).Infof("reconcilePrivateLinkService for service(%s): found existing private link service attached(%s)", serviceName, lo.FromPtrOr(existingPLS.Name, "")) if !isManagedPrivateLinkSerivce(existingPLS, clusterName) { return fmt.Errorf( "reconcilePrivateLinkService for service(%s) failed: LB frontend(%s) already has unmanaged private link service(%s)", serviceName, - ptr.Deref(fipConfigID, ""), - ptr.Deref(existingPLS.ID, ""), + lo.FromPtrOr(fipConfigID, ""), + lo.FromPtrOr(existingPLS.ID, ""), ) } // If there is an existing private link service, only owner service can update its properties @@ -116,15 +114,15 @@ func (az *Cloud) reconcilePrivateLinkService( return fmt.Errorf( "reconcilePrivateLinkService for service(%s) failed: LB frontend(%s) already has existing private link service(%s) owned by service(%s)", serviceName, - ptr.Deref(fipConfigID, ""), - ptr.Deref(existingPLS.Name, ""), + lo.FromPtrOr(fipConfigID, ""), + lo.FromPtrOr(existingPLS.Name, ""), ownerService, ) } klog.V(2).Infof( "reconcilePrivateLinkService for service(%s): automatically share private link service(%s) owned by service(%s)", serviceName, - ptr.Deref(existingPLS.Name, ""), + lo.FromPtrOr(existingPLS.Name, ""), ownerService, ) return nil @@ -158,7 +156,7 @@ func (az *Cloud) reconcilePrivateLinkService( klog.Errorf("reconcilePrivateLinkService for service(%s) disable PLS network policy failed for pls(%s): %v", serviceName, plsName, err.Error()) return err } - existingPLS.Etag = ptr.To("") + existingPLS.Etag = to.Ptr("") _, err = az.plsRepo.CreateOrUpdate(ctx, az.getPLSResourceGroup(service), *existingPLS) if err != nil { klog.Errorf("reconcilePrivateLinkService for service(%s) abort backoff: pls(%s) - updating: %s", serviceName, plsName, err.Error()) @@ -168,15 +166,15 @@ func (az *Cloud) reconcilePrivateLinkService( } else if !wantPLS { existingPLS, err := az.plsRepo.Get(ctx, az.getPLSResourceGroup(service), *fipConfigID, azcache.CacheReadTypeDefault) if err != nil { - klog.Errorf("reconcilePrivateLinkService for service(%s): getPrivateLinkService(%s) failed: %v", serviceName, ptr.Deref(fipConfigID, ""), err) + klog.Errorf("reconcilePrivateLinkService for service(%s): getPrivateLinkService(%s) failed: %v", serviceName, lo.FromPtrOr(fipConfigID, ""), err) return err } - exists := !strings.EqualFold(ptr.Deref(existingPLS.ID, ""), consts.PrivateLinkServiceNotExistID) + exists := !strings.EqualFold(lo.FromPtrOr(existingPLS.ID, ""), consts.PrivateLinkServiceNotExistID) if exists { deleteErr := az.safeDeletePLS(ctx, existingPLS, service) if deleteErr != nil { - klog.Errorf("reconcilePrivateLinkService for service(%s): deletePLS for frontEnd(%s) failed: %v", serviceName, ptr.Deref(fipConfigID, ""), err) + klog.Errorf("reconcilePrivateLinkService for service(%s): deletePLS for frontEnd(%s) failed: %v", serviceName, lo.FromPtrOr(fipConfigID, ""), err) return deleteErr } } @@ -244,21 +242,21 @@ func (az *Cloud) safeDeletePLS(ctx context.Context, pls *armnetwork.PrivateLinkS peConns := pls.Properties.PrivateEndpointConnections for _, peConn := range peConns { - klog.V(2).Infof("deletePLS: deleting PEConnection %s", ptr.Deref(peConn.Name, "")) - err := az.plsRepo.DeletePEConnection(ctx, az.getPLSResourceGroup(service), ptr.Deref(pls.Name, ""), ptr.Deref(peConn.Name, "")) + klog.V(2).Infof("deletePLS: deleting PEConnection %s", lo.FromPtrOr(peConn.Name, "")) + err := az.plsRepo.DeletePEConnection(ctx, az.getPLSResourceGroup(service), lo.FromPtrOr(pls.Name, ""), lo.FromPtrOr(peConn.Name, "")) if err != nil { return err } } resourceGroup := az.getPLSResourceGroup(service) - plsName := ptr.Deref(pls.Name, "") - lbFrontendID := ptr.Deref((pls.Properties.LoadBalancerFrontendIPConfigurations)[0].ID, "") + plsName := lo.FromPtrOr(pls.Name, "") + lbFrontendID := lo.FromPtrOr((pls.Properties.LoadBalancerFrontendIPConfigurations)[0].ID, "") rerr := az.plsRepo.Delete(ctx, resourceGroup, plsName, lbFrontendID) if rerr != nil { return rerr } - klog.V(2).Infof("safeDeletePLS(%s) finished", ptr.Deref(pls.Name, "")) + klog.V(2).Infof("safeDeletePLS(%s) finished", lo.FromPtrOr(pls.Name, "")) return nil } @@ -273,11 +271,11 @@ func (az *Cloud) getPrivateLinkServiceName( if nameFromService, found := service.Annotations[consts.ServiceAnnotationPLSName]; found { nameFromService = strings.TrimSpace(nameFromService) - if existingName != nil && !strings.EqualFold(ptr.Deref(existingName, ""), nameFromService) { + if existingName != nil && !strings.EqualFold(lo.FromPtrOr(existingName, ""), nameFromService) { return "", fmt.Errorf( "getPrivateLinkServiceName(%s) failed: cannot change existing private link service name (%s) to (%s)", serviceName, - ptr.Deref(existingName, ""), + lo.FromPtrOr(existingName, ""), nameFromService, ) } @@ -285,7 +283,7 @@ func (az *Cloud) getPrivateLinkServiceName( } if existingName != nil { - return ptr.Deref(existingName, ""), nil + return lo.FromPtrOr(existingName, ""), nil } // default PLS name: pls- @@ -412,19 +410,19 @@ func (az *Cloud) reconcilePLSIpConfigs( existingStaticIps := make([]string, 0) for _, ipConfig := range existingPLS.Properties.IPConfigurations { - if !strings.EqualFold(ptr.Deref(subnet.ID, ""), ptr.Deref(ipConfig.Properties.Subnet.ID, "")) { + if !strings.EqualFold(lo.FromPtrOr(subnet.ID, ""), lo.FromPtrOr(ipConfig.Properties.Subnet.ID, "")) { changed = true } if *ipConfig.Properties.PrivateIPAllocationMethod == armnetwork.IPAllocationMethodStatic { - klog.V(10).Infof("Found static IP: %s", ptr.Deref(ipConfig.Properties.PrivateIPAddress, "")) - if _, found := staticIps[ptr.Deref(ipConfig.Properties.PrivateIPAddress, "")]; !found { + klog.V(10).Infof("Found static IP: %s", lo.FromPtrOr(ipConfig.Properties.PrivateIPAddress, "")) + if _, found := staticIps[lo.FromPtrOr(ipConfig.Properties.PrivateIPAddress, "")]; !found { changed = true } - existingStaticIps = append(existingStaticIps, ptr.Deref(ipConfig.Properties.PrivateIPAddress, "")) + existingStaticIps = append(existingStaticIps, lo.FromPtrOr(ipConfig.Properties.PrivateIPAddress, "")) } if *ipConfig.Properties.Primary { if *ipConfig.Properties.PrivateIPAllocationMethod == armnetwork.IPAllocationMethodStatic { - if !strings.EqualFold(primaryIP, ptr.Deref(ipConfig.Properties.PrivateIPAddress, "")) { + if !strings.EqualFold(primaryIP, lo.FromPtrOr(ipConfig.Properties.PrivateIPAddress, "")) { changed = true } } else { @@ -446,7 +444,7 @@ func (az *Cloud) reconcilePLSIpConfigs( if maxPrefixLen <= 0 { return "", fmt.Errorf("reconcilePLSIpConfigs: frontend ipConfig suffix %s is too long (not likely to happen)", suffix) } - prefix := fmt.Sprintf("%s-%s", ptr.Deref(subnet.Name, ""), ptr.Deref(existingPLS.Name, "")) + prefix := fmt.Sprintf("%s-%s", lo.FromPtrOr(subnet.Name, ""), lo.FromPtrOr(existingPLS.Name, "")) if len(prefix) > maxPrefixLen { prefix = prefix[:maxPrefixLen] } @@ -530,14 +528,14 @@ func reconcilePLSFqdn( if len(fqdns) != 0 { changed = true } - } else if !sameContentInSlices(fqdns, fnutil.Map(func(s *string) string { + } else if !sameContentInSlices(fqdns, lo.Map(existingPLS.Properties.Fqdns, func(s *string, _ int) string { return *s - }, existingPLS.Properties.Fqdns)) { + })) { changed = true } if changed { - existingPLS.Properties.Fqdns = fnutil.Map(func(s string) *string { return &s }, fqdns) + existingPLS.Properties.Fqdns = lo.Map(fqdns, func(s string, _ int) *string { return &s }) } return changed } @@ -554,9 +552,9 @@ func reconcilePLSVisibility( if len(visibilitySubs) != 0 { changed = true } - } else if !sameContentInSlices(visibilitySubs, fnutil.Map(func(s *string) string { + } else if !sameContentInSlices(visibilitySubs, lo.Map(existingPLS.Properties.Visibility.Subscriptions, func(s *string, _ int) string { return *s - }, existingPLS.Properties.Visibility.Subscriptions)) { + })) { changed = true } @@ -564,9 +562,9 @@ func reconcilePLSVisibility( if len(autoApprovalSubs) != 0 { changed = true } - } else if !sameContentInSlices(autoApprovalSubs, fnutil.Map(func(s *string) string { + } else if !sameContentInSlices(autoApprovalSubs, lo.Map(existingPLS.Properties.AutoApproval.Subscriptions, func(s *string, _ int) string { return *s - }, existingPLS.Properties.AutoApproval.Subscriptions)) { + })) { changed = true } diff --git a/pkg/provider/azure_privatelinkservice_test.go b/pkg/provider/azure_privatelinkservice_test.go index ac1202b8df..b81c8f8c25 100644 --- a/pkg/provider/azure_privatelinkservice_test.go +++ b/pkg/provider/azure_privatelinkservice_test.go @@ -26,11 +26,11 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" + "github.com/samber/lo" "github.com/stretchr/testify/assert" "go.uber.org/mock/gomock" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" @@ -76,8 +76,8 @@ func TestReconcilePrivateLinkService(t *testing.T) { wantPLS: true, expectedSubnetGet: true, existingSubnet: &armnetwork.Subnet{ - Name: ptr.To("subnet"), - ID: ptr.To("subnetID"), + Name: to.Ptr("subnet"), + ID: to.Ptr("subnetID"), Properties: &armnetwork.SubnetPropertiesFormat{ PrivateLinkServiceNetworkPolicies: to.Ptr(armnetwork.VirtualNetworkPrivateLinkServiceNetworkPoliciesDisabled), }, @@ -85,7 +85,7 @@ func TestReconcilePrivateLinkService(t *testing.T) { expectedPLSList: true, existingPLSList: []*armnetwork.PrivateLinkService{}, expectedPLSCreate: true, - expectedPLS: &armnetwork.PrivateLinkService{Name: ptr.To("pls-fipConfig")}, + expectedPLS: &armnetwork.PrivateLinkService{Name: to.Ptr("pls-fipConfig")}, }, { desc: "reconcilePrivateLinkService should create a new PLS if no existing PLS attached to the LB frontend", @@ -97,8 +97,8 @@ func TestReconcilePrivateLinkService(t *testing.T) { wantPLS: true, expectedSubnetGet: true, existingSubnet: &armnetwork.Subnet{ - Name: ptr.To("subnet"), - ID: ptr.To("subnetID"), + Name: to.Ptr("subnet"), + ID: to.Ptr("subnetID"), Properties: &armnetwork.SubnetPropertiesFormat{ PrivateLinkServiceNetworkPolicies: to.Ptr(armnetwork.VirtualNetworkPrivateLinkServiceNetworkPoliciesDisabled), }, @@ -106,7 +106,7 @@ func TestReconcilePrivateLinkService(t *testing.T) { expectedPLSList: true, existingPLSList: []*armnetwork.PrivateLinkService{}, expectedPLSCreate: true, - expectedPLS: &armnetwork.PrivateLinkService{Name: ptr.To("testpls")}, + expectedPLS: &armnetwork.PrivateLinkService{Name: to.Ptr("testpls")}, }, { desc: "reconcilePrivateLinkService should report error if existing PLS attached to LB frontEnd is unmanaged", @@ -119,15 +119,15 @@ func TestReconcilePrivateLinkService(t *testing.T) { expectedPLSList: true, existingPLSList: []*armnetwork.PrivateLinkService{ { - Name: ptr.To("testpls"), + Name: to.Ptr("testpls"), Properties: &armnetwork.PrivateLinkServiceProperties{ - LoadBalancerFrontendIPConfigurations: []*armnetwork.FrontendIPConfiguration{{ID: ptr.To("fipConfigID")}}, + LoadBalancerFrontendIPConfigurations: []*armnetwork.FrontendIPConfiguration{{ID: to.Ptr("fipConfigID")}}, IPConfigurations: []*armnetwork.PrivateLinkServiceIPConfiguration{ { Properties: &armnetwork.PrivateLinkServiceIPConfigurationProperties{ PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), - Subnet: &armnetwork.Subnet{ID: ptr.To("subnetID")}, - Primary: ptr.To(true), + Subnet: &armnetwork.Subnet{ID: to.Ptr("subnetID")}, + Primary: to.Ptr(true), PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, @@ -148,23 +148,23 @@ func TestReconcilePrivateLinkService(t *testing.T) { expectedPLSList: true, existingPLSList: []*armnetwork.PrivateLinkService{ { - Name: ptr.To("testpls"), + Name: to.Ptr("testpls"), Properties: &armnetwork.PrivateLinkServiceProperties{ - LoadBalancerFrontendIPConfigurations: []*armnetwork.FrontendIPConfiguration{{ID: ptr.To("fipConfigID")}}, + LoadBalancerFrontendIPConfigurations: []*armnetwork.FrontendIPConfiguration{{ID: to.Ptr("fipConfigID")}}, IPConfigurations: []*armnetwork.PrivateLinkServiceIPConfiguration{ { Properties: &armnetwork.PrivateLinkServiceIPConfigurationProperties{ PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), - Subnet: &armnetwork.Subnet{ID: ptr.To("subnetID")}, - Primary: ptr.To(true), + Subnet: &armnetwork.Subnet{ID: to.Ptr("subnetID")}, + Primary: to.Ptr(true), PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, }, }, Tags: map[string]*string{ - consts.ClusterNameTagKey: ptr.To(testClusterName), - consts.OwnerServiceTagKey: ptr.To("default/test1"), + consts.ClusterNameTagKey: to.Ptr(testClusterName), + consts.OwnerServiceTagKey: to.Ptr("default/test1"), }, }, }, @@ -180,24 +180,24 @@ func TestReconcilePrivateLinkService(t *testing.T) { expectedPLSList: true, existingPLSList: []*armnetwork.PrivateLinkService{ { - Name: ptr.To("testpls"), + Name: to.Ptr("testpls"), Properties: &armnetwork.PrivateLinkServiceProperties{ - LoadBalancerFrontendIPConfigurations: []*armnetwork.FrontendIPConfiguration{{ID: ptr.To("fipConfigID")}}, + LoadBalancerFrontendIPConfigurations: []*armnetwork.FrontendIPConfiguration{{ID: to.Ptr("fipConfigID")}}, IPConfigurations: []*armnetwork.PrivateLinkServiceIPConfiguration{ { Properties: &armnetwork.PrivateLinkServiceIPConfigurationProperties{ PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), - PrivateIPAddress: ptr.To("10.2.0.4"), - Subnet: &armnetwork.Subnet{ID: ptr.To("subnetID")}, - Primary: ptr.To(true), + PrivateIPAddress: to.Ptr("10.2.0.4"), + Subnet: &armnetwork.Subnet{ID: to.Ptr("subnetID")}, + Primary: to.Ptr(true), PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, }, }, Tags: map[string]*string{ - consts.ClusterNameTagKey: ptr.To(testClusterName), - consts.OwnerServiceTagKey: ptr.To("default/test1"), + consts.ClusterNameTagKey: to.Ptr(testClusterName), + consts.OwnerServiceTagKey: to.Ptr("default/test1"), }, }, }, @@ -212,8 +212,8 @@ func TestReconcilePrivateLinkService(t *testing.T) { wantPLS: true, expectedSubnetGet: true, existingSubnet: &armnetwork.Subnet{ - Name: ptr.To("subnet"), - ID: ptr.To("subnetID"), + Name: to.Ptr("subnet"), + ID: to.Ptr("subnetID"), Properties: &armnetwork.SubnetPropertiesFormat{ PrivateLinkServiceNetworkPolicies: to.Ptr(armnetwork.VirtualNetworkPrivateLinkServiceNetworkPoliciesDisabled), }, @@ -221,23 +221,23 @@ func TestReconcilePrivateLinkService(t *testing.T) { expectedPLSList: true, existingPLSList: []*armnetwork.PrivateLinkService{ { - Name: ptr.To("testpls"), + Name: to.Ptr("testpls"), Properties: &armnetwork.PrivateLinkServiceProperties{ - LoadBalancerFrontendIPConfigurations: []*armnetwork.FrontendIPConfiguration{{ID: ptr.To("fipConfigID")}}, + LoadBalancerFrontendIPConfigurations: []*armnetwork.FrontendIPConfiguration{{ID: to.Ptr("fipConfigID")}}, IPConfigurations: []*armnetwork.PrivateLinkServiceIPConfiguration{ { Properties: &armnetwork.PrivateLinkServiceIPConfigurationProperties{ PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), - Subnet: &armnetwork.Subnet{ID: ptr.To("subnetID")}, - Primary: ptr.To(true), + Subnet: &armnetwork.Subnet{ID: to.Ptr("subnetID")}, + Primary: to.Ptr(true), PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, }, }, Tags: map[string]*string{ - consts.ClusterNameTagKey: ptr.To(testClusterName), - consts.OwnerServiceTagKey: ptr.To("default/test"), + consts.ClusterNameTagKey: to.Ptr(testClusterName), + consts.OwnerServiceTagKey: to.Ptr("default/test"), }, }, }, @@ -253,8 +253,8 @@ func TestReconcilePrivateLinkService(t *testing.T) { wantPLS: true, expectedSubnetGet: true, existingSubnet: &armnetwork.Subnet{ - Name: ptr.To("subnet"), - ID: ptr.To("subnetID"), + Name: to.Ptr("subnet"), + ID: to.Ptr("subnetID"), Properties: &armnetwork.SubnetPropertiesFormat{ PrivateLinkServiceNetworkPolicies: to.Ptr(armnetwork.VirtualNetworkPrivateLinkServiceNetworkPoliciesDisabled), }, @@ -262,28 +262,28 @@ func TestReconcilePrivateLinkService(t *testing.T) { expectedPLSList: true, existingPLSList: []*armnetwork.PrivateLinkService{ { - Name: ptr.To("testpls"), + Name: to.Ptr("testpls"), Properties: &armnetwork.PrivateLinkServiceProperties{ - LoadBalancerFrontendIPConfigurations: []*armnetwork.FrontendIPConfiguration{{ID: ptr.To("fipConfigID")}}, + LoadBalancerFrontendIPConfigurations: []*armnetwork.FrontendIPConfiguration{{ID: to.Ptr("fipConfigID")}}, IPConfigurations: []*armnetwork.PrivateLinkServiceIPConfiguration{ { Properties: &armnetwork.PrivateLinkServiceIPConfigurationProperties{ PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), - Subnet: &armnetwork.Subnet{ID: ptr.To("subnetID")}, - Primary: ptr.To(true), + Subnet: &armnetwork.Subnet{ID: to.Ptr("subnetID")}, + Primary: to.Ptr(true), PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, }, }, Tags: map[string]*string{ - consts.ClusterNameTagKey: ptr.To(testClusterName), - consts.OwnerServiceTagKey: ptr.To("default/test"), + consts.ClusterNameTagKey: to.Ptr(testClusterName), + consts.OwnerServiceTagKey: to.Ptr("default/test"), }, }, }, expectedPLSCreate: true, - expectedPLS: &armnetwork.PrivateLinkService{Name: ptr.To("testpls")}, + expectedPLS: &armnetwork.PrivateLinkService{Name: to.Ptr("testpls")}, }, { desc: "reconcilePrivateLinkService should not do anything if no existing PLS attached to the LB frontend when deleting", @@ -295,9 +295,9 @@ func TestReconcilePrivateLinkService(t *testing.T) { expectedPLSList: true, existingPLSList: []*armnetwork.PrivateLinkService{ { - Name: ptr.To("testpls"), + Name: to.Ptr("testpls"), Properties: &armnetwork.PrivateLinkServiceProperties{ - LoadBalancerFrontendIPConfigurations: []*armnetwork.FrontendIPConfiguration{{ID: ptr.To("fipConfigID2")}}, + LoadBalancerFrontendIPConfigurations: []*armnetwork.FrontendIPConfiguration{{ID: to.Ptr("fipConfigID2")}}, }, }, }, @@ -312,9 +312,9 @@ func TestReconcilePrivateLinkService(t *testing.T) { expectedPLSList: true, existingPLSList: []*armnetwork.PrivateLinkService{ { - Name: ptr.To("testpls"), + Name: to.Ptr("testpls"), Properties: &armnetwork.PrivateLinkServiceProperties{ - LoadBalancerFrontendIPConfigurations: []*armnetwork.FrontendIPConfiguration{{ID: ptr.To("fipConfigID")}}, + LoadBalancerFrontendIPConfigurations: []*armnetwork.FrontendIPConfiguration{{ID: to.Ptr("fipConfigID")}}, }, }, }, @@ -327,11 +327,11 @@ func TestReconcilePrivateLinkService(t *testing.T) { az := GetTestCloud(ctrl) service := getTestServiceWithAnnotation("test", test.annotations, false, 80) fipConfig := &network.FrontendIPConfiguration{ - Name: ptr.To("fipConfig"), - ID: ptr.To("fipConfigID"), + Name: to.Ptr("fipConfig"), + ID: to.Ptr("fipConfigID"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PublicIPAddress: &network.PublicIPAddress{ - ID: ptr.To("pipID"), + ID: to.Ptr("pipID"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAddressVersion: network.IPv4, }, @@ -411,7 +411,7 @@ func TestDisablePLSNetworkPolicy(t *testing.T) { { desc: "disablePLSNetworkPolicy shall not update subnet if pls-network-policy is disabled", subnet: &armnetwork.Subnet{ - Name: ptr.To("plsSubnet"), + Name: to.Ptr("plsSubnet"), Properties: &armnetwork.SubnetPropertiesFormat{ PrivateLinkServiceNetworkPolicies: to.Ptr(armnetwork.VirtualNetworkPrivateLinkServiceNetworkPoliciesDisabled), }, @@ -421,7 +421,7 @@ func TestDisablePLSNetworkPolicy(t *testing.T) { { desc: "disablePLSNetworkPolicy shall update subnet if pls-network-policy is enabled", subnet: &armnetwork.Subnet{ - Name: ptr.To("plsSubnet"), + Name: to.Ptr("plsSubnet"), Properties: &armnetwork.SubnetPropertiesFormat{ PrivateLinkServiceNetworkPolicies: to.Ptr(armnetwork.VirtualNetworkPrivateLinkServiceNetworkPoliciesEnabled), }, @@ -441,7 +441,7 @@ func TestDisablePLSNetworkPolicy(t *testing.T) { mockSubnetsClient.EXPECT().Get(gomock.Any(), "rg", "vnet", "plsSubnet").Return(test.subnet, nil).Times(1) if test.expectedSubnetUpdate { mockSubnetsClient.EXPECT().CreateOrUpdate(gomock.Any(), "rg", "vnet", "plsSubnet", armnetwork.Subnet{ - Name: ptr.To("plsSubnet"), + Name: to.Ptr("plsSubnet"), Properties: &armnetwork.SubnetPropertiesFormat{ PrivateLinkServiceNetworkPolicies: to.Ptr(armnetwork.VirtualNetworkPrivateLinkServiceNetworkPoliciesDisabled), }, @@ -464,12 +464,12 @@ func TestSafeDeletePLS(t *testing.T) { { desc: "safeDeletePLS shall delete all PE connections and pls itself", pls: &armnetwork.PrivateLinkService{ - Name: ptr.To("testpls"), + Name: to.Ptr("testpls"), Properties: &armnetwork.PrivateLinkServiceProperties{ - LoadBalancerFrontendIPConfigurations: []*armnetwork.FrontendIPConfiguration{{ID: ptr.To("FipConfigID")}}, + LoadBalancerFrontendIPConfigurations: []*armnetwork.FrontendIPConfiguration{{ID: to.Ptr("FipConfigID")}}, PrivateEndpointConnections: []*armnetwork.PrivateEndpointConnection{ - {Name: ptr.To("pe1")}, - {Name: ptr.To("pe2")}, + {Name: to.Ptr("pe1")}, + {Name: to.Ptr("pe2")}, }, }, }, @@ -513,14 +513,14 @@ func TestGetPrivateLinkServiceName(t *testing.T) { desc: "If pls name does not set, and service does not configure, sets it as default(pls-fipConfigName)", pls: &armnetwork.PrivateLinkService{}, fipConfig: &network.FrontendIPConfiguration{ - Name: ptr.To("fipname"), + Name: to.Ptr("fipname"), }, expectedName: "pls-fipname", }, { desc: "If pls name is not equal to service configuration, error should be reported", pls: &armnetwork.PrivateLinkService{ - Name: ptr.To("testpls"), + Name: to.Ptr("testpls"), }, annotations: map[string]string{ consts.ServiceAnnotationPLSName: "testpls1", @@ -530,7 +530,7 @@ func TestGetPrivateLinkServiceName(t *testing.T) { { desc: "If pls name is same as service configuration, simply return it", pls: &armnetwork.PrivateLinkService{ - Name: ptr.To("testpls"), + Name: to.Ptr("testpls"), }, annotations: map[string]string{ consts.ServiceAnnotationPLSName: "testpls", @@ -574,13 +574,13 @@ func TestGetExpectedPrivateLinkService(t *testing.T) { } plsName := "testPLS" clusterName := testClusterName - fipConfig := &network.FrontendIPConfiguration{ID: ptr.To("fipConfigID")} + fipConfig := &network.FrontendIPConfiguration{ID: to.Ptr("fipConfigID")} pls := &armnetwork.PrivateLinkService{Properties: &armnetwork.PrivateLinkServiceProperties{}} subnetClient := cloud.subnetRepo.(*subnet.MockRepository) subnetClient.EXPECT().Get(gomock.Any(), "rg", "vnet", "subnet").Return( &armnetwork.Subnet{ - ID: ptr.To("subnetID"), - Name: ptr.To("subnet"), + ID: to.Ptr("subnetID"), + Name: to.Ptr("subnet"), }, nil).MaxTimes(1) dirtyPLS, err := cloud.getExpectedPrivateLinkService(context.TODO(), pls, &plsName, &clusterName, service, fipConfig) @@ -594,31 +594,31 @@ func TestGetExpectedPrivateLinkService(t *testing.T) { expectedConfigs := []*armnetwork.PrivateLinkServiceIPConfiguration{ { - Name: ptr.To("subnet-testPLS-static-10.2.0.4"), + Name: to.Ptr("subnet-testPLS-static-10.2.0.4"), Properties: &armnetwork.PrivateLinkServiceIPConfigurationProperties{ PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), - PrivateIPAddress: ptr.To("10.2.0.4"), - Subnet: &armnetwork.Subnet{ID: ptr.To("subnetID")}, - Primary: ptr.To(true), + PrivateIPAddress: to.Ptr("10.2.0.4"), + Subnet: &armnetwork.Subnet{ID: to.Ptr("subnetID")}, + Primary: to.Ptr(true), PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, { - Name: ptr.To("subnet-testPLS-static-10.2.0.5"), + Name: to.Ptr("subnet-testPLS-static-10.2.0.5"), Properties: &armnetwork.PrivateLinkServiceIPConfigurationProperties{ PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), - PrivateIPAddress: ptr.To("10.2.0.5"), - Subnet: &armnetwork.Subnet{ID: ptr.To("subnetID")}, - Primary: ptr.To(false), + PrivateIPAddress: to.Ptr("10.2.0.5"), + Subnet: &armnetwork.Subnet{ID: to.Ptr("subnetID")}, + Primary: to.Ptr(false), PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, { - Name: ptr.To("subnet-testPLS-dynamic-0"), + Name: to.Ptr("subnet-testPLS-dynamic-0"), Properties: &armnetwork.PrivateLinkServiceIPConfigurationProperties{ PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), - Subnet: &armnetwork.Subnet{ID: ptr.To("subnetID")}, - Primary: ptr.To(false), + Subnet: &armnetwork.Subnet{ID: to.Ptr("subnetID")}, + Primary: to.Ptr(false), PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, @@ -677,11 +677,11 @@ func TestReconcilePLSIpConfigs(t *testing.T) { plsName: "testpls", expectedIPConfigs: []*armnetwork.PrivateLinkServiceIPConfiguration{ { - Name: ptr.To("subnet-testpls-dynamic-0"), + Name: to.Ptr("subnet-testpls-dynamic-0"), Properties: &armnetwork.PrivateLinkServiceIPConfigurationProperties{ PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), - Subnet: &armnetwork.Subnet{ID: ptr.To("subnetID")}, - Primary: ptr.To(true), + Subnet: &armnetwork.Subnet{ID: to.Ptr("subnetID")}, + Primary: to.Ptr(true), PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, @@ -696,31 +696,31 @@ func TestReconcilePLSIpConfigs(t *testing.T) { }, existingIPConfigs: []*armnetwork.PrivateLinkServiceIPConfiguration{ { - Name: ptr.To("subnet-testpls-dynamic-0"), + Name: to.Ptr("subnet-testpls-dynamic-0"), Properties: &armnetwork.PrivateLinkServiceIPConfigurationProperties{ PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), - Subnet: &armnetwork.Subnet{ID: ptr.To("subnetID")}, - Primary: ptr.To(true), + Subnet: &armnetwork.Subnet{ID: to.Ptr("subnetID")}, + Primary: to.Ptr(true), PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, }, expectedIPConfigs: []*armnetwork.PrivateLinkServiceIPConfiguration{ { - Name: ptr.To("subnet-testpls-dynamic-0"), + Name: to.Ptr("subnet-testpls-dynamic-0"), Properties: &armnetwork.PrivateLinkServiceIPConfigurationProperties{ PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), - Subnet: &armnetwork.Subnet{ID: ptr.To("subnetID")}, - Primary: ptr.To(true), + Subnet: &armnetwork.Subnet{ID: to.Ptr("subnetID")}, + Primary: to.Ptr(true), PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, { - Name: ptr.To("subnet-testpls-dynamic-1"), + Name: to.Ptr("subnet-testpls-dynamic-1"), Properties: &armnetwork.PrivateLinkServiceIPConfigurationProperties{ PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), - Subnet: &armnetwork.Subnet{ID: ptr.To("subnetID")}, - Primary: ptr.To(false), + Subnet: &armnetwork.Subnet{ID: to.Ptr("subnetID")}, + Primary: to.Ptr(false), PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, @@ -732,22 +732,22 @@ func TestReconcilePLSIpConfigs(t *testing.T) { plsName: "testpls", existingIPConfigs: []*armnetwork.PrivateLinkServiceIPConfiguration{ { - Name: ptr.To("subnet-testpls-dynamic-0"), + Name: to.Ptr("subnet-testpls-dynamic-0"), Properties: &armnetwork.PrivateLinkServiceIPConfigurationProperties{ PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), - Subnet: &armnetwork.Subnet{ID: ptr.To("subnetID1")}, - Primary: ptr.To(true), + Subnet: &armnetwork.Subnet{ID: to.Ptr("subnetID1")}, + Primary: to.Ptr(true), PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, }, expectedIPConfigs: []*armnetwork.PrivateLinkServiceIPConfiguration{ { - Name: ptr.To("subnet-testpls-dynamic-0"), + Name: to.Ptr("subnet-testpls-dynamic-0"), Properties: &armnetwork.PrivateLinkServiceIPConfigurationProperties{ PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), - Subnet: &armnetwork.Subnet{ID: ptr.To("subnetID")}, - Primary: ptr.To(true), + Subnet: &armnetwork.Subnet{ID: to.Ptr("subnetID")}, + Primary: to.Ptr(true), PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, @@ -763,32 +763,32 @@ func TestReconcilePLSIpConfigs(t *testing.T) { }, existingIPConfigs: []*armnetwork.PrivateLinkServiceIPConfiguration{ { - Name: ptr.To("subnet-testpls-dynamic-0"), + Name: to.Ptr("subnet-testpls-dynamic-0"), Properties: &armnetwork.PrivateLinkServiceIPConfigurationProperties{ PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), - Subnet: &armnetwork.Subnet{ID: ptr.To("subnetID")}, - Primary: ptr.To(true), + Subnet: &armnetwork.Subnet{ID: to.Ptr("subnetID")}, + Primary: to.Ptr(true), PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, }, expectedIPConfigs: []*armnetwork.PrivateLinkServiceIPConfiguration{ { - Name: ptr.To("subnet-testpls-static-10.2.0.4"), + Name: to.Ptr("subnet-testpls-static-10.2.0.4"), Properties: &armnetwork.PrivateLinkServiceIPConfigurationProperties{ PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), - PrivateIPAddress: ptr.To("10.2.0.4"), - Subnet: &armnetwork.Subnet{ID: ptr.To("subnetID")}, - Primary: ptr.To(true), + PrivateIPAddress: to.Ptr("10.2.0.4"), + Subnet: &armnetwork.Subnet{ID: to.Ptr("subnetID")}, + Primary: to.Ptr(true), PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, { - Name: ptr.To("subnet-testpls-dynamic-0"), + Name: to.Ptr("subnet-testpls-dynamic-0"), Properties: &armnetwork.PrivateLinkServiceIPConfigurationProperties{ PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), - Subnet: &armnetwork.Subnet{ID: ptr.To("subnetID")}, - Primary: ptr.To(false), + Subnet: &armnetwork.Subnet{ID: to.Ptr("subnetID")}, + Primary: to.Ptr(false), PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, @@ -800,23 +800,23 @@ func TestReconcilePLSIpConfigs(t *testing.T) { plsName: "testpls", existingIPConfigs: []*armnetwork.PrivateLinkServiceIPConfiguration{ { - Name: ptr.To("subnet-testpls-static-10.2.0.4"), + Name: to.Ptr("subnet-testpls-static-10.2.0.4"), Properties: &armnetwork.PrivateLinkServiceIPConfigurationProperties{ PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), - Subnet: &armnetwork.Subnet{ID: ptr.To("subnetID")}, - PrivateIPAddress: ptr.To("10.2.0.4"), - Primary: ptr.To(true), + Subnet: &armnetwork.Subnet{ID: to.Ptr("subnetID")}, + PrivateIPAddress: to.Ptr("10.2.0.4"), + Primary: to.Ptr(true), PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, }, expectedIPConfigs: []*armnetwork.PrivateLinkServiceIPConfiguration{ { - Name: ptr.To("subnet-testpls-dynamic-0"), + Name: to.Ptr("subnet-testpls-dynamic-0"), Properties: &armnetwork.PrivateLinkServiceIPConfigurationProperties{ PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), - Subnet: &armnetwork.Subnet{ID: ptr.To("subnetID")}, - Primary: ptr.To(true), + Subnet: &armnetwork.Subnet{ID: to.Ptr("subnetID")}, + Primary: to.Ptr(true), PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, @@ -831,24 +831,24 @@ func TestReconcilePLSIpConfigs(t *testing.T) { }, existingIPConfigs: []*armnetwork.PrivateLinkServiceIPConfiguration{ { - Name: ptr.To("subnet-testpls-static-10.2.0.4"), + Name: to.Ptr("subnet-testpls-static-10.2.0.4"), Properties: &armnetwork.PrivateLinkServiceIPConfigurationProperties{ PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), - PrivateIPAddress: ptr.To("10.2.0.4"), - Subnet: &armnetwork.Subnet{ID: ptr.To("subnetID")}, - Primary: ptr.To(true), + PrivateIPAddress: to.Ptr("10.2.0.4"), + Subnet: &armnetwork.Subnet{ID: to.Ptr("subnetID")}, + Primary: to.Ptr(true), PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, }, expectedIPConfigs: []*armnetwork.PrivateLinkServiceIPConfiguration{ { - Name: ptr.To("subnet-testpls-static-10.2.0.5"), + Name: to.Ptr("subnet-testpls-static-10.2.0.5"), Properties: &armnetwork.PrivateLinkServiceIPConfigurationProperties{ PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), - PrivateIPAddress: ptr.To("10.2.0.5"), - Subnet: &armnetwork.Subnet{ID: ptr.To("subnetID")}, - Primary: ptr.To(true), + PrivateIPAddress: to.Ptr("10.2.0.5"), + Subnet: &armnetwork.Subnet{ID: to.Ptr("subnetID")}, + Primary: to.Ptr(true), PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, @@ -860,22 +860,22 @@ func TestReconcilePLSIpConfigs(t *testing.T) { plsName: "testpls", existingIPConfigs: []*armnetwork.PrivateLinkServiceIPConfiguration{ { - Name: ptr.To("subnet-testpls-dynamic-0"), + Name: to.Ptr("subnet-testpls-dynamic-0"), Properties: &armnetwork.PrivateLinkServiceIPConfigurationProperties{ PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), - Subnet: &armnetwork.Subnet{ID: ptr.To("subnetID")}, - Primary: ptr.To(true), + Subnet: &armnetwork.Subnet{ID: to.Ptr("subnetID")}, + Primary: to.Ptr(true), PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, }, expectedIPConfigs: []*armnetwork.PrivateLinkServiceIPConfiguration{ { - Name: ptr.To("subnet-testpls-dynamic-0"), + Name: to.Ptr("subnet-testpls-dynamic-0"), Properties: &armnetwork.PrivateLinkServiceIPConfigurationProperties{ PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), - Subnet: &armnetwork.Subnet{ID: ptr.To("subnetID")}, - Primary: ptr.To(true), + Subnet: &armnetwork.Subnet{ID: to.Ptr("subnetID")}, + Primary: to.Ptr(true), PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, @@ -889,24 +889,24 @@ func TestReconcilePLSIpConfigs(t *testing.T) { }, existingIPConfigs: []*armnetwork.PrivateLinkServiceIPConfiguration{ { - Name: ptr.To("subnet-testpls-static-10.2.0.5"), + Name: to.Ptr("subnet-testpls-static-10.2.0.5"), Properties: &armnetwork.PrivateLinkServiceIPConfigurationProperties{ PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), - PrivateIPAddress: ptr.To("10.2.0.5"), - Subnet: &armnetwork.Subnet{ID: ptr.To("subnetID")}, - Primary: ptr.To(true), + PrivateIPAddress: to.Ptr("10.2.0.5"), + Subnet: &armnetwork.Subnet{ID: to.Ptr("subnetID")}, + Primary: to.Ptr(true), PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, }, expectedIPConfigs: []*armnetwork.PrivateLinkServiceIPConfiguration{ { - Name: ptr.To("subnet-testpls-static-10.2.0.5"), + Name: to.Ptr("subnet-testpls-static-10.2.0.5"), Properties: &armnetwork.PrivateLinkServiceIPConfigurationProperties{ PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), - PrivateIPAddress: ptr.To("10.2.0.5"), - Subnet: &armnetwork.Subnet{ID: ptr.To("subnetID")}, - Primary: ptr.To(true), + PrivateIPAddress: to.Ptr("10.2.0.5"), + Subnet: &armnetwork.Subnet{ID: to.Ptr("subnetID")}, + Primary: to.Ptr(true), PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, @@ -922,21 +922,21 @@ func TestReconcilePLSIpConfigs(t *testing.T) { existingIPConfigs: []*armnetwork.PrivateLinkServiceIPConfiguration{}, expectedIPConfigs: []*armnetwork.PrivateLinkServiceIPConfiguration{ { - Name: ptr.To("subnet-" + strings.Repeat("12345678", 7) + "1" + "-static-10.2.0.5"), + Name: to.Ptr("subnet-" + strings.Repeat("12345678", 7) + "1" + "-static-10.2.0.5"), Properties: &armnetwork.PrivateLinkServiceIPConfigurationProperties{ PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), - PrivateIPAddress: ptr.To("10.2.0.5"), - Subnet: &armnetwork.Subnet{ID: ptr.To("subnetID")}, - Primary: ptr.To(true), + PrivateIPAddress: to.Ptr("10.2.0.5"), + Subnet: &armnetwork.Subnet{ID: to.Ptr("subnetID")}, + Primary: to.Ptr(true), PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, { - Name: ptr.To("subnet-" + strings.Repeat("12345678", 7) + "1234567" + "-dynamic-0"), + Name: to.Ptr("subnet-" + strings.Repeat("12345678", 7) + "1234567" + "-dynamic-0"), Properties: &armnetwork.PrivateLinkServiceIPConfigurationProperties{ PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), - Subnet: &armnetwork.Subnet{ID: ptr.To("subnetID")}, - Primary: ptr.To(false), + Subnet: &armnetwork.Subnet{ID: to.Ptr("subnetID")}, + Primary: to.Ptr(false), PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, @@ -952,42 +952,42 @@ func TestReconcilePLSIpConfigs(t *testing.T) { }, existingIPConfigs: []*armnetwork.PrivateLinkServiceIPConfiguration{ { - Name: ptr.To("subnet-" + strings.Repeat("12345678", 7) + "1" + "-static-10.2.0.5"), + Name: to.Ptr("subnet-" + strings.Repeat("12345678", 7) + "1" + "-static-10.2.0.5"), Properties: &armnetwork.PrivateLinkServiceIPConfigurationProperties{ PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), - PrivateIPAddress: ptr.To("10.2.0.5"), - Subnet: &armnetwork.Subnet{ID: ptr.To("subnetID")}, - Primary: ptr.To(true), + PrivateIPAddress: to.Ptr("10.2.0.5"), + Subnet: &armnetwork.Subnet{ID: to.Ptr("subnetID")}, + Primary: to.Ptr(true), PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, { - Name: ptr.To("subnet-" + strings.Repeat("12345678", 7) + "1234567" + "-dynamic-0"), + Name: to.Ptr("subnet-" + strings.Repeat("12345678", 7) + "1234567" + "-dynamic-0"), Properties: &armnetwork.PrivateLinkServiceIPConfigurationProperties{ PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), - Subnet: &armnetwork.Subnet{ID: ptr.To("subnetID")}, - Primary: ptr.To(false), + Subnet: &armnetwork.Subnet{ID: to.Ptr("subnetID")}, + Primary: to.Ptr(false), PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, }, expectedIPConfigs: []*armnetwork.PrivateLinkServiceIPConfiguration{ { - Name: ptr.To("subnet-" + strings.Repeat("12345678", 7) + "1" + "-static-10.2.0.5"), + Name: to.Ptr("subnet-" + strings.Repeat("12345678", 7) + "1" + "-static-10.2.0.5"), Properties: &armnetwork.PrivateLinkServiceIPConfigurationProperties{ PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodStatic), - PrivateIPAddress: ptr.To("10.2.0.5"), - Subnet: &armnetwork.Subnet{ID: ptr.To("subnetID")}, - Primary: ptr.To(true), + PrivateIPAddress: to.Ptr("10.2.0.5"), + Subnet: &armnetwork.Subnet{ID: to.Ptr("subnetID")}, + Primary: to.Ptr(true), PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, { - Name: ptr.To("subnet-" + strings.Repeat("12345678", 7) + "1234567" + "-dynamic-0"), + Name: to.Ptr("subnet-" + strings.Repeat("12345678", 7) + "1234567" + "-dynamic-0"), Properties: &armnetwork.PrivateLinkServiceIPConfigurationProperties{ PrivateIPAllocationMethod: to.Ptr(armnetwork.IPAllocationMethodDynamic), - Subnet: &armnetwork.Subnet{ID: ptr.To("subnetID")}, - Primary: ptr.To(false), + Subnet: &armnetwork.Subnet{ID: to.Ptr("subnetID")}, + Primary: to.Ptr(false), PrivateIPAddressVersion: to.Ptr(armnetwork.IPVersionIPv4), }, }, @@ -1003,7 +1003,7 @@ func TestReconcilePLSIpConfigs(t *testing.T) { }, } pls := &armnetwork.PrivateLinkService{ - Name: ptr.To(test.plsName), + Name: to.Ptr(test.plsName), Properties: &armnetwork.PrivateLinkServiceProperties{ IPConfigurations: test.existingIPConfigs, }, @@ -1011,8 +1011,8 @@ func TestReconcilePLSIpConfigs(t *testing.T) { subnetClient := cloud.subnetRepo.(*subnet.MockRepository) subnetClient.EXPECT().Get(gomock.Any(), "rg", "vnet", "subnet").Return( &armnetwork.Subnet{ - ID: ptr.To("subnetID"), - Name: ptr.To("subnet"), + ID: to.Ptr("subnetID"), + Name: to.Ptr("subnet"), }, test.getSubnetError).MaxTimes(1) changed, err := cloud.reconcilePLSIpConfigs(context.TODO(), pls, service) @@ -1030,10 +1030,10 @@ func testSamePLSIpConfigs(t *testing.T, actual []*armnetwork.PrivateLinkServiceI actualIPConfigs := make(map[string]armnetwork.PrivateLinkServiceIPConfiguration) expectedIPConfigs := make(map[string]armnetwork.PrivateLinkServiceIPConfiguration) for _, ipConfig := range actual { - actualIPConfigs[ptr.Deref(ipConfig.Name, "")] = *ipConfig + actualIPConfigs[lo.FromPtrOr(ipConfig.Name, "")] = *ipConfig } for _, ipConfig := range expected { - expectedIPConfigs[ptr.Deref(ipConfig.Name, "")] = *ipConfig + expectedIPConfigs[lo.FromPtrOr(ipConfig.Name, "")] = *ipConfig } for name, expectedIPConfig := range expectedIPConfigs { @@ -1112,10 +1112,10 @@ func TestReconcilePLSEnableProxyProtocol(t *testing.T) { }, pls: &armnetwork.PrivateLinkService{ Properties: &armnetwork.PrivateLinkServiceProperties{ - EnableProxyProtocol: ptr.To(false), + EnableProxyProtocol: to.Ptr(false), }, }, - expectedEnabled: ptr.To(false), + expectedEnabled: to.Ptr(false), }, { desc: "true service enableProxyProto and true pls enableProxyProto should not trigger any change", @@ -1124,10 +1124,10 @@ func TestReconcilePLSEnableProxyProtocol(t *testing.T) { }, pls: &armnetwork.PrivateLinkService{ Properties: &armnetwork.PrivateLinkServiceProperties{ - EnableProxyProtocol: ptr.To(true), + EnableProxyProtocol: to.Ptr(true), }, }, - expectedEnabled: ptr.To(true), + expectedEnabled: to.Ptr(true), }, { desc: "true service enableProxyProto and empty pls enableProxyProto should trigger update", @@ -1137,7 +1137,7 @@ func TestReconcilePLSEnableProxyProtocol(t *testing.T) { pls: &armnetwork.PrivateLinkService{ Properties: &armnetwork.PrivateLinkServiceProperties{}, }, - expectedEnabled: ptr.To(true), + expectedEnabled: to.Ptr(true), expectedChanged: true, }, { @@ -1147,10 +1147,10 @@ func TestReconcilePLSEnableProxyProtocol(t *testing.T) { }, pls: &armnetwork.PrivateLinkService{ Properties: &armnetwork.PrivateLinkServiceProperties{ - EnableProxyProtocol: ptr.To(true), + EnableProxyProtocol: to.Ptr(true), }, }, - expectedEnabled: ptr.To(false), + expectedEnabled: to.Ptr(false), expectedChanged: true, }, } @@ -1409,9 +1409,9 @@ func TestReconcilePLSTags(t *testing.T) { } pls := armnetwork.PrivateLinkService{ Tags: map[string]*string{ - "foo": ptr.To("bar"), - "a": ptr.To("j"), - "m": ptr.To("n"), + "foo": to.Ptr("bar"), + "a": to.Ptr("j"), + "m": to.Ptr("n"), }, } clusterName := testClusterName @@ -1419,12 +1419,12 @@ func TestReconcilePLSTags(t *testing.T) { t.Run("reconcilePLSTags should ensure the pls is tagged as configured", func(t *testing.T) { expectedPLS := armnetwork.PrivateLinkService{ Tags: map[string]*string{ - consts.ClusterNameTagKey: ptr.To(testClusterName), - consts.OwnerServiceTagKey: ptr.To("test-ns/test-svc"), - "foo": ptr.To("bar"), - "a": ptr.To("x"), - "y": ptr.To("z"), - "m": ptr.To("n"), + consts.ClusterNameTagKey: to.Ptr(testClusterName), + consts.OwnerServiceTagKey: to.Ptr("test-ns/test-svc"), + "foo": to.Ptr("bar"), + "a": to.Ptr("x"), + "y": to.Ptr("z"), + "m": to.Ptr("n"), }, } changed := cloud.reconcilePLSTags(&pls, &clusterName, &service) @@ -1436,11 +1436,11 @@ func TestReconcilePLSTags(t *testing.T) { cloud.SystemTags = "a,foo,b" expectedPLS := armnetwork.PrivateLinkService{ Tags: map[string]*string{ - consts.ClusterNameTagKey: ptr.To(testClusterName), - consts.OwnerServiceTagKey: ptr.To("test-ns/test-svc"), - "foo": ptr.To("bar"), - "a": ptr.To("x"), - "y": ptr.To("z"), + consts.ClusterNameTagKey: to.Ptr(testClusterName), + consts.OwnerServiceTagKey: to.Ptr("test-ns/test-svc"), + "foo": to.Ptr("bar"), + "a": to.Ptr("x"), + "y": to.Ptr("z"), }, } changed := cloud.reconcilePLSTags(&pls, &clusterName, &service) @@ -1453,11 +1453,11 @@ func TestReconcilePLSTags(t *testing.T) { cloud.TagsMap = map[string]string{"a": "c", "a=b": "c=d", "Y": "zz"} expectedPLS := armnetwork.PrivateLinkService{ Tags: map[string]*string{ - consts.ClusterNameTagKey: ptr.To(testClusterName), - consts.OwnerServiceTagKey: ptr.To("test-ns/test-svc"), - "foo": ptr.To("bar"), - "a": ptr.To("c"), - "a=b": ptr.To("c=d"), + consts.ClusterNameTagKey: to.Ptr(testClusterName), + consts.OwnerServiceTagKey: to.Ptr("test-ns/test-svc"), + "foo": to.Ptr("bar"), + "a": to.Ptr("c"), + "a=b": to.Ptr("c=d"), }, } changed := cloud.reconcilePLSTags(&pls, &clusterName, &service) @@ -1465,18 +1465,18 @@ func TestReconcilePLSTags(t *testing.T) { assert.Equal(t, expectedPLS, pls) }) - pls.Tags[consts.ClusterNameTagKey] = ptr.To("testCluster1") - pls.Tags[consts.OwnerServiceTagKey] = ptr.To("default/svc") + pls.Tags[consts.ClusterNameTagKey] = to.Ptr("testCluster1") + pls.Tags[consts.OwnerServiceTagKey] = to.Ptr("default/svc") t.Run("reconcilePLSTags should respect cluster and owner service tag keys", func(t *testing.T) { expectedPLS := armnetwork.PrivateLinkService{ Tags: map[string]*string{ - consts.ClusterNameTagKey: ptr.To("testCluster1"), - consts.OwnerServiceTagKey: ptr.To("default/svc"), - "foo": ptr.To("bar"), - "a": ptr.To("c"), - "a=b": ptr.To("c=d"), - "Y": ptr.To("zz"), + consts.ClusterNameTagKey: to.Ptr("testCluster1"), + consts.OwnerServiceTagKey: to.Ptr("default/svc"), + "foo": to.Ptr("bar"), + "a": to.Ptr("c"), + "a=b": to.Ptr("c=d"), + "Y": to.Ptr("zz"), }, } changed := cloud.reconcilePLSTags(&pls, &clusterName, &service) @@ -1502,7 +1502,7 @@ func TestGetPLSSubnetName(t *testing.T) { annotations: map[string]string{ consts.ServiceAnnotationPLSIpConfigurationSubnet: "pls-subnet", }, - expectedSubnet: ptr.To("pls-subnet"), + expectedSubnet: to.Ptr("pls-subnet"), }, { desc: "Service with empty private link subnet specified but LB subnet specified should return LB subnet", @@ -1511,7 +1511,7 @@ func TestGetPLSSubnetName(t *testing.T) { consts.ServiceAnnotationPLSIpConfigurationSubnet: "", consts.ServiceAnnotationLoadBalancerInternalSubnet: "lb-subnet", }, - expectedSubnet: ptr.To("lb-subnet"), + expectedSubnet: to.Ptr("lb-subnet"), }, { desc: "Service with LB subnet specified should return it", @@ -1519,7 +1519,7 @@ func TestGetPLSSubnetName(t *testing.T) { consts.ServiceAnnotationLoadBalancerInternal: "true", consts.ServiceAnnotationLoadBalancerInternalSubnet: "lb-subnet", }, - expectedSubnet: ptr.To("lb-subnet"), + expectedSubnet: to.Ptr("lb-subnet"), }, { desc: "Service with both empty subnets specified should return nil", @@ -1857,7 +1857,7 @@ func TestIsManagedPrivateLinkSerivce(t *testing.T) { desc: "Private link service with different cluster name should return false", pls: &armnetwork.PrivateLinkService{ Tags: map[string]*string{ - "k8s-azure-cluster-name": ptr.To("test-cluster1"), + "k8s-azure-cluster-name": to.Ptr("test-cluster1"), }, }, clusterName: "test-cluster", @@ -1866,7 +1866,7 @@ func TestIsManagedPrivateLinkSerivce(t *testing.T) { desc: "Private link service with same cluster name should return true", pls: &armnetwork.PrivateLinkService{ Tags: map[string]*string{ - "k8s-azure-cluster-name": ptr.To("test-cluster"), + "k8s-azure-cluster-name": to.Ptr("test-cluster"), }, }, clusterName: "test-cluster", @@ -1898,7 +1898,7 @@ func TestGetPrivateLinkServiceOwner(t *testing.T) { { desc: "Private link service with service owner tag should return service owner", pls: &armnetwork.PrivateLinkService{ - Tags: map[string]*string{"k8s-azure-owner-service": ptr.To("test-service")}, + Tags: map[string]*string{"k8s-azure-owner-service": to.Ptr("test-service")}, }, expected: "test-service", }, diff --git a/pkg/provider/azure_publicip_repo.go b/pkg/provider/azure_publicip_repo.go index 8c9d4dfa03..8a89d3afe4 100644 --- a/pkg/provider/azure_publicip_repo.go +++ b/pkg/provider/azure_publicip_repo.go @@ -26,10 +26,9 @@ import ( "time" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - + "github.com/samber/lo" v1 "k8s.io/api/core/v1" "k8s.io/klog/v2" - "k8s.io/utils/ptr" azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" @@ -41,8 +40,8 @@ func (az *Cloud) CreateOrUpdatePIP(service *v1.Service, pipResourceGroup string, ctx, cancel := getContextWithCancel() defer cancel() - rerr := az.PublicIPAddressesClient.CreateOrUpdate(ctx, pipResourceGroup, ptr.Deref(pip.Name, ""), pip) - klog.V(10).Infof("PublicIPAddressesClient.CreateOrUpdate(%s, %s): end", pipResourceGroup, ptr.Deref(pip.Name, "")) + rerr := az.PublicIPAddressesClient.CreateOrUpdate(ctx, pipResourceGroup, lo.FromPtrOr(pip.Name, ""), pip) + klog.V(10).Infof("PublicIPAddressesClient.CreateOrUpdate(%s, %s): end", pipResourceGroup, lo.FromPtrOr(pip.Name, "")) if rerr == nil { // Invalidate the cache right after updating _ = az.pipCache.Delete(pipResourceGroup) @@ -50,19 +49,19 @@ func (az *Cloud) CreateOrUpdatePIP(service *v1.Service, pipResourceGroup string, } pipJSON, _ := json.Marshal(pip) - klog.Warningf("PublicIPAddressesClient.CreateOrUpdate(%s, %s) failed: %s, PublicIP request: %s", pipResourceGroup, ptr.Deref(pip.Name, ""), rerr.Error().Error(), string(pipJSON)) + klog.Warningf("PublicIPAddressesClient.CreateOrUpdate(%s, %s) failed: %s, PublicIP request: %s", pipResourceGroup, lo.FromPtrOr(pip.Name, ""), rerr.Error().Error(), string(pipJSON)) az.Event(service, v1.EventTypeWarning, "CreateOrUpdatePublicIPAddress", rerr.Error().Error()) // Invalidate the cache because ETAG precondition mismatch. if rerr.HTTPStatusCode == http.StatusPreconditionFailed { - klog.V(3).Infof("PublicIP cache for (%s, %s) is cleanup because of http.StatusPreconditionFailed", pipResourceGroup, ptr.Deref(pip.Name, "")) + klog.V(3).Infof("PublicIP cache for (%s, %s) is cleanup because of http.StatusPreconditionFailed", pipResourceGroup, lo.FromPtrOr(pip.Name, "")) _ = az.pipCache.Delete(pipResourceGroup) } retryErrorMessage := rerr.Error().Error() // Invalidate the cache because another new operation has canceled the current request. if strings.Contains(strings.ToLower(retryErrorMessage), consts.OperationCanceledErrorMessage) { - klog.V(3).Infof("PublicIP cache for (%s, %s) is cleanup because CreateOrUpdate is canceled by another operation", pipResourceGroup, ptr.Deref(pip.Name, "")) + klog.V(3).Infof("PublicIP cache for (%s, %s) is cleanup because CreateOrUpdate is canceled by another operation", pipResourceGroup, lo.FromPtrOr(pip.Name, "")) _ = az.pipCache.Delete(pipResourceGroup) } @@ -102,7 +101,7 @@ func (az *Cloud) newPIPCache() (azcache.Resource, error) { pipMap := &sync.Map{} for _, pip := range pipList { pip := pip - pipMap.Store(strings.ToLower(ptr.Deref(pip.Name, "")), &pip) + pipMap.Store(strings.ToLower(lo.FromPtrOr(pip.Name, "")), &pip) } return pipMap, nil } @@ -178,7 +177,7 @@ func (az *Cloud) findMatchedPIP(ctx context.Context, loadBalancerIP, pipName, pi func (az *Cloud) findMatchedPIPByName(ctx context.Context, pips *[]network.PublicIPAddress, pipName, pipResourceGroup string) (*network.PublicIPAddress, error) { for _, pip := range *pips { - if strings.EqualFold(ptr.Deref(pip.Name, ""), pipName) { + if strings.EqualFold(lo.FromPtrOr(pip.Name, ""), pipName) { return &pip, nil } } @@ -188,7 +187,7 @@ func (az *Cloud) findMatchedPIPByName(ctx context.Context, pips *[]network.Publi return nil, fmt.Errorf("findMatchedPIPByName: failed to listPIP force refresh: %w", err) } for _, pip := range pipList { - if strings.EqualFold(ptr.Deref(pip.Name, ""), pipName) { + if strings.EqualFold(lo.FromPtrOr(pip.Name, ""), pipName) { return &pip, nil } } diff --git a/pkg/provider/azure_publicip_repo_test.go b/pkg/provider/azure_publicip_repo_test.go index 58cdb3eedd..6ccfd4b183 100644 --- a/pkg/provider/azure_publicip_repo_test.go +++ b/pkg/provider/azure_publicip_repo_test.go @@ -24,13 +24,12 @@ import ( "sync" "testing" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" + "github.com/samber/lo" "github.com/stretchr/testify/assert" - "go.uber.org/mock/gomock" - v1 "k8s.io/api/core/v1" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/publicipclient/mockpublicipclient" "sigs.k8s.io/cloud-provider-azure/pkg/cache" @@ -67,14 +66,14 @@ func TestCreateOrUpdatePIP(t *testing.T) { for _, test := range tests { az := GetTestCloud(ctrl) - az.pipCache.Set(az.ResourceGroup, []network.PublicIPAddress{{Name: ptr.To("test")}}) + az.pipCache.Set(az.ResourceGroup, []network.PublicIPAddress{{Name: to.Ptr("test")}}) mockPIPClient := az.PublicIPAddressesClient.(*mockpublicipclient.MockInterface) mockPIPClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, "nic", gomock.Any()).Return(test.clientErr) if test.cacheExpectedEmpty { mockPIPClient.EXPECT().List(gomock.Any(), az.ResourceGroup).Return([]network.PublicIPAddress{}, nil) } - err := az.CreateOrUpdatePIP(&v1.Service{}, az.ResourceGroup, network.PublicIPAddress{Name: ptr.To("nic")}) + err := az.CreateOrUpdatePIP(&v1.Service{}, az.ResourceGroup, network.PublicIPAddress{Name: to.Ptr("nic")}) assert.EqualError(t, test.expectedErr, err.Error()) cachedPIP, err := az.pipCache.GetWithDeepCopy(context.TODO(), az.ResourceGroup, cache.CacheReadTypeDefault) @@ -116,14 +115,14 @@ func TestListPIP(t *testing.T) { { desc: "listPIP should return data from cache", pipCache: []network.PublicIPAddress{ - {Name: ptr.To("pip1")}, - {Name: ptr.To("pip2")}, + {Name: to.Ptr("pip1")}, + {Name: to.Ptr("pip2")}, }, }, { desc: "listPIP should return data from arm list call", expectPIPList: true, - existingPIPs: []network.PublicIPAddress{{Name: ptr.To("pip")}}, + existingPIPs: []network.PublicIPAddress{{Name: to.Ptr("pip")}}, }, } for _, test := range tests { @@ -133,7 +132,7 @@ func TestListPIP(t *testing.T) { pipCache := &sync.Map{} for _, pip := range test.pipCache { pip := pip - pipCache.Store(ptr.Deref(pip.Name, ""), &pip) + pipCache.Store(lo.FromPtrOr(pip.Name, ""), &pip) } az.pipCache.Set(az.ResourceGroup, pipCache) } @@ -166,25 +165,25 @@ func TestGetPublicIPAddress(t *testing.T) { }{ { desc: "getPublicIPAddress should return pip from cache when it exists", - pipCache: []network.PublicIPAddress{{Name: ptr.To("pip")}}, + pipCache: []network.PublicIPAddress{{Name: to.Ptr("pip")}}, expectExists: true, - expectedPIP: network.PublicIPAddress{Name: ptr.To("pip")}, + expectedPIP: network.PublicIPAddress{Name: to.Ptr("pip")}, }, { desc: "getPublicIPAddress should from list call when cache is empty", expectPIPList: true, existingPIPs: []network.PublicIPAddress{ - {Name: ptr.To("pip")}, - {Name: ptr.To("pip1")}, + {Name: to.Ptr("pip")}, + {Name: to.Ptr("pip1")}, }, expectExists: true, - expectedPIP: network.PublicIPAddress{Name: ptr.To("pip")}, + expectedPIP: network.PublicIPAddress{Name: to.Ptr("pip")}, }, { desc: "getPublicIPAddress should try listing when pip does not exist", - pipCache: []network.PublicIPAddress{{Name: ptr.To("pip1")}}, + pipCache: []network.PublicIPAddress{{Name: to.Ptr("pip1")}}, expectPIPList: true, - existingPIPs: []network.PublicIPAddress{{Name: ptr.To("pip1")}}, + existingPIPs: []network.PublicIPAddress{{Name: to.Ptr("pip1")}}, expectExists: false, expectedPIP: network.PublicIPAddress{}, }, @@ -194,7 +193,7 @@ func TestGetPublicIPAddress(t *testing.T) { pipCache := &sync.Map{} for _, pip := range test.pipCache { pip := pip - pipCache.Store(ptr.Deref(pip.Name, ""), &pip) + pipCache.Store(lo.FromPtrOr(pip.Name, ""), &pip) } az := GetTestCloud(ctrl) az.pipCache.Set(az.ResourceGroup, pipCache) @@ -215,9 +214,9 @@ func TestFindMatchedPIP(t *testing.T) { defer ctrl.Finish() testPIP := network.PublicIPAddress{ - Name: ptr.To("pipName"), + Name: to.Ptr("pipName"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, } @@ -291,9 +290,9 @@ func TestFindMatchedPIPByLoadBalancerIP(t *testing.T) { defer ctrl.Finish() testPIP := network.PublicIPAddress{ - Name: ptr.To("pipName"), + Name: to.Ptr("pipName"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("1.2.3.4"), + IPAddress: to.Ptr("1.2.3.4"), }, } testCases := []struct { diff --git a/pkg/provider/azure_routes.go b/pkg/provider/azure_routes.go index 4527908ef8..a852bf6dd6 100644 --- a/pkg/provider/azure_routes.go +++ b/pkg/provider/azure_routes.go @@ -23,13 +23,14 @@ import ( "sync" "time" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" + "github.com/samber/lo" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/wait" cloudprovider "k8s.io/cloud-provider" "k8s.io/klog/v2" utilnet "k8s.io/utils/net" - "k8s.io/utils/ptr" azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" @@ -164,13 +165,13 @@ func (d *delayedRouteUpdater) updateRoutes(ctx context.Context) { routeMatch := false onlyUpdateTags = false for i, existingRoute := range routes { - if strings.EqualFold(ptr.Deref(existingRoute.Name, ""), ptr.Deref(rt.route.Name, "")) { + if strings.EqualFold(lo.FromPtrOr(existingRoute.Name, ""), lo.FromPtrOr(rt.route.Name, "")) { // delete the name-matched routes here (missing routes would be added later if the operation is add). routes = append(routes[:i], routes[i+1:]...) if existingRoute.Properties != nil && rt.route.Properties != nil && - strings.EqualFold(ptr.Deref(existingRoute.Properties.AddressPrefix, ""), ptr.Deref(rt.route.Properties.AddressPrefix, "")) && - strings.EqualFold(ptr.Deref(existingRoute.Properties.NextHopIPAddress, ""), ptr.Deref(rt.route.Properties.NextHopIPAddress, "")) { + strings.EqualFold(lo.FromPtrOr(existingRoute.Properties.AddressPrefix, ""), lo.FromPtrOr(rt.route.Properties.AddressPrefix, "")) && + strings.EqualFold(lo.FromPtrOr(existingRoute.Properties.NextHopIPAddress, ""), lo.FromPtrOr(rt.route.Properties.NextHopIPAddress, "")) { routeMatch = true } if rt.operation == routeOperationDelete { @@ -180,7 +181,7 @@ func (d *delayedRouteUpdater) updateRoutes(ctx context.Context) { } } if rt.operation == routeOperationDelete && !dirty { - klog.Warningf("updateRoutes: route to be deleted %s does not match any of the existing route", ptr.Deref(rt.route.Name, "")) + klog.Warningf("updateRoutes: route to be deleted %s does not match any of the existing route", lo.FromPtrOr(rt.route.Name, "")) } // Add missing routes if the operation is add. @@ -213,7 +214,7 @@ func (d *delayedRouteUpdater) updateRoutes(ctx context.Context) { // and deletes all dualstack routes when dualstack is not enabled. func (d *delayedRouteUpdater) cleanupOutdatedRoutes(existingRoutes []*armnetwork.Route) (routes []*armnetwork.Route, changed bool) { for i := len(existingRoutes) - 1; i >= 0; i-- { - existingRouteName := ptr.Deref(existingRoutes[i].Name, "") + existingRouteName := lo.FromPtrOr(existingRoutes[i].Name, "") split := strings.Split(existingRouteName, consts.RouteNameSeparator) klog.V(4).Infof("cleanupOutdatedRoutes: checking route %s", existingRouteName) @@ -304,7 +305,7 @@ func (az *Cloud) ListRoutes(ctx context.Context, clusterName string) ([]*cloudpr // ensure the route table is tagged as configured tags, changed := az.ensureRouteTableTagged(routeTable) if changed { - klog.V(2).Infof("ListRoutes: updating tags on route table %s", ptr.Deref(routeTable.Name, "")) + klog.V(2).Infof("ListRoutes: updating tags on route table %s", lo.FromPtrOr(routeTable.Name, "")) op := az.routeUpdater.addOperation(getUpdateRouteTableTagsOperation(tags)) // Wait for operation complete. @@ -349,8 +350,8 @@ func processRoutes(ipv6DualStackEnabled bool, routeTable *armnetwork.RouteTable, func (az *Cloud) createRouteTable(ctx context.Context) error { routeTable := armnetwork.RouteTable{ - Name: ptr.To(az.RouteTableName), - Location: ptr.To(az.Location), + Name: to.Ptr(az.RouteTableName), + Location: to.Ptr(az.Location), Properties: &armnetwork.RouteTablePropertiesFormat{}, } @@ -412,11 +413,11 @@ func (az *Cloud) CreateRoute(ctx context.Context, clusterName string, _ string, } routeName := mapNodeNameToRouteName(az.ipv6DualStackEnabled, kubeRoute.TargetNode, kubeRoute.DestinationCIDR) route := &armnetwork.Route{ - Name: ptr.To(routeName), + Name: to.Ptr(routeName), Properties: &armnetwork.RoutePropertiesFormat{ - AddressPrefix: ptr.To(kubeRoute.DestinationCIDR), - NextHopType: ptr.To(armnetwork.RouteNextHopTypeVirtualAppliance), - NextHopIPAddress: ptr.To(targetIP), + AddressPrefix: to.Ptr(kubeRoute.DestinationCIDR), + NextHopType: to.Ptr(armnetwork.RouteNextHopTypeVirtualAppliance), + NextHopIPAddress: to.Ptr(targetIP), }, } @@ -463,7 +464,7 @@ func (az *Cloud) DeleteRoute(_ context.Context, clusterName string, kubeRoute *c routeName := mapNodeNameToRouteName(az.ipv6DualStackEnabled, kubeRoute.TargetNode, kubeRoute.DestinationCIDR) klog.V(2).Infof("DeleteRoute: deleting route. clusterName=%q instance=%q cidr=%q routeName=%q", clusterName, kubeRoute.TargetNode, kubeRoute.DestinationCIDR, routeName) route := &armnetwork.Route{ - Name: ptr.To(routeName), + Name: to.Ptr(routeName), Properties: &armnetwork.RoutePropertiesFormat{}, } op := az.routeUpdater.addOperation(getDeleteRouteOperation(route)) @@ -480,7 +481,7 @@ func (az *Cloud) DeleteRoute(_ context.Context, clusterName string, kubeRoute *c routeNameWithoutIPV6Suffix := strings.Split(routeName, consts.RouteNameSeparator)[0] klog.V(2).Infof("DeleteRoute: deleting route. clusterName=%q instance=%q cidr=%q routeName=%q", clusterName, kubeRoute.TargetNode, kubeRoute.DestinationCIDR, routeNameWithoutIPV6Suffix) route := &armnetwork.Route{ - Name: ptr.To(routeNameWithoutIPV6Suffix), + Name: to.Ptr(routeNameWithoutIPV6Suffix), Properties: &armnetwork.RoutePropertiesFormat{}, } op := az.routeUpdater.addOperation(getDeleteRouteOperation(route)) diff --git a/pkg/provider/azure_routes_test.go b/pkg/provider/azure_routes_test.go index 4704fa736f..ef4d8592b4 100644 --- a/pkg/provider/azure_routes_test.go +++ b/pkg/provider/azure_routes_test.go @@ -24,13 +24,12 @@ import ( "testing" "time" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" "github.com/stretchr/testify/assert" "go.uber.org/mock/gomock" - "k8s.io/apimachinery/pkg/types" cloudprovider "k8s.io/cloud-provider" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/provider/config" "sigs.k8s.io/cloud-provider-azure/pkg/provider/routetable" @@ -203,11 +202,11 @@ func TestCreateRoute(t *testing.T) { defaultNetworkRoute := func() []*armnetwork.Route { return []*armnetwork.Route{ { - Name: ptr.To("node"), + Name: to.Ptr("node"), Properties: &armnetwork.RoutePropertiesFormat{ - AddressPrefix: ptr.To("1.2.3.4/24"), + AddressPrefix: to.Ptr("1.2.3.4/24"), NextHopIPAddress: &nodePrivateIP, - NextHopType: ptr.To(armnetwork.RouteNextHopTypeVirtualAppliance), + NextHopType: to.Ptr(armnetwork.RouteNextHopTypeVirtualAppliance), }, }, } @@ -290,11 +289,11 @@ func TestCreateRoute(t *testing.T) { routeTableName: "rt9", updatedRoute: []*armnetwork.Route{ { - Name: ptr.To("node____123424"), + Name: to.Ptr("node____123424"), Properties: &armnetwork.RoutePropertiesFormat{ - AddressPrefix: ptr.To("1.2.3.4/24"), + AddressPrefix: to.Ptr("1.2.3.4/24"), NextHopIPAddress: &nodePrivateIP, - NextHopType: ptr.To(armnetwork.RouteNextHopTypeVirtualAppliance), + NextHopType: to.Ptr(armnetwork.RouteNextHopTypeVirtualAppliance), }, }, }, @@ -331,14 +330,14 @@ func TestCreateRoute(t *testing.T) { go cloud.routeUpdater.run(context.Background()) initialTable := &armnetwork.RouteTable{ - Name: ptr.To(tt.routeTableName), + Name: to.Ptr(tt.routeTableName), Location: &cloud.Location, Properties: &armnetwork.RouteTablePropertiesFormat{ Routes: tt.initialRoute, }, } updatedTable := armnetwork.RouteTable{ - Name: ptr.To(tt.routeTableName), + Name: to.Ptr(tt.routeTableName), Location: &cloud.Location, Properties: &armnetwork.RouteTablePropertiesFormat{ Routes: tt.updatedRoute, @@ -450,9 +449,9 @@ func TestProcessRoutes(t *testing.T) { Properties: &armnetwork.RouteTablePropertiesFormat{ Routes: []*armnetwork.Route{ { - Name: ptr.To("name"), + Name: to.Ptr("name"), Properties: &armnetwork.RoutePropertiesFormat{ - AddressPrefix: ptr.To("1.2.3.4/16"), + AddressPrefix: to.Ptr("1.2.3.4/16"), }, }, }, @@ -472,15 +471,15 @@ func TestProcessRoutes(t *testing.T) { Properties: &armnetwork.RouteTablePropertiesFormat{ Routes: []*armnetwork.Route{ { - Name: ptr.To("name"), + Name: to.Ptr("name"), Properties: &armnetwork.RoutePropertiesFormat{ - AddressPrefix: ptr.To("1.2.3.4/16"), + AddressPrefix: to.Ptr("1.2.3.4/16"), }, }, { - Name: ptr.To("name2"), + Name: to.Ptr("name2"), Properties: &armnetwork.RoutePropertiesFormat{ - AddressPrefix: ptr.To("5.6.7.8/16"), + AddressPrefix: to.Ptr("5.6.7.8/16"), }, }, }, @@ -628,14 +627,14 @@ func TestListRoutes(t *testing.T) { name: "ListRoutes should return correct routes", routeTableName: "rt1", routeTable: &armnetwork.RouteTable{ - Name: ptr.To("rt1"), + Name: to.Ptr("rt1"), Location: &cloud.Location, Properties: &armnetwork.RouteTablePropertiesFormat{ Routes: []*armnetwork.Route{ { - Name: ptr.To("node"), + Name: to.Ptr("node"), Properties: &armnetwork.RoutePropertiesFormat{ - AddressPrefix: ptr.To("1.2.3.4/24"), + AddressPrefix: to.Ptr("1.2.3.4/24"), }, }, }, @@ -656,14 +655,14 @@ func TestListRoutes(t *testing.T) { unmanagedNodeName: "unmanaged-node", routeCIDRs: map[string]string{"unmanaged-node": "2.2.3.4/24"}, routeTable: &armnetwork.RouteTable{ - Name: ptr.To("rt2"), + Name: to.Ptr("rt2"), Location: &cloud.Location, Properties: &armnetwork.RouteTablePropertiesFormat{ Routes: []*armnetwork.Route{ { - Name: ptr.To("node"), + Name: to.Ptr("node"), Properties: &armnetwork.RoutePropertiesFormat{ - AddressPrefix: ptr.To("1.2.3.4/24"), + AddressPrefix: to.Ptr("1.2.3.4/24"), }, }, }, @@ -749,11 +748,11 @@ func TestCleanupOutdatedRoutes(t *testing.T) { { description: "cleanupOutdatedRoutes should delete outdated non-dualstack routes when dualstack is enabled", existingRoutes: []*armnetwork.Route{ - {Name: ptr.To("aks-node1-vmss000000____xxx")}, - {Name: ptr.To("aks-node1-vmss000000")}, + {Name: to.Ptr("aks-node1-vmss000000____xxx")}, + {Name: to.Ptr("aks-node1-vmss000000")}, }, expectedRoutes: []*armnetwork.Route{ - {Name: ptr.To("aks-node1-vmss000000____xxx")}, + {Name: to.Ptr("aks-node1-vmss000000____xxx")}, }, existingNodeNames: utilsets.NewString("aks-node1-vmss000000"), enableIPV6DualStack: true, @@ -762,11 +761,11 @@ func TestCleanupOutdatedRoutes(t *testing.T) { { description: "cleanupOutdatedRoutes should delete outdated dualstack routes when dualstack is disabled", existingRoutes: []*armnetwork.Route{ - {Name: ptr.To("aks-node1-vmss000000____xxx")}, - {Name: ptr.To("aks-node1-vmss000000")}, + {Name: to.Ptr("aks-node1-vmss000000____xxx")}, + {Name: to.Ptr("aks-node1-vmss000000")}, }, expectedRoutes: []*armnetwork.Route{ - {Name: ptr.To("aks-node1-vmss000000")}, + {Name: to.Ptr("aks-node1-vmss000000")}, }, existingNodeNames: utilsets.NewString("aks-node1-vmss000000"), expectedChanged: true, @@ -774,12 +773,12 @@ func TestCleanupOutdatedRoutes(t *testing.T) { { description: "cleanupOutdatedRoutes should not delete unmanaged routes when dualstack is enabled", existingRoutes: []*armnetwork.Route{ - {Name: ptr.To("aks-node1-vmss000000____xxx")}, - {Name: ptr.To("aks-node1-vmss000000")}, + {Name: to.Ptr("aks-node1-vmss000000____xxx")}, + {Name: to.Ptr("aks-node1-vmss000000")}, }, expectedRoutes: []*armnetwork.Route{ - {Name: ptr.To("aks-node1-vmss000000____xxx")}, - {Name: ptr.To("aks-node1-vmss000000")}, + {Name: to.Ptr("aks-node1-vmss000000____xxx")}, + {Name: to.Ptr("aks-node1-vmss000000")}, }, existingNodeNames: utilsets.NewString("aks-node1-vmss000001"), enableIPV6DualStack: true, @@ -787,12 +786,12 @@ func TestCleanupOutdatedRoutes(t *testing.T) { { description: "cleanupOutdatedRoutes should not delete unmanaged routes when dualstack is disabled", existingRoutes: []*armnetwork.Route{ - {Name: ptr.To("aks-node1-vmss000000____xxx")}, - {Name: ptr.To("aks-node1-vmss000000")}, + {Name: to.Ptr("aks-node1-vmss000000____xxx")}, + {Name: to.Ptr("aks-node1-vmss000000")}, }, expectedRoutes: []*armnetwork.Route{ - {Name: ptr.To("aks-node1-vmss000000____xxx")}, - {Name: ptr.To("aks-node1-vmss000000")}, + {Name: to.Ptr("aks-node1-vmss000000____xxx")}, + {Name: to.Ptr("aks-node1-vmss000000")}, }, existingNodeNames: utilsets.NewString("aks-node1-vmss000001"), }, @@ -822,8 +821,8 @@ func TestEnsureRouteTableTagged(t *testing.T) { cloud.Tags = "a=b,c=d" expectedTags := map[string]*string{ - "a": ptr.To("b"), - "c": ptr.To("d"), + "a": to.Ptr("b"), + "c": to.Ptr("d"), } rt := &armnetwork.RouteTable{} tags, changed := cloud.ensureRouteTableTagged(rt) diff --git a/pkg/provider/azure_standard.go b/pkg/provider/azure_standard.go index 79b13824c9..cea7d48ead 100644 --- a/pkg/provider/azure_standard.go +++ b/pkg/provider/azure_standard.go @@ -28,16 +28,17 @@ import ( "sync/atomic" "time" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" + "github.com/samber/lo" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/types" utilerrors "k8s.io/apimachinery/pkg/util/errors" "k8s.io/apimachinery/pkg/util/uuid" cloudprovider "k8s.io/cloud-provider" "k8s.io/klog/v2" - "k8s.io/utils/ptr" azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" @@ -198,7 +199,7 @@ func getPrimaryInterfaceID(machine compute.VirtualMachine) (string, error) { } for _, ref := range *machine.NetworkProfile.NetworkInterfaces { - if ptr.Deref(ref.Primary, false) { + if lo.FromPtrOr(ref.Primary, false) { return *ref.ID, nil } } @@ -243,7 +244,7 @@ func getIPConfigByIPFamily(nic network.Interface, IPv6 bool) (*network.Interface return &ref, nil } } - return nil, fmt.Errorf("failed to determine the ipconfig(IPv6=%v). nicname=%q", IPv6, ptr.Deref(nic.Name, "")) + return nil, fmt.Errorf("failed to determine the ipconfig(IPv6=%v). nicname=%q", IPv6, lo.FromPtrOr(nic.Name, "")) } // getBackendPoolName the LB BackendPool name for a service. @@ -356,7 +357,7 @@ func publicIPOwnsFrontendIP(service *v1.Service, fip *network.FrontendIPConfigur fip != nil && fip.FrontendIPConfigurationPropertiesFormat != nil && fip.FrontendIPConfigurationPropertiesFormat.PublicIPAddress != nil { - if strings.EqualFold(ptr.Deref(pip.ID, ""), ptr.Deref(fip.PublicIPAddress.ID, "")) { + if strings.EqualFold(lo.FromPtrOr(pip.ID, ""), lo.FromPtrOr(fip.PublicIPAddress.ID, "")) { klog.V(6).Infof("publicIPOwnsFrontendIP:found secondary service %s of the frontend IP config %s", service.Name, *fip.Name) return true } @@ -424,11 +425,11 @@ func (as *availabilitySet) newVMASCache() (azcache.Resource, error) { for i := range allAvailabilitySets { vmas := allAvailabilitySets[i] - if strings.EqualFold(ptr.Deref(vmas.Name, ""), "") { + if strings.EqualFold(lo.FromPtrOr(vmas.Name, ""), "") { klog.Warning("failed to get the name of the VMAS") continue } - localCache.Store(ptr.Deref(vmas.Name, ""), &AvailabilitySetEntry{ + localCache.Store(lo.FromPtrOr(vmas.Name, ""), &AvailabilitySetEntry{ VMAS: &vmas, ResourceGroup: resourceGroup, }) @@ -511,7 +512,7 @@ func (as *availabilitySet) GetPowerStatusByNodeName(ctx context.Context, name st } if vm.InstanceView != nil { - return vmutil.GetVMPowerState(ptr.Deref(vm.Name, ""), vm.InstanceView.Statuses), nil + return vmutil.GetVMPowerState(lo.FromPtrOr(vm.Name, ""), vm.InstanceView.Statuses), nil } // vm.InstanceView or vm.InstanceView.Statuses are nil when the VM is under deleting. @@ -530,7 +531,7 @@ func (as *availabilitySet) GetProvisioningStateByNodeName(ctx context.Context, n return provisioningState, nil } - return ptr.Deref(vm.VirtualMachineProperties.ProvisioningState, ""), nil + return lo.FromPtrOr(vm.VirtualMachineProperties.ProvisioningState, ""), nil } // GetNodeNameByProviderID gets the node name by provider ID. @@ -576,15 +577,15 @@ func (as *availabilitySet) GetZoneByNodeName(ctx context.Context, name string) ( return cloudprovider.Zone{}, fmt.Errorf("failed to parse zone %q: %w", zones, err) } - failureDomain = as.makeZone(ptr.Deref(vm.Location, ""), zoneID) + failureDomain = as.makeZone(lo.FromPtrOr(vm.Location, ""), zoneID) } else { // Availability zone is not used for the node, falling back to fault domain. - failureDomain = strconv.Itoa(int(ptr.Deref(vm.VirtualMachineProperties.InstanceView.PlatformFaultDomain, 0))) + failureDomain = strconv.Itoa(int(lo.FromPtrOr(vm.VirtualMachineProperties.InstanceView.PlatformFaultDomain, 0))) } zone := cloudprovider.Zone{ FailureDomain: strings.ToLower(failureDomain), - Region: strings.ToLower(ptr.Deref(vm.Location, "")), + Region: strings.ToLower(lo.FromPtrOr(vm.Location, "")), } return zone, nil } @@ -758,13 +759,13 @@ func (as *availabilitySet) GetNodeVMSetName(ctx context.Context, node *v1.Node) var asName string for _, vm := range vms { - if strings.EqualFold(ptr.Deref(vm.Name, ""), hostName) { - if vm.AvailabilitySet != nil && ptr.Deref(vm.AvailabilitySet.ID, "") != "" { + if strings.EqualFold(lo.FromPtrOr(vm.Name, ""), hostName) { + if vm.AvailabilitySet != nil && lo.FromPtrOr(vm.AvailabilitySet.ID, "") != "" { klog.V(4).Infof("as.GetNodeVMSetName: found vm %s", hostName) - asName, err = getLastSegment(ptr.Deref(vm.AvailabilitySet.ID, ""), "/") + asName, err = getLastSegment(lo.FromPtrOr(vm.AvailabilitySet.ID, ""), "/") if err != nil { - klog.Errorf("as.GetNodeVMSetName: failed to get last segment of ID %s: %s", ptr.Deref(vm.AvailabilitySet.ID, ""), err) + klog.Errorf("as.GetNodeVMSetName: failed to get last segment of ID %s: %s", lo.FromPtrOr(vm.AvailabilitySet.ID, ""), err) return "", err } } @@ -852,7 +853,7 @@ func (as *availabilitySet) getPrimaryInterfaceWithVMSet(ctx context.Context, nod var availabilitySetID string if machine.VirtualMachineProperties != nil && machine.AvailabilitySet != nil { - availabilitySetID = ptr.Deref(machine.AvailabilitySet.ID, "") + availabilitySetID = lo.FromPtrOr(machine.AvailabilitySet.ID, "") } return nic, availabilitySetID, nil } @@ -927,7 +928,7 @@ func (as *availabilitySet) EnsureHostInPool(ctx context.Context, service *v1.Ser newBackendPools = append(newBackendPools, network.BackendAddressPool{ - ID: ptr.To(backendPoolID), + ID: to.Ptr(backendPoolID), }) primaryIPConfig.LoadBalancerBackendAddressPools = &newBackendPools @@ -1005,7 +1006,7 @@ func (as *availabilitySet) EnsureBackendPoolDeleted(ctx context.Context, service ipConfigurationIDs := []string{} for _, backendPool := range *backendAddressPools { for _, backendPoolID := range backendPoolIDs { - if strings.EqualFold(ptr.Deref(backendPool.ID, ""), backendPoolID) { + if strings.EqualFold(lo.FromPtrOr(backendPool.ID, ""), backendPoolID) { if backendPool.BackendAddressPoolPropertiesFormat != nil && backendPool.BackendIPConfigurations != nil { for _, ipConf := range *backendPool.BackendIPConfigurations { @@ -1077,7 +1078,7 @@ func (as *availabilitySet) EnsureBackendPoolDeleted(ctx context.Context, service nic := ipconfigPrefixToNicMap[k] newIPConfigs := *nic.IPConfigurations for j, ipConf := range newIPConfigs { - if isServiceIPv4 && !ptr.Deref(ipConf.Primary, false) { + if isServiceIPv4 && !lo.FromPtrOr(ipConf.Primary, false) { continue } // To support IPv6 only and dual-stack clusters, all IP configurations @@ -1088,7 +1089,7 @@ func (as *availabilitySet) EnsureBackendPoolDeleted(ctx context.Context, service for k := len(newLBAddressPools) - 1; k >= 0; k-- { pool := newLBAddressPools[k] for _, backendPoolID := range backendPoolIDs { - if strings.EqualFold(ptr.Deref(pool.ID, ""), backendPoolID) { + if strings.EqualFold(lo.FromPtrOr(pool.ID, ""), backendPoolID) { newLBAddressPools = append(newLBAddressPools[:k], newLBAddressPools[k+1:]...) break } @@ -1099,10 +1100,10 @@ func (as *availabilitySet) EnsureBackendPoolDeleted(ctx context.Context, service } nic.IPConfigurations = &newIPConfigs nicUpdaters = append(nicUpdaters, func() error { - klog.V(2).Infof("EnsureBackendPoolDeleted begins to CreateOrUpdate for NIC(%s, %s) with backendPoolIDs %q", as.ResourceGroup, ptr.Deref(nic.Name, ""), backendPoolIDs) - rerr := as.InterfacesClient.CreateOrUpdate(ctx, as.ResourceGroup, ptr.Deref(nic.Name, ""), nic) + klog.V(2).Infof("EnsureBackendPoolDeleted begins to CreateOrUpdate for NIC(%s, %s) with backendPoolIDs %q", as.ResourceGroup, lo.FromPtrOr(nic.Name, ""), backendPoolIDs) + rerr := as.InterfacesClient.CreateOrUpdate(ctx, as.ResourceGroup, lo.FromPtrOr(nic.Name, ""), nic) if rerr != nil { - klog.Errorf("EnsureBackendPoolDeleted CreateOrUpdate for NIC(%s, %s) failed with error %v", as.ResourceGroup, ptr.Deref(nic.Name, ""), rerr.Error()) + klog.Errorf("EnsureBackendPoolDeleted CreateOrUpdate for NIC(%s, %s) failed with error %v", as.ResourceGroup, lo.FromPtrOr(nic.Name, ""), rerr.Error()) return rerr.Error() } nicUpdated.Store(true) @@ -1164,7 +1165,7 @@ func (as *availabilitySet) GetNodeNameByIPConfigurationID(ctx context.Context, i } vmID := "" if nic.InterfacePropertiesFormat != nil && nic.VirtualMachine != nil { - vmID = ptr.Deref(nic.VirtualMachine.ID, "") + vmID = lo.FromPtrOr(nic.VirtualMachine.ID, "") } if vmID == "" { klog.V(2).Infof("GetNodeNameByIPConfigurationID(%s): empty vmID", ipConfigurationID) @@ -1184,7 +1185,7 @@ func (as *availabilitySet) GetNodeNameByIPConfigurationID(ctx context.Context, i } asID := "" if vm.VirtualMachineProperties != nil && vm.AvailabilitySet != nil { - asID = ptr.Deref(vm.AvailabilitySet.ID, "") + asID = lo.FromPtrOr(vm.AvailabilitySet.ID, "") } if asID == "" { return vmName, "", nil @@ -1216,9 +1217,9 @@ func (as *availabilitySet) getAvailabilitySetByNodeName(ctx context.Context, nod if vmas != nil && vmas.AvailabilitySetProperties != nil && vmas.VirtualMachines != nil { for _, vmIDRef := range *vmas.VirtualMachines { if vmIDRef.ID != nil { - matches := vmIDRE.FindStringSubmatch(ptr.Deref(vmIDRef.ID, "")) + matches := vmIDRE.FindStringSubmatch(lo.FromPtrOr(vmIDRef.ID, "")) if len(matches) != 2 { - err = fmt.Errorf("invalid vm ID %s", ptr.Deref(vmIDRef.ID, "")) + err = fmt.Errorf("invalid vm ID %s", lo.FromPtrOr(vmIDRef.ID, "")) return false } @@ -1263,15 +1264,15 @@ func (as *availabilitySet) GetNodeCIDRMasksByProviderID(ctx context.Context, pro var ipv4Mask, ipv6Mask int if v4, ok := vmas.Tags[consts.VMSetCIDRIPV4TagKey]; ok && v4 != nil { - ipv4Mask, err = strconv.Atoi(ptr.Deref(v4, "")) + ipv4Mask, err = strconv.Atoi(lo.FromPtrOr(v4, "")) if err != nil { - klog.Errorf("GetNodeCIDRMasksByProviderID: error when paring the value of the ipv4 mask size %s: %v", ptr.Deref(v4, ""), err) + klog.Errorf("GetNodeCIDRMasksByProviderID: error when paring the value of the ipv4 mask size %s: %v", lo.FromPtrOr(v4, ""), err) } } if v6, ok := vmas.Tags[consts.VMSetCIDRIPV6TagKey]; ok && v6 != nil { - ipv6Mask, err = strconv.Atoi(ptr.Deref(v6, "")) + ipv6Mask, err = strconv.Atoi(lo.FromPtrOr(v6, "")) if err != nil { - klog.Errorf("GetNodeCIDRMasksByProviderID: error when paring the value of the ipv6 mask size%s: %v", ptr.Deref(v6, ""), err) + klog.Errorf("GetNodeCIDRMasksByProviderID: error when paring the value of the ipv6 mask size%s: %v", lo.FromPtrOr(v6, ""), err) } } diff --git a/pkg/provider/azure_standard_test.go b/pkg/provider/azure_standard_test.go index 06eb62586a..16f3abe0d4 100644 --- a/pkg/provider/azure_standard_test.go +++ b/pkg/provider/azure_standard_test.go @@ -24,6 +24,7 @@ import ( "strconv" "testing" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" @@ -33,7 +34,6 @@ import ( meta "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" cloudprovider "k8s.io/cloud-provider" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/interfaceclient/mockinterfaceclient" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmasclient/mockvmasclient" @@ -643,21 +643,21 @@ func TestGetStandardVMPrimaryInterfaceID(t *testing.T) { { name: "GetPrimaryInterfaceID should get primary NIC ID", vm: compute.VirtualMachine{ - Name: ptr.To("vm2"), + Name: to.Ptr("vm2"), VirtualMachineProperties: &compute.VirtualMachineProperties{ NetworkProfile: &compute.NetworkProfile{ NetworkInterfaces: &[]compute.NetworkInterfaceReference{ { NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{ - Primary: ptr.To(true), + Primary: to.Ptr(true), }, - ID: ptr.To("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic1"), + ID: to.Ptr("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic1"), }, { NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{ - Primary: ptr.To(false), + Primary: to.Ptr(false), }, - ID: ptr.To("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic2"), + ID: to.Ptr("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic2"), }, }, }, @@ -668,21 +668,21 @@ func TestGetStandardVMPrimaryInterfaceID(t *testing.T) { { name: "GetPrimaryInterfaceID should report error if node don't have primary NIC", vm: compute.VirtualMachine{ - Name: ptr.To("vm3"), + Name: to.Ptr("vm3"), VirtualMachineProperties: &compute.VirtualMachineProperties{ NetworkProfile: &compute.NetworkProfile{ NetworkInterfaces: &[]compute.NetworkInterfaceReference{ { NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{ - Primary: ptr.To(false), + Primary: to.Ptr(false), }, - ID: ptr.To("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic1"), + ID: to.Ptr("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic1"), }, { NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{ - Primary: ptr.To(false), + Primary: to.Ptr(false), }, - ID: ptr.To("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic2"), + ID: to.Ptr("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic2"), }, }, }, @@ -710,51 +710,51 @@ func TestGetPrimaryIPConfig(t *testing.T) { { name: "GetPrimaryIPConfig should get the only IP configuration", nic: network.Interface{ - Name: ptr.To("nic"), + Name: to.Ptr("nic"), InterfacePropertiesFormat: &network.InterfacePropertiesFormat{ IPConfigurations: &[]network.InterfaceIPConfiguration{ { - Name: ptr.To("ipconfig1"), + Name: to.Ptr("ipconfig1"), }, }, }, }, expectedIPConfig: &network.InterfaceIPConfiguration{ - Name: ptr.To("ipconfig1"), + Name: to.Ptr("ipconfig1"), }, }, { name: "GetPrimaryIPConfig should get the primary IP configuration", nic: network.Interface{ - Name: ptr.To("nic"), + Name: to.Ptr("nic"), InterfacePropertiesFormat: &network.InterfacePropertiesFormat{ IPConfigurations: &[]network.InterfaceIPConfiguration{ { - Name: ptr.To("ipconfig1"), + Name: to.Ptr("ipconfig1"), InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ - Primary: ptr.To(true), + Primary: to.Ptr(true), }, }, { - Name: ptr.To("ipconfig2"), + Name: to.Ptr("ipconfig2"), InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ - Primary: ptr.To(false), + Primary: to.Ptr(false), }, }, }, }, }, expectedIPConfig: &network.InterfaceIPConfiguration{ - Name: ptr.To("ipconfig1"), + Name: to.Ptr("ipconfig1"), InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ - Primary: ptr.To(true), + Primary: to.Ptr(true), }, }, }, { name: "GetPrimaryIPConfig should report error if nic don't have IP configuration", nic: network.Interface{ - Name: ptr.To("nic"), + Name: to.Ptr("nic"), InterfacePropertiesFormat: &network.InterfacePropertiesFormat{}, }, expectedErrMsg: fmt.Errorf("nic.IPConfigurations for nic (nicname=%q) is nil", "nic"), @@ -762,19 +762,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", nic: network.Interface{ - Name: ptr.To("nic"), + Name: to.Ptr("nic"), InterfacePropertiesFormat: &network.InterfacePropertiesFormat{ IPConfigurations: &[]network.InterfaceIPConfiguration{ { - Name: ptr.To("ipconfig1"), + Name: to.Ptr("ipconfig1"), InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ - Primary: ptr.To(false), + Primary: to.Ptr(false), }, }, { - Name: ptr.To("ipconfig2"), + Name: to.Ptr("ipconfig2"), InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ - Primary: ptr.To(false), + Primary: to.Ptr(false), }, }, }, @@ -793,21 +793,21 @@ func TestGetPrimaryIPConfig(t *testing.T) { func TestGetIPConfigByIPFamily(t *testing.T) { ipv4IPconfig := network.InterfaceIPConfiguration{ - Name: ptr.To("ipconfig1"), + Name: to.Ptr("ipconfig1"), InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ PrivateIPAddressVersion: network.IPv4, - PrivateIPAddress: ptr.To("10.10.0.12"), + PrivateIPAddress: to.Ptr("10.10.0.12"), }, } ipv6IPconfig := network.InterfaceIPConfiguration{ - Name: ptr.To("ipconfig2"), + Name: to.Ptr("ipconfig2"), InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ PrivateIPAddressVersion: network.IPv6, - PrivateIPAddress: ptr.To("1111:11111:00:00:1111:1111:000:111"), + PrivateIPAddress: to.Ptr("1111:11111:00:00:1111:1111:000:111"), }, } testNic := network.Interface{ - Name: ptr.To("nic"), + Name: to.Ptr("nic"), InterfacePropertiesFormat: &network.InterfacePropertiesFormat{ IPConfigurations: &[]network.InterfaceIPConfiguration{ipv4IPconfig, ipv6IPconfig}, }, @@ -833,7 +833,7 @@ func TestGetIPConfigByIPFamily(t *testing.T) { { name: "GetIPConfigByIPFamily should report error if nic don't have IP configuration", nic: network.Interface{ - Name: ptr.To("nic"), + Name: to.Ptr("nic"), InterfacePropertiesFormat: &network.InterfacePropertiesFormat{}, }, expectedErrMsg: fmt.Errorf("nic.IPConfigurations for nic (nicname=%q) is nil", "nic"), @@ -841,7 +841,7 @@ func TestGetIPConfigByIPFamily(t *testing.T) { { name: "GetIPConfigByIPFamily should report error if nic don't have IPv6 configuration when IPv6 is true", nic: network.Interface{ - Name: ptr.To("nic"), + Name: to.Ptr("nic"), InterfacePropertiesFormat: &network.InterfacePropertiesFormat{ IPConfigurations: &[]network.InterfaceIPConfiguration{ipv4IPconfig}, }, @@ -852,11 +852,11 @@ func TestGetIPConfigByIPFamily(t *testing.T) { { name: "GetIPConfigByIPFamily should report error if nic don't have PrivateIPAddress", nic: network.Interface{ - Name: ptr.To("nic"), + Name: to.Ptr("nic"), InterfacePropertiesFormat: &network.InterfacePropertiesFormat{ IPConfigurations: &[]network.InterfaceIPConfiguration{ { - Name: ptr.To("ipconfig1"), + Name: to.Ptr("ipconfig1"), InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ PrivateIPAddressVersion: network.IPv4, }, @@ -949,8 +949,8 @@ func TestGetStandardInstanceIDByNodeName(t *testing.T) { cloud := GetTestCloud(ctrl) expectedVM := compute.VirtualMachine{ - Name: ptr.To("vm1"), - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/vm1"), + Name: to.Ptr("vm1"), + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/vm1"), } invalidResouceID := "/subscriptions/subscription/resourceGroups/rg/Microsoft.Compute/virtualMachines/vm4" testcases := []struct { @@ -989,8 +989,8 @@ func TestGetStandardInstanceIDByNodeName(t *testing.T) { RawError: fmt.Errorf("VMGet error"), }).AnyTimes() mockVMClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, "vm4", gomock.Any()).Return(compute.VirtualMachine{ - Name: ptr.To("vm4"), - ID: ptr.To(invalidResouceID), + Name: to.Ptr("vm4"), + ID: to.Ptr(invalidResouceID), }, nil).AnyTimes() instanceID, err := cloud.VMSet.GetInstanceIDByNodeName(context.Background(), test.nodeName) @@ -1028,13 +1028,13 @@ func TestGetStandardVMPowerStatusByNodeName(t *testing.T) { name: "GetPowerStatusByNodeName should get power status as expected", nodeName: "vm2", vm: compute.VirtualMachine{ - Name: ptr.To("vm2"), + Name: to.Ptr("vm2"), VirtualMachineProperties: &compute.VirtualMachineProperties{ - ProvisioningState: ptr.To("Succeeded"), + ProvisioningState: to.Ptr("Succeeded"), InstanceView: &compute.VirtualMachineInstanceView{ Statuses: &[]compute.InstanceViewStatus{ { - Code: ptr.To("PowerState/Running"), + Code: to.Ptr("PowerState/Running"), }, }, }, @@ -1046,9 +1046,9 @@ func TestGetStandardVMPowerStatusByNodeName(t *testing.T) { name: "GetPowerStatusByNodeName should get vmPowerStateUnknown if vm.InstanceView is nil", nodeName: "vm3", vm: compute.VirtualMachine{ - Name: ptr.To("vm3"), + Name: to.Ptr("vm3"), VirtualMachineProperties: &compute.VirtualMachineProperties{ - ProvisioningState: ptr.To("Succeeded"), + ProvisioningState: to.Ptr("Succeeded"), }, }, expectedStatus: consts.VMPowerStateUnknown, @@ -1057,9 +1057,9 @@ func TestGetStandardVMPowerStatusByNodeName(t *testing.T) { name: "GetPowerStatusByNodeName should get vmPowerStateUnknown if vm.InstanceView.statuses is nil", nodeName: "vm4", vm: compute.VirtualMachine{ - Name: ptr.To("vm4"), + Name: to.Ptr("vm4"), VirtualMachineProperties: &compute.VirtualMachineProperties{ - ProvisioningState: ptr.To("Succeeded"), + ProvisioningState: to.Ptr("Succeeded"), InstanceView: &compute.VirtualMachineInstanceView{}, }, }, @@ -1103,13 +1103,13 @@ func TestGetStandardVMProvisioningStateByNodeName(t *testing.T) { name: "GetProvisioningStateByNodeName should return Succeeded for running VM", nodeName: "vm2", vm: compute.VirtualMachine{ - Name: ptr.To("vm2"), + Name: to.Ptr("vm2"), VirtualMachineProperties: &compute.VirtualMachineProperties{ - ProvisioningState: ptr.To("Succeeded"), + ProvisioningState: to.Ptr("Succeeded"), InstanceView: &compute.VirtualMachineInstanceView{ Statuses: &[]compute.InstanceViewStatus{ { - Code: ptr.To("PowerState/Running"), + Code: to.Ptr("PowerState/Running"), }, }, }, @@ -1121,7 +1121,7 @@ func TestGetStandardVMProvisioningStateByNodeName(t *testing.T) { name: "GetProvisioningStateByNodeName should return empty string when vm.ProvisioningState is nil", nodeName: "vm3", vm: compute.VirtualMachine{ - Name: ptr.To("vm3"), + Name: to.Ptr("vm3"), VirtualMachineProperties: &compute.VirtualMachineProperties{ ProvisioningState: nil, }, @@ -1167,8 +1167,8 @@ func TestGetStandardVMZoneByNodeName(t *testing.T) { name: "GetZoneByNodeName should get zone as expected", nodeName: "vm2", vm: compute.VirtualMachine{ - Name: ptr.To("vm2"), - Location: ptr.To("EASTUS"), + Name: to.Ptr("vm2"), + Location: to.Ptr("EASTUS"), Zones: &[]string{"2"}, VirtualMachineProperties: &compute.VirtualMachineProperties{ InstanceView: &compute.VirtualMachineInstanceView{ @@ -1185,8 +1185,8 @@ func TestGetStandardVMZoneByNodeName(t *testing.T) { name: "GetZoneByNodeName should get FailureDomain as zone if zone is not used for node", nodeName: "vm3", vm: compute.VirtualMachine{ - Name: ptr.To("vm3"), - Location: ptr.To("EASTUS"), + Name: to.Ptr("vm3"), + Location: to.Ptr("EASTUS"), VirtualMachineProperties: &compute.VirtualMachineProperties{ InstanceView: &compute.VirtualMachineInstanceView{ PlatformFaultDomain: &faultDomain, @@ -1202,8 +1202,8 @@ func TestGetStandardVMZoneByNodeName(t *testing.T) { name: "GetZoneByNodeName should report error if zones is invalid", nodeName: "vm4", vm: compute.VirtualMachine{ - Name: ptr.To("vm4"), - Location: ptr.To("EASTUS"), + Name: to.Ptr("vm4"), + Location: to.Ptr("EASTUS"), Zones: &[]string{"a"}, VirtualMachineProperties: &compute.VirtualMachineProperties{ InstanceView: &compute.VirtualMachineInstanceView{ @@ -1231,13 +1231,13 @@ func TestGetStandardVMSetNames(t *testing.T) { defer ctrl.Finish() testVM := compute.VirtualMachine{ - Name: ptr.To("vm1"), + Name: to.Ptr("vm1"), VirtualMachineProperties: &compute.VirtualMachineProperties{ - AvailabilitySet: &compute.SubResource{ID: ptr.To(asID)}, + AvailabilitySet: &compute.SubResource{ID: to.Ptr(asID)}, }, } testVMWithoutAS := compute.VirtualMachine{ - Name: ptr.To("vm2"), + Name: to.Ptr("vm2"), VirtualMachineProperties: &compute.VirtualMachineProperties{}, } testCases := []struct { @@ -1459,10 +1459,10 @@ func TestStandardEnsureHostInPool(t *testing.T) { } testVM := buildDefaultTestVirtualMachine(availabilitySetID, []string{test.nicID}) - testVM.Name = ptr.To(string(test.nodeName)) + testVM.Name = to.Ptr(string(test.nodeName)) testNIC := buildDefaultTestInterface(false, []string{backendAddressPoolID}) - testNIC.Name = ptr.To(test.nicName) - testNIC.ID = ptr.To(test.nicID) + testNIC.Name = to.Ptr(test.nicName) + testNIC.ID = to.Ptr(test.nicID) testNIC.ProvisioningState = test.nicProvisionState mockVMClient := cloud.VirtualMachinesClient.(*mockvmclient.MockInterface) @@ -1572,13 +1572,13 @@ func TestStandardEnsureHostsInPool(t *testing.T) { for _, test := range testCases { t.Run(test.name, func(t *testing.T) { cloud.Config.LoadBalancerSku = consts.LoadBalancerSkuStandard - cloud.Config.ExcludeMasterFromStandardLB = ptr.To(true) + cloud.Config.ExcludeMasterFromStandardLB = to.Ptr(true) cloud.excludeLoadBalancerNodes = utilsets.NewString(test.excludeLBNodes...) testVM := buildDefaultTestVirtualMachine(availabilitySetID, []string{test.nicID}) testNIC := buildDefaultTestInterface(false, []string{backendAddressPoolID}) - testNIC.Name = ptr.To(test.nicName) - testNIC.ID = ptr.To(test.nicID) + testNIC.Name = to.Ptr(test.nicName) + testNIC.ID = to.Ptr(test.nicID) mockVMClient := cloud.VirtualMachinesClient.(*mockvmclient.MockInterface) mockVMClient.EXPECT().Get(gomock.Any(), cloud.ResourceGroup, test.nodeName, gomock.Any()).Return(testVM, nil).AnyTimes() @@ -1616,11 +1616,11 @@ func TestStandardEnsureBackendPoolDeleted(t *testing.T) { desc: "EnsureBackendPoolDeleted should decouple the nic and the load balancer properly", backendAddressPools: &[]network.BackendAddressPool{ { - ID: ptr.To(backendPoolID), + ID: to.Ptr(backendPoolID), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ BackendIPConfigurations: &[]network.InterfaceIPConfiguration{ { - ID: ptr.To("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/k8s-agentpool1-00000000-nic-1/ipConfigurations/ipconfig1"), + ID: to.Ptr("/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/k8s-agentpool1-00000000-nic-1/ipConfigurations/ipconfig1"), }, }, }, @@ -1640,7 +1640,7 @@ func TestStandardEnsureBackendPoolDeleted(t *testing.T) { cloud.VirtualMachinesClient = mockVMClient mockNICClient := mockinterfaceclient.NewMockInterface(ctrl) test.existingNIC.VirtualMachine = &network.SubResource{ - ID: ptr.To("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/k8s-agentpool1-00000000-1"), + ID: to.Ptr("/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().CreateOrUpdate(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil) @@ -1659,7 +1659,7 @@ func buildDefaultTestInterface(isPrimary bool, lbBackendpoolIDs []string) networ IPConfigurations: &[]network.InterfaceIPConfiguration{ { InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ - Primary: ptr.To(isPrimary), + Primary: to.Ptr(isPrimary), }, }, }, @@ -1668,7 +1668,7 @@ func buildDefaultTestInterface(isPrimary bool, lbBackendpoolIDs []string) networ backendAddressPool := make([]network.BackendAddressPool, 0) for _, id := range lbBackendpoolIDs { backendAddressPool = append(backendAddressPool, network.BackendAddressPool{ - ID: ptr.To(id), + ID: to.Ptr(id), }) } (*expectedNIC.IPConfigurations)[0].LoadBalancerBackendAddressPools = &backendAddressPool @@ -1679,7 +1679,7 @@ func buildDefaultTestVirtualMachine(asID string, nicIDs []string) compute.Virtua expectedVM := compute.VirtualMachine{ VirtualMachineProperties: &compute.VirtualMachineProperties{ AvailabilitySet: &compute.SubResource{ - ID: ptr.To(asID), + ID: to.Ptr(asID), }, NetworkProfile: &compute.NetworkProfile{}, }, @@ -1687,7 +1687,7 @@ func buildDefaultTestVirtualMachine(asID string, nicIDs []string) compute.Virtua networkInterfaces := make([]compute.NetworkInterfaceReference, 0) for _, nicID := range nicIDs { networkInterfaces = append(networkInterfaces, compute.NetworkInterfaceReference{ - ID: ptr.To(nicID), + ID: to.Ptr(nicID), }) } expectedVM.VirtualMachineProperties.NetworkProfile.NetworkInterfaces = &networkInterfaces @@ -1699,12 +1699,12 @@ func TestStandardGetNodeNameByIPConfigurationID(t *testing.T) { defer ctrl.Finish() cloud := GetTestCloud(ctrl) expectedVM := buildDefaultTestVirtualMachine("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/availabilitySets/AGENTPOOL1-AVAILABILITYSET-00000000", []string{}) - expectedVM.Name = ptr.To("name") + expectedVM.Name = to.Ptr("name") mockVMClient := cloud.VirtualMachinesClient.(*mockvmclient.MockInterface) mockVMClient.EXPECT().Get(gomock.Any(), "rg", "k8s-agentpool1-00000000-0", gomock.Any()).Return(expectedVM, nil) expectedNIC := buildDefaultTestInterface(true, []string{}) expectedNIC.VirtualMachine = &network.SubResource{ - ID: ptr.To("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/k8s-agentpool1-00000000-0"), + ID: to.Ptr("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/k8s-agentpool1-00000000-0"), } mockNICClient := cloud.InterfacesClient.(*mockinterfaceclient.MockInterface) mockNICClient.EXPECT().Get(gomock.Any(), "rg", "k8s-agentpool1-00000000-nic-0", gomock.Any()).Return(expectedNIC, nil) @@ -1764,11 +1764,11 @@ func TestGetAvailabilitySetByNodeName(t *testing.T) { subResources := make([]compute.SubResource, 0) for _, vmID := range test.vmasVMIDs { subResources = append(subResources, compute.SubResource{ - ID: ptr.To(vmID), + ID: to.Ptr(vmID), }) } expected := compute.AvailabilitySet{ - Name: ptr.To("vmas-1"), + Name: to.Ptr("vmas-1"), AvailabilitySetProperties: &compute.AvailabilitySetProperties{ VirtualMachines: &subResources, }, @@ -1804,8 +1804,8 @@ func TestGetNodeCIDRMasksByProviderIDAvailabilitySet(t *testing.T) { description: "GetNodeCIDRMaksByProviderID should return the correct mask sizes", providerID: "azure:///subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/vm-0", tags: map[string]*string{ - consts.VMSetCIDRIPV4TagKey: ptr.To("24"), - consts.VMSetCIDRIPV6TagKey: ptr.To("64"), + consts.VMSetCIDRIPV4TagKey: to.Ptr("24"), + consts.VMSetCIDRIPV6TagKey: to.Ptr("64"), }, expectedIPV4MaskSize: 24, expectedIPV6MaskSize: 64, @@ -1820,7 +1820,7 @@ func TestGetNodeCIDRMasksByProviderIDAvailabilitySet(t *testing.T) { description: "GetNodeCIDRMaksByProviderID should return the correct mask sizes even if some of the tags are not specified", providerID: "azure:///subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/vm-0", tags: map[string]*string{ - consts.VMSetCIDRIPV4TagKey: ptr.To("24"), + consts.VMSetCIDRIPV4TagKey: to.Ptr("24"), }, expectedIPV4MaskSize: 24, }, @@ -1828,8 +1828,8 @@ func TestGetNodeCIDRMasksByProviderIDAvailabilitySet(t *testing.T) { description: "GetNodeCIDRMaksByProviderID should not fail even if some of the tag is invalid", providerID: "azure:///subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/vm-0", tags: map[string]*string{ - consts.VMSetCIDRIPV4TagKey: ptr.To("abc"), - consts.VMSetCIDRIPV6TagKey: ptr.To("64"), + consts.VMSetCIDRIPV4TagKey: to.Ptr("abc"), + consts.VMSetCIDRIPV6TagKey: to.Ptr("64"), }, expectedIPV6MaskSize: 64, }, @@ -1844,10 +1844,10 @@ func TestGetNodeCIDRMasksByProviderIDAvailabilitySet(t *testing.T) { cloud.AvailabilitySetsClient = mockVMASClient expected := compute.AvailabilitySet{ - Name: ptr.To("vmas-1"), + Name: to.Ptr("vmas-1"), AvailabilitySetProperties: &compute.AvailabilitySetProperties{ VirtualMachines: &[]compute.SubResource{ - {ID: ptr.To("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/vm-0")}, + {ID: to.Ptr("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/vm-0")}, }, }, Tags: tc.tags, @@ -1931,10 +1931,10 @@ func TestGetNodeVMSetName(t *testing.T) { }, expectedVMs: []compute.VirtualMachine{ { - Name: ptr.To("vm"), + Name: to.Ptr("vm"), VirtualMachineProperties: &compute.VirtualMachineProperties{ AvailabilitySet: &compute.SubResource{ - ID: ptr.To("/"), + ID: to.Ptr("/"), }, }, }, @@ -1956,10 +1956,10 @@ func TestGetNodeVMSetName(t *testing.T) { }, expectedVMs: []compute.VirtualMachine{ { - Name: ptr.To("vm"), + Name: to.Ptr("vm"), VirtualMachineProperties: &compute.VirtualMachineProperties{ AvailabilitySet: &compute.SubResource{ - ID: ptr.To("as"), + ID: to.Ptr("as"), }, }, }, diff --git a/pkg/provider/azure_storageaccount.go b/pkg/provider/azure_storageaccount.go index bd4bcf9ef5..01ea0dc44c 100644 --- a/pkg/provider/azure_storageaccount.go +++ b/pkg/provider/azure_storageaccount.go @@ -25,13 +25,13 @@ import ( "strings" "time" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" privatedns "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/privatedns/armprivatedns" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" "github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2021-09-01/storage" - + "github.com/samber/lo" "k8s.io/klog/v2" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/accountclient" "sigs.k8s.io/cloud-provider-azure/pkg/cache" @@ -302,7 +302,7 @@ func (az *Cloud) EnsureStorageAccount(ctx context.Context, accountOptions *Accou } var privateDNSZoneName string - if ptr.Deref(accountOptions.CreatePrivateEndpoint, false) { + if lo.FromPtrOr(accountOptions.CreatePrivateEndpoint, false) { if accountOptions.StorageType == "" { klog.V(2).Info("set StorageType as file when not specified") accountOptions.StorageType = StorageTypeFile @@ -377,7 +377,7 @@ func (az *Cloud) EnsureStorageAccount(ctx context.Context, accountOptions *Accou } } - if ptr.Deref(accountOptions.CreatePrivateEndpoint, false) { + if lo.FromPtrOr(accountOptions.CreatePrivateEndpoint, false) { clientFactory := az.NetworkClientFactory if clientFactory == nil { // multi-tenant support @@ -426,7 +426,7 @@ func (az *Cloud) EnsureStorageAccount(ctx context.Context, accountOptions *Accou } } - if ptr.Deref(accountOptions.CreatePrivateEndpoint, false) { + if lo.FromPtrOr(accountOptions.CreatePrivateEndpoint, false) { networkRuleSet = &storage.NetworkRuleSet{ DefaultAction: storage.DefaultActionDeny, } @@ -477,8 +477,8 @@ func (az *Cloud) EnsureStorageAccount(ctx context.Context, accountOptions *Accou RequireInfrastructureEncryption: accountOptions.RequireInfrastructureEncryption, KeySource: storage.KeySourceMicrosoftStorage, Services: &storage.EncryptionServices{ - File: &storage.EncryptionService{Enabled: ptr.To(true)}, - Blob: &storage.EncryptionService{Enabled: ptr.To(true)}, + File: &storage.EncryptionService{Enabled: to.Ptr(true)}, + Blob: &storage.EncryptionService{Enabled: to.Ptr(true)}, }, } } @@ -496,8 +496,8 @@ func (az *Cloud) EnsureStorageAccount(ctx context.Context, accountOptions *Accou }, KeySource: storage.KeySourceMicrosoftKeyvault, Services: &storage.EncryptionServices{ - File: &storage.EncryptionService{Enabled: ptr.To(true)}, - Blob: &storage.EncryptionService{Enabled: ptr.To(true)}, + File: &storage.EncryptionService{Enabled: to.Ptr(true)}, + Blob: &storage.EncryptionService{Enabled: to.Ptr(true)}, }, } } @@ -509,7 +509,7 @@ func (az *Cloud) EnsureStorageAccount(ctx context.Context, accountOptions *Accou return "", "", fmt.Errorf("failed to create storage account %s, error: %v", accountName, rerr) } - if ptr.Deref(accountOptions.EnableBlobVersioning, false) || + if lo.FromPtrOr(accountOptions.EnableBlobVersioning, false) || accountOptions.SoftDeleteBlobs > 0 || accountOptions.SoftDeleteContainers > 0 { var blobPolicy, containerPolicy *storage.DeleteRetentionPolicy @@ -517,19 +517,19 @@ func (az *Cloud) EnsureStorageAccount(ctx context.Context, accountOptions *Accou if accountOptions.SoftDeleteContainers > 0 { containerPolicy = &storage.DeleteRetentionPolicy{ - Enabled: ptr.To(accountOptions.SoftDeleteContainers > 0), - Days: ptr.To(accountOptions.SoftDeleteContainers), + Enabled: to.Ptr(accountOptions.SoftDeleteContainers > 0), + Days: to.Ptr(accountOptions.SoftDeleteContainers), } } if accountOptions.SoftDeleteBlobs > 0 { blobPolicy = &storage.DeleteRetentionPolicy{ - Enabled: ptr.To(accountOptions.SoftDeleteBlobs > 0), - Days: ptr.To(accountOptions.SoftDeleteBlobs), + Enabled: to.Ptr(accountOptions.SoftDeleteBlobs > 0), + Days: to.Ptr(accountOptions.SoftDeleteBlobs), } } if accountOptions.EnableBlobVersioning != nil { - enableBlobVersioning = ptr.To(*accountOptions.EnableBlobVersioning) + enableBlobVersioning = to.Ptr(*accountOptions.EnableBlobVersioning) } property := storage.BlobServiceProperties{ @@ -577,7 +577,7 @@ func (az *Cloud) EnsureStorageAccount(ctx context.Context, accountOptions *Accou } } - if ptr.Deref(accountOptions.CreatePrivateEndpoint, false) { + if lo.FromPtrOr(accountOptions.CreatePrivateEndpoint, false) { // Get properties of the storageAccount storageAccount, err := az.StorageAccountClient.GetProperties(ctx, subsID, resourceGroup, accountName) if err != nil { @@ -687,7 +687,7 @@ func (az *Cloud) createVNetLink(ctx context.Context, vNetLinkName, vnetResourceG Location: &location, Properties: &privatedns.VirtualNetworkLinkProperties{ VirtualNetwork: &privatedns.SubResource{ID: &vnetID}, - RegistrationEnabled: ptr.To(false)}, + RegistrationEnabled: to.Ptr(false)}, } _, err := vnetLinkClient.CreateOrUpdate(ctx, vnetResourceGroup, privateDNSZoneName, vNetLinkName, parameters) return err @@ -856,7 +856,7 @@ func AreVNetRulesEqual(account storage.Account, accountOptions *AccountOptions) for _, subnetID := range accountOptions.VirtualNetworkResourceIDs { found := false for _, rule := range *account.AccountProperties.NetworkRuleSet.VirtualNetworkRules { - if strings.EqualFold(ptr.Deref(rule.VirtualNetworkResourceID, ""), subnetID) && rule.Action == storage.ActionAllow { + if strings.EqualFold(lo.FromPtrOr(rule.VirtualNetworkResourceID, ""), subnetID) && rule.Action == storage.ActionAllow { found = true break } @@ -865,7 +865,7 @@ func AreVNetRulesEqual(account storage.Account, accountOptions *AccountOptions) return false } } - klog.V(2).Infof("found all vnet rules(%v) in account %s", accountOptions.VirtualNetworkResourceIDs, ptr.Deref(account.Name, "")) + klog.V(2).Infof("found all vnet rules(%v) in account %s", accountOptions.VirtualNetworkResourceIDs, lo.FromPtrOr(account.Name, "")) } return true } @@ -884,7 +884,7 @@ func isTaggedWithSkip(account storage.Account) bool { if account.Tags != nil { // skip account with SkipMatchingTag tag if _, ok := account.Tags[SkipMatchingTag]; ok { - klog.V(2).Infof("found %s tag for account %s, skip matching", SkipMatchingTag, ptr.Deref(account.Name, "")) + klog.V(2).Infof("found %s tag for account %s, skip matching", SkipMatchingTag, lo.FromPtrOr(account.Name, "")) return false } } @@ -908,7 +908,7 @@ func isTagsEqual(account storage.Account, accountOptions *AccountOptions) bool { // ensure all tags in accountOptions are in account for k, v := range accountOptions.Tags { - if ptr.Deref(account.Tags[k], "") != v { + if lo.FromPtrOr(account.Tags[k], "") != v { return false } } @@ -916,15 +916,15 @@ func isTagsEqual(account storage.Account, accountOptions *AccountOptions) bool { } func isHnsPropertyEqual(account storage.Account, accountOptions *AccountOptions) bool { - return ptr.Deref(accountOptions.IsHnsEnabled, false) == ptr.Deref(account.IsHnsEnabled, false) + return lo.FromPtrOr(accountOptions.IsHnsEnabled, false) == lo.FromPtrOr(account.IsHnsEnabled, false) } func isEnableNfsV3PropertyEqual(account storage.Account, accountOptions *AccountOptions) bool { - return ptr.Deref(accountOptions.EnableNfsV3, false) == ptr.Deref(account.EnableNfsV3, false) + return lo.FromPtrOr(accountOptions.EnableNfsV3, false) == lo.FromPtrOr(account.EnableNfsV3, false) } func isEnableHTTPSTrafficOnlyEqual(account storage.Account, accountOptions *AccountOptions) bool { - return accountOptions.EnableHTTPSTrafficOnly == ptr.Deref(account.EnableHTTPSTrafficOnly, true) + return accountOptions.EnableHTTPSTrafficOnly == lo.FromPtrOr(account.EnableHTTPSTrafficOnly, true) } func isPrivateEndpointAsExpected(account storage.Account, accountOptions *AccountOptions) bool { @@ -933,29 +933,29 @@ func isPrivateEndpointAsExpected(account storage.Account, accountOptions *Accoun return true } - if ptr.Deref(accountOptions.CreatePrivateEndpoint, false) && account.PrivateEndpointConnections != nil && len(*account.PrivateEndpointConnections) > 0 { + if lo.FromPtrOr(accountOptions.CreatePrivateEndpoint, false) && account.PrivateEndpointConnections != nil && len(*account.PrivateEndpointConnections) > 0 { return true } - if !ptr.Deref(accountOptions.CreatePrivateEndpoint, false) && (account.PrivateEndpointConnections == nil || len(*account.PrivateEndpointConnections) == 0) { + if !lo.FromPtrOr(accountOptions.CreatePrivateEndpoint, false) && (account.PrivateEndpointConnections == nil || len(*account.PrivateEndpointConnections) == 0) { return true } return false } func isAllowBlobPublicAccessEqual(account storage.Account, accountOptions *AccountOptions) bool { - return ptr.Deref(accountOptions.AllowBlobPublicAccess, true) == ptr.Deref(account.AllowBlobPublicAccess, true) + return lo.FromPtrOr(accountOptions.AllowBlobPublicAccess, true) == lo.FromPtrOr(account.AllowBlobPublicAccess, true) } func isRequireInfrastructureEncryptionEqual(account storage.Account, accountOptions *AccountOptions) bool { - requireInfraEncryption := ptr.Deref(accountOptions.RequireInfrastructureEncryption, false) + requireInfraEncryption := lo.FromPtrOr(accountOptions.RequireInfrastructureEncryption, false) if account.Encryption == nil { return !requireInfraEncryption } - return requireInfraEncryption == ptr.Deref(account.Encryption.RequireInfrastructureEncryption, false) + return requireInfraEncryption == lo.FromPtrOr(account.Encryption.RequireInfrastructureEncryption, false) } func isAllowSharedKeyAccessEqual(account storage.Account, accountOptions *AccountOptions) bool { - return ptr.Deref(accountOptions.AllowSharedKeyAccess, true) == ptr.Deref(account.AllowSharedKeyAccess, true) + return lo.FromPtrOr(accountOptions.AllowSharedKeyAccess, true) == lo.FromPtrOr(account.AllowSharedKeyAccess, true) } func isAccessTierEqual(account storage.Account, accountOptions *AccountOptions) bool { @@ -975,7 +975,7 @@ func (az *Cloud) isMultichannelEnabledEqual(ctx context.Context, account storage return false, nil } - prop, err := az.getFileServicePropertiesCache(ctx, accountOptions.SubscriptionID, accountOptions.ResourceGroup, ptr.Deref(account.Name, "")) + prop, err := az.getFileServicePropertiesCache(ctx, accountOptions.SubscriptionID, accountOptions.ResourceGroup, lo.FromPtrOr(account.Name, "")) if err != nil { return false, err } @@ -987,7 +987,7 @@ func (az *Cloud) isMultichannelEnabledEqual(ctx context.Context, account storage return !*accountOptions.IsMultichannelEnabled, nil } - return *accountOptions.IsMultichannelEnabled == ptr.Deref(prop.FileServicePropertiesProperties.ProtocolSettings.Smb.Multichannel.Enabled, false), nil + return *accountOptions.IsMultichannelEnabled == lo.FromPtrOr(prop.FileServicePropertiesProperties.ProtocolSettings.Smb.Multichannel.Enabled, false), nil } func (az *Cloud) isDisableFileServiceDeleteRetentionPolicyEqual(ctx context.Context, account storage.Account, accountOptions *AccountOptions) (bool, error) { @@ -1000,7 +1000,7 @@ func (az *Cloud) isDisableFileServiceDeleteRetentionPolicyEqual(ctx context.Cont return false, nil } - prop, err := az.FileClient.WithSubscriptionID(accountOptions.SubscriptionID).GetServiceProperties(ctx, accountOptions.ResourceGroup, ptr.Deref(account.Name, "")) + prop, err := az.FileClient.WithSubscriptionID(accountOptions.SubscriptionID).GetServiceProperties(ctx, accountOptions.ResourceGroup, lo.FromPtrOr(account.Name, "")) if err != nil { return false, err } @@ -1022,7 +1022,7 @@ func (az *Cloud) isEnableBlobDataProtectionEqual(ctx context.Context, account st return true, nil } - property, err := az.BlobClient.GetServiceProperties(ctx, accountOptions.SubscriptionID, accountOptions.ResourceGroup, ptr.Deref(account.Name, "")) + property, err := az.BlobClient.GetServiceProperties(ctx, accountOptions.SubscriptionID, accountOptions.ResourceGroup, lo.FromPtrOr(account.Name, "")) if err != nil { return false, err } @@ -1035,7 +1035,7 @@ func (az *Cloud) isEnableBlobDataProtectionEqual(ctx context.Context, account st func isSoftDeleteBlobsEqual(property storage.BlobServiceProperties, accountOptions *AccountOptions) bool { wantEnable := accountOptions.SoftDeleteBlobs > 0 actualEnable := property.DeleteRetentionPolicy != nil && - ptr.Deref(property.DeleteRetentionPolicy.Enabled, false) + lo.FromPtrOr(property.DeleteRetentionPolicy.Enabled, false) if wantEnable != actualEnable { return false } @@ -1043,13 +1043,13 @@ func isSoftDeleteBlobsEqual(property storage.BlobServiceProperties, accountOptio return true } - return accountOptions.SoftDeleteBlobs == ptr.Deref(property.DeleteRetentionPolicy.Days, 0) + return accountOptions.SoftDeleteBlobs == lo.FromPtrOr(property.DeleteRetentionPolicy.Days, 0) } func isSoftDeleteContainersEqual(property storage.BlobServiceProperties, accountOptions *AccountOptions) bool { wantEnable := accountOptions.SoftDeleteContainers > 0 actualEnable := property.ContainerDeleteRetentionPolicy != nil && - ptr.Deref(property.ContainerDeleteRetentionPolicy.Enabled, false) + lo.FromPtrOr(property.ContainerDeleteRetentionPolicy.Enabled, false) if wantEnable != actualEnable { return false } @@ -1057,9 +1057,9 @@ func isSoftDeleteContainersEqual(property storage.BlobServiceProperties, account return true } - return accountOptions.SoftDeleteContainers == ptr.Deref(property.ContainerDeleteRetentionPolicy.Days, 0) + return accountOptions.SoftDeleteContainers == lo.FromPtrOr(property.ContainerDeleteRetentionPolicy.Days, 0) } func isEnableBlobVersioningEqual(property storage.BlobServiceProperties, accountOptions *AccountOptions) bool { - return ptr.Deref(accountOptions.EnableBlobVersioning, false) == ptr.Deref(property.IsVersioningEnabled, false) + return lo.FromPtrOr(accountOptions.EnableBlobVersioning, false) == lo.FromPtrOr(property.IsVersioningEnabled, false) } diff --git a/pkg/provider/azure_storageaccount_test.go b/pkg/provider/azure_storageaccount_test.go index dda0fbd0f2..771b72d2d4 100644 --- a/pkg/provider/azure_storageaccount_test.go +++ b/pkg/provider/azure_storageaccount_test.go @@ -25,16 +25,15 @@ import ( "testing" "time" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" privatedns "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/privatedns/armprivatedns" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" "github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2021-09-01/storage" "github.com/Azure/go-autorest/autorest/date" + "github.com/samber/lo" "github.com/stretchr/testify/assert" - "go.uber.org/mock/gomock" - "k8s.io/utils/ptr" - "sigs.k8s.io/cloud-provider-azure/pkg/azclient/privatezoneclient/mock_privatezoneclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualnetworklinkclient/mock_virtualnetworklinkclient" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/blobclient/mockblobclient" @@ -349,7 +348,7 @@ func TestGetStorageAccountEdgeCases(t *testing.T) { testCase: "account options CreatePrivateEndpoint is true and no private endpoint exists", testAccountOptions: &AccountOptions{ ResourceGroup: "rg", - CreatePrivateEndpoint: ptr.To(true), + CreatePrivateEndpoint: to.Ptr(true), }, testResourceGroups: []storage.Account{{Name: &name, Kind: "kind", Location: &location, Sku: sku, AccountProperties: &storage.AccountProperties{}}}, expectedResult: []accountWithLocation{}, @@ -402,9 +401,9 @@ func TestEnsureStorageAccount(t *testing.T) { } testStorageAccounts := []storage.Account{ - {Name: ptr.To("testStorageAccount"), Kind: "kind", Location: &location, Sku: sku, AccountProperties: &storage.AccountProperties{NetworkRuleSet: &storage.NetworkRuleSet{}}}, - {Name: ptr.To("wantedAccount"), Kind: "kind", Location: &location, Sku: sku, AccountProperties: &storage.AccountProperties{NetworkRuleSet: &storage.NetworkRuleSet{}}}, - {Name: ptr.To("otherAccount"), Kind: "kind", Location: &location, Sku: sku, AccountProperties: &storage.AccountProperties{NetworkRuleSet: &storage.NetworkRuleSet{}}}, + {Name: to.Ptr("testStorageAccount"), Kind: "kind", Location: &location, Sku: sku, AccountProperties: &storage.AccountProperties{NetworkRuleSet: &storage.NetworkRuleSet{}}}, + {Name: to.Ptr("wantedAccount"), Kind: "kind", Location: &location, Sku: sku, AccountProperties: &storage.AccountProperties{NetworkRuleSet: &storage.NetworkRuleSet{}}}, + {Name: to.Ptr("otherAccount"), Kind: "kind", Location: &location, Sku: sku, AccountProperties: &storage.AccountProperties{NetworkRuleSet: &storage.NetworkRuleSet{}}}, } value := "foo bar" @@ -436,13 +435,13 @@ func TestEnsureStorageAccount(t *testing.T) { { name: "[Success] EnsureStorageAccount with createPrivateEndpoint and storagetype blob", createAccount: true, - createPrivateEndpoint: ptr.To(true), + createPrivateEndpoint: to.Ptr(true), mockStorageAccountsClient: true, setAccountOptions: true, pickRandomMatchingAccount: true, storageType: StorageTypeBlob, - requireInfrastructureEncryption: ptr.To(true), - keyVaultURL: ptr.To("keyVaultURL"), + requireInfrastructureEncryption: to.Ptr(true), + keyVaultURL: to.Ptr("keyVaultURL"), resourceGroup: "rg", accessTier: "AccessTierHot", accountName: "", @@ -451,11 +450,11 @@ func TestEnsureStorageAccount(t *testing.T) { { name: "[Success] EnsureStorageAccount with createPrivateEndpoint", createAccount: true, - createPrivateEndpoint: ptr.To(true), + createPrivateEndpoint: to.Ptr(true), mockStorageAccountsClient: true, setAccountOptions: true, - requireInfrastructureEncryption: ptr.To(true), - keyVaultURL: ptr.To("keyVaultURL"), + requireInfrastructureEncryption: to.Ptr(true), + keyVaultURL: to.Ptr("keyVaultURL"), resourceGroup: "rg", accessTier: "AccessTierHot", accountName: "", @@ -465,7 +464,7 @@ func TestEnsureStorageAccount(t *testing.T) { name: "[Success] EnsureStorageAccount returns with source account", mockStorageAccountsClient: true, setAccountOptions: true, - requireInfrastructureEncryption: ptr.To(true), + requireInfrastructureEncryption: to.Ptr(true), resourceGroup: "rg", sourceAccountName: "wantedAccount", accountName: "wantedAccount", @@ -474,7 +473,7 @@ func TestEnsureStorageAccount(t *testing.T) { { name: "[Failed] EnsureStorageAccount with createPrivateEndpoint: get storage key failed", createAccount: true, - createPrivateEndpoint: ptr.To(true), + createPrivateEndpoint: to.Ptr(true), SubnetPropertiesFormatNil: true, mockStorageAccountsClient: true, setAccountOptions: true, @@ -516,7 +515,7 @@ func TestEnsureStorageAccount(t *testing.T) { cloud.StorageAccountClient = mockStorageAccountsClient } - if ptr.Deref(test.createPrivateEndpoint, false) { + if lo.FromPtrOr(test.createPrivateEndpoint, false) { mockStorageAccountsClient.EXPECT().ListByResourceGroup(gomock.Any(), gomock.Any(), gomock.Any()).Return(testStorageAccounts, nil).AnyTimes() mockStorageAccountsClient.EXPECT().Create(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil).AnyTimes() mockStorageAccountsClient.EXPECT().GetProperties(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(testStorageAccounts[0], nil).AnyTimes() @@ -566,7 +565,7 @@ func TestEnsureStorageAccount(t *testing.T) { SubscriptionID: test.subscriptionID, AccessTier: test.accessTier, StorageType: test.storageType, - EnableBlobVersioning: ptr.To(true), + EnableBlobVersioning: to.Ptr(true), SoftDeleteBlobs: 7, SoftDeleteContainers: 7, PickRandomMatchingAccount: test.pickRandomMatchingAccount, @@ -721,13 +720,13 @@ func TestAddStorageAccountTags(t *testing.T) { { name: "tags update", account: "account", - tags: map[string]*string{"key": ptr.To("value")}, + tags: map[string]*string{"key": to.Ptr("value")}, expectedErr: nil, }, { name: "tags update in parallel", account: "account", - tags: map[string]*string{"key": ptr.To("value")}, + tags: map[string]*string{"key": to.Ptr("value")}, parallelThread: 10, expectedErr: nil, }, @@ -811,7 +810,7 @@ func TestRemoveStorageAccountTags(t *testing.T) { for _, test := range tests { mockStorageAccountsClient := mockstorageaccountclient.NewMockInterface(ctrl) cloud.StorageAccountClient = mockStorageAccountsClient - mockStorageAccountsClient.EXPECT().GetProperties(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(storage.Account{Tags: map[string]*string{"key": ptr.To("value")}}, nil).AnyTimes() + mockStorageAccountsClient.EXPECT().GetProperties(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(storage.Account{Tags: map[string]*string{"key": to.Ptr("value")}}, nil).AnyTimes() parallelThread := 1 if test.parallelThread > 1 { @@ -853,7 +852,7 @@ func TestIsPrivateEndpointAsExpected(t *testing.T) { }, }, accountOptions: &AccountOptions{ - CreatePrivateEndpoint: ptr.To(true), + CreatePrivateEndpoint: to.Ptr(true), }, expectedResult: true, }, @@ -864,7 +863,7 @@ func TestIsPrivateEndpointAsExpected(t *testing.T) { }, }, accountOptions: &AccountOptions{ - CreatePrivateEndpoint: ptr.To(false), + CreatePrivateEndpoint: to.Ptr(false), }, expectedResult: true, }, @@ -875,7 +874,7 @@ func TestIsPrivateEndpointAsExpected(t *testing.T) { }, }, accountOptions: &AccountOptions{ - CreatePrivateEndpoint: ptr.To(false), + CreatePrivateEndpoint: to.Ptr(false), }, expectedResult: false, }, @@ -897,7 +896,7 @@ func TestIsPrivateEndpointAsExpected(t *testing.T) { }, }, accountOptions: &AccountOptions{ - CreatePrivateEndpoint: ptr.To(true), + CreatePrivateEndpoint: to.Ptr(true), }, expectedResult: false, }, @@ -936,7 +935,7 @@ func TestIsTagsEqual(t *testing.T) { desc: "identitical tags", account: storage.Account{ Tags: map[string]*string{ - "key": ptr.To("value"), + "key": to.Ptr("value"), "key2": nil, }, }, @@ -952,8 +951,8 @@ func TestIsTagsEqual(t *testing.T) { desc: "identitical tags", account: storage.Account{ Tags: map[string]*string{ - "key": ptr.To("value"), - "key2": ptr.To("value2"), + "key": to.Ptr("value"), + "key2": to.Ptr("value2"), }, }, accountOptions: &AccountOptions{ @@ -968,7 +967,7 @@ func TestIsTagsEqual(t *testing.T) { desc: "non-identitical tags while MatchTags is false", account: storage.Account{ Tags: map[string]*string{ - "key": ptr.To("value2"), + "key": to.Ptr("value2"), }, }, accountOptions: &AccountOptions{ @@ -983,7 +982,7 @@ func TestIsTagsEqual(t *testing.T) { desc: "non-identitical tags", account: storage.Account{ Tags: map[string]*string{ - "key": ptr.To("value2"), + "key": to.Ptr("value2"), }, }, accountOptions: &AccountOptions{ @@ -998,7 +997,7 @@ func TestIsTagsEqual(t *testing.T) { desc: "non-identitical tags with different keys", account: storage.Account{ Tags: map[string]*string{ - "key1": ptr.To("value2"), + "key1": to.Ptr("value2"), }, }, accountOptions: &AccountOptions{ @@ -1039,7 +1038,7 @@ func TestIsHnsPropertyEqual(t *testing.T) { { account: storage.Account{ AccountProperties: &storage.AccountProperties{ - IsHnsEnabled: ptr.To(true), + IsHnsEnabled: to.Ptr(true), }, }, accountOptions: &AccountOptions{}, @@ -1050,18 +1049,18 @@ func TestIsHnsPropertyEqual(t *testing.T) { AccountProperties: &storage.AccountProperties{}, }, accountOptions: &AccountOptions{ - IsHnsEnabled: ptr.To(false), + IsHnsEnabled: to.Ptr(false), }, expectedResult: true, }, { account: storage.Account{ AccountProperties: &storage.AccountProperties{ - IsHnsEnabled: ptr.To(true), + IsHnsEnabled: to.Ptr(true), }, }, accountOptions: &AccountOptions{ - IsHnsEnabled: ptr.To(true), + IsHnsEnabled: to.Ptr(true), }, expectedResult: true, }, @@ -1070,18 +1069,18 @@ func TestIsHnsPropertyEqual(t *testing.T) { AccountProperties: &storage.AccountProperties{}, }, accountOptions: &AccountOptions{ - IsHnsEnabled: ptr.To(true), + IsHnsEnabled: to.Ptr(true), }, expectedResult: false, }, { account: storage.Account{ AccountProperties: &storage.AccountProperties{ - IsHnsEnabled: ptr.To(true), + IsHnsEnabled: to.Ptr(true), }, }, accountOptions: &AccountOptions{ - IsHnsEnabled: ptr.To(false), + IsHnsEnabled: to.Ptr(false), }, expectedResult: false, }, @@ -1102,7 +1101,7 @@ func TestIsEnableNfsV3PropertyEqual(t *testing.T) { { account: storage.Account{ AccountProperties: &storage.AccountProperties{ - EnableNfsV3: ptr.To(true), + EnableNfsV3: to.Ptr(true), }, }, accountOptions: &AccountOptions{}, @@ -1113,18 +1112,18 @@ func TestIsEnableNfsV3PropertyEqual(t *testing.T) { AccountProperties: &storage.AccountProperties{}, }, accountOptions: &AccountOptions{ - EnableNfsV3: ptr.To(false), + EnableNfsV3: to.Ptr(false), }, expectedResult: true, }, { account: storage.Account{ AccountProperties: &storage.AccountProperties{ - EnableNfsV3: ptr.To(true), + EnableNfsV3: to.Ptr(true), }, }, accountOptions: &AccountOptions{ - EnableNfsV3: ptr.To(true), + EnableNfsV3: to.Ptr(true), }, expectedResult: true, }, @@ -1133,18 +1132,18 @@ func TestIsEnableNfsV3PropertyEqual(t *testing.T) { AccountProperties: &storage.AccountProperties{}, }, accountOptions: &AccountOptions{ - EnableNfsV3: ptr.To(true), + EnableNfsV3: to.Ptr(true), }, expectedResult: false, }, { account: storage.Account{ AccountProperties: &storage.AccountProperties{ - EnableNfsV3: ptr.To(true), + EnableNfsV3: to.Ptr(true), }, }, accountOptions: &AccountOptions{ - EnableNfsV3: ptr.To(false), + EnableNfsV3: to.Ptr(false), }, expectedResult: false, }, @@ -1165,7 +1164,7 @@ func TestIsEnableHTTPSTrafficOnly(t *testing.T) { { account: storage.Account{ AccountProperties: &storage.AccountProperties{ - EnableHTTPSTrafficOnly: ptr.To(true), + EnableHTTPSTrafficOnly: to.Ptr(true), }, }, accountOptions: &AccountOptions{}, @@ -1183,7 +1182,7 @@ func TestIsEnableHTTPSTrafficOnly(t *testing.T) { { account: storage.Account{ AccountProperties: &storage.AccountProperties{ - EnableHTTPSTrafficOnly: ptr.To(true), + EnableHTTPSTrafficOnly: to.Ptr(true), }, }, accountOptions: &AccountOptions{ @@ -1203,7 +1202,7 @@ func TestIsEnableHTTPSTrafficOnly(t *testing.T) { { account: storage.Account{ AccountProperties: &storage.AccountProperties{ - EnableHTTPSTrafficOnly: ptr.To(true), + EnableHTTPSTrafficOnly: to.Ptr(true), }, }, accountOptions: &AccountOptions{ @@ -1228,7 +1227,7 @@ func TestIsAllowBlobPublicAccessEqual(t *testing.T) { { account: storage.Account{ AccountProperties: &storage.AccountProperties{ - AllowBlobPublicAccess: ptr.To(true), + AllowBlobPublicAccess: to.Ptr(true), }, }, accountOptions: &AccountOptions{}, @@ -1239,18 +1238,18 @@ func TestIsAllowBlobPublicAccessEqual(t *testing.T) { AccountProperties: &storage.AccountProperties{}, }, accountOptions: &AccountOptions{ - AllowBlobPublicAccess: ptr.To(false), + AllowBlobPublicAccess: to.Ptr(false), }, expectedResult: false, }, { account: storage.Account{ AccountProperties: &storage.AccountProperties{ - AllowBlobPublicAccess: ptr.To(true), + AllowBlobPublicAccess: to.Ptr(true), }, }, accountOptions: &AccountOptions{ - AllowBlobPublicAccess: ptr.To(true), + AllowBlobPublicAccess: to.Ptr(true), }, expectedResult: true, }, @@ -1259,18 +1258,18 @@ func TestIsAllowBlobPublicAccessEqual(t *testing.T) { AccountProperties: &storage.AccountProperties{}, }, accountOptions: &AccountOptions{ - AllowBlobPublicAccess: ptr.To(true), + AllowBlobPublicAccess: to.Ptr(true), }, expectedResult: true, }, { account: storage.Account{ AccountProperties: &storage.AccountProperties{ - AllowBlobPublicAccess: ptr.To(true), + AllowBlobPublicAccess: to.Ptr(true), }, }, accountOptions: &AccountOptions{ - AllowBlobPublicAccess: ptr.To(false), + AllowBlobPublicAccess: to.Ptr(false), }, expectedResult: false, }, @@ -1291,7 +1290,7 @@ func TestIsAllowSharedKeyAccessEqual(t *testing.T) { { account: storage.Account{ AccountProperties: &storage.AccountProperties{ - AllowSharedKeyAccess: ptr.To(true), + AllowSharedKeyAccess: to.Ptr(true), }, }, accountOptions: &AccountOptions{}, @@ -1302,18 +1301,18 @@ func TestIsAllowSharedKeyAccessEqual(t *testing.T) { AccountProperties: &storage.AccountProperties{}, }, accountOptions: &AccountOptions{ - AllowSharedKeyAccess: ptr.To(false), + AllowSharedKeyAccess: to.Ptr(false), }, expectedResult: false, }, { account: storage.Account{ AccountProperties: &storage.AccountProperties{ - AllowSharedKeyAccess: ptr.To(true), + AllowSharedKeyAccess: to.Ptr(true), }, }, accountOptions: &AccountOptions{ - AllowSharedKeyAccess: ptr.To(true), + AllowSharedKeyAccess: to.Ptr(true), }, expectedResult: true, }, @@ -1322,18 +1321,18 @@ func TestIsAllowSharedKeyAccessEqual(t *testing.T) { AccountProperties: &storage.AccountProperties{}, }, accountOptions: &AccountOptions{ - AllowSharedKeyAccess: ptr.To(true), + AllowSharedKeyAccess: to.Ptr(true), }, expectedResult: true, }, { account: storage.Account{ AccountProperties: &storage.AccountProperties{ - AllowSharedKeyAccess: ptr.To(true), + AllowSharedKeyAccess: to.Ptr(true), }, }, accountOptions: &AccountOptions{ - AllowSharedKeyAccess: ptr.To(false), + AllowSharedKeyAccess: to.Ptr(false), }, expectedResult: false, }, @@ -1355,7 +1354,7 @@ func TestIsRequireInfrastructureEncryptionEqual(t *testing.T) { account: storage.Account{ AccountProperties: &storage.AccountProperties{ Encryption: &storage.Encryption{ - RequireInfrastructureEncryption: ptr.To(true), + RequireInfrastructureEncryption: to.Ptr(true), }, }, }, @@ -1366,12 +1365,12 @@ func TestIsRequireInfrastructureEncryptionEqual(t *testing.T) { account: storage.Account{ AccountProperties: &storage.AccountProperties{ Encryption: &storage.Encryption{ - RequireInfrastructureEncryption: ptr.To(true), + RequireInfrastructureEncryption: to.Ptr(true), }, }, }, accountOptions: &AccountOptions{ - RequireInfrastructureEncryption: ptr.To(true), + RequireInfrastructureEncryption: to.Ptr(true), }, expectedResult: true, }, @@ -1379,12 +1378,12 @@ func TestIsRequireInfrastructureEncryptionEqual(t *testing.T) { account: storage.Account{ AccountProperties: &storage.AccountProperties{ Encryption: &storage.Encryption{ - RequireInfrastructureEncryption: ptr.To(false), + RequireInfrastructureEncryption: to.Ptr(false), }, }, }, accountOptions: &AccountOptions{ - RequireInfrastructureEncryption: ptr.To(false), + RequireInfrastructureEncryption: to.Ptr(false), }, expectedResult: true, }, @@ -1393,7 +1392,7 @@ func TestIsRequireInfrastructureEncryptionEqual(t *testing.T) { AccountProperties: &storage.AccountProperties{}, }, accountOptions: &AccountOptions{ - RequireInfrastructureEncryption: ptr.To(false), + RequireInfrastructureEncryption: to.Ptr(false), }, expectedResult: true, }, @@ -1401,12 +1400,12 @@ func TestIsRequireInfrastructureEncryptionEqual(t *testing.T) { account: storage.Account{ AccountProperties: &storage.AccountProperties{ Encryption: &storage.Encryption{ - RequireInfrastructureEncryption: ptr.To(true), + RequireInfrastructureEncryption: to.Ptr(true), }, }, }, accountOptions: &AccountOptions{ - RequireInfrastructureEncryption: ptr.To(false), + RequireInfrastructureEncryption: to.Ptr(false), }, expectedResult: false, }, @@ -1414,12 +1413,12 @@ func TestIsRequireInfrastructureEncryptionEqual(t *testing.T) { account: storage.Account{ AccountProperties: &storage.AccountProperties{ Encryption: &storage.Encryption{ - RequireInfrastructureEncryption: ptr.To(false), + RequireInfrastructureEncryption: to.Ptr(false), }, }, }, accountOptions: &AccountOptions{ - RequireInfrastructureEncryption: ptr.To(true), + RequireInfrastructureEncryption: to.Ptr(true), }, expectedResult: false, }, @@ -1428,7 +1427,7 @@ func TestIsRequireInfrastructureEncryptionEqual(t *testing.T) { AccountProperties: &storage.AccountProperties{}, }, accountOptions: &AccountOptions{ - RequireInfrastructureEncryption: ptr.To(true), + RequireInfrastructureEncryption: to.Ptr(true), }, expectedResult: false, }, @@ -1460,7 +1459,7 @@ func TestIsLargeFileSharesPropertyEqual(t *testing.T) { AccountProperties: &storage.AccountProperties{}, }, accountOptions: &AccountOptions{ - EnableLargeFileShare: ptr.To(false), + EnableLargeFileShare: to.Ptr(false), }, expectedResult: true, }, @@ -1471,7 +1470,7 @@ func TestIsLargeFileSharesPropertyEqual(t *testing.T) { }, }, accountOptions: &AccountOptions{ - EnableLargeFileShare: ptr.To(true), + EnableLargeFileShare: to.Ptr(true), }, expectedResult: true, }, @@ -1480,7 +1479,7 @@ func TestIsLargeFileSharesPropertyEqual(t *testing.T) { AccountProperties: &storage.AccountProperties{}, }, accountOptions: &AccountOptions{ - EnableLargeFileShare: ptr.To(true), + EnableLargeFileShare: to.Ptr(true), }, expectedResult: false, }, @@ -1491,7 +1490,7 @@ func TestIsLargeFileSharesPropertyEqual(t *testing.T) { }, }, accountOptions: &AccountOptions{ - EnableLargeFileShare: ptr.To(false), + EnableLargeFileShare: to.Ptr(false), }, expectedResult: false, }, @@ -1583,7 +1582,7 @@ func TestIsMultichannelEnabledEqual(t *testing.T) { multichannelEnabled := storage.FileServiceProperties{ FileServicePropertiesProperties: &storage.FileServicePropertiesProperties{ ProtocolSettings: &storage.ProtocolSettings{ - Smb: &storage.SmbSetting{Multichannel: &storage.Multichannel{Enabled: ptr.To(true)}}, + Smb: &storage.SmbSetting{Multichannel: &storage.Multichannel{Enabled: to.Ptr(true)}}, }, }, } @@ -1591,7 +1590,7 @@ func TestIsMultichannelEnabledEqual(t *testing.T) { multichannelDisabled := storage.FileServiceProperties{ FileServicePropertiesProperties: &storage.FileServicePropertiesProperties{ ProtocolSettings: &storage.ProtocolSettings{ - Smb: &storage.SmbSetting{Multichannel: &storage.Multichannel{Enabled: ptr.To(false)}}, + Smb: &storage.SmbSetting{Multichannel: &storage.Multichannel{Enabled: to.Ptr(false)}}, }, }, } @@ -1628,7 +1627,7 @@ func TestIsMultichannelEnabledEqual(t *testing.T) { AccountProperties: &storage.AccountProperties{}, }, accountOptions: &AccountOptions{ - IsMultichannelEnabled: ptr.To(false), + IsMultichannelEnabled: to.Ptr(false), }, expectedResult: false, }, @@ -1639,7 +1638,7 @@ func TestIsMultichannelEnabledEqual(t *testing.T) { AccountProperties: &storage.AccountProperties{}, }, accountOptions: &AccountOptions{ - IsMultichannelEnabled: ptr.To(false), + IsMultichannelEnabled: to.Ptr(false), }, serviceProperties: &multichannelEnabled, expectedResult: false, @@ -1651,7 +1650,7 @@ func TestIsMultichannelEnabledEqual(t *testing.T) { AccountProperties: &storage.AccountProperties{}, }, accountOptions: &AccountOptions{ - IsMultichannelEnabled: ptr.To(false), + IsMultichannelEnabled: to.Ptr(false), }, serviceProperties: &multichannelEnabled, servicePropertiesRetError: fmt.Errorf("GetServiceProperties return error"), @@ -1664,7 +1663,7 @@ func TestIsMultichannelEnabledEqual(t *testing.T) { AccountProperties: &storage.AccountProperties{}, }, accountOptions: &AccountOptions{ - IsMultichannelEnabled: ptr.To(true), + IsMultichannelEnabled: to.Ptr(true), }, serviceProperties: &multichannelDisabled, expectedResult: false, @@ -1676,7 +1675,7 @@ func TestIsMultichannelEnabledEqual(t *testing.T) { AccountProperties: &storage.AccountProperties{}, }, accountOptions: &AccountOptions{ - IsMultichannelEnabled: ptr.To(true), + IsMultichannelEnabled: to.Ptr(true), }, serviceProperties: &multichannelEnabled, expectedResult: true, @@ -1688,7 +1687,7 @@ func TestIsMultichannelEnabledEqual(t *testing.T) { AccountProperties: &storage.AccountProperties{}, }, accountOptions: &AccountOptions{ - IsMultichannelEnabled: ptr.To(false), + IsMultichannelEnabled: to.Ptr(false), }, serviceProperties: &multichannelDisabled, expectedResult: true, @@ -1700,7 +1699,7 @@ func TestIsMultichannelEnabledEqual(t *testing.T) { AccountProperties: &storage.AccountProperties{}, }, accountOptions: &AccountOptions{ - IsMultichannelEnabled: ptr.To(false), + IsMultichannelEnabled: to.Ptr(false), }, serviceProperties: &incompleteServiceProperties, expectedResult: true, @@ -1731,7 +1730,7 @@ func TestIsDisableFileServiceDeleteRetentionPolicyEqual(t *testing.T) { deleteRetentionPolicyEnabled := storage.FileServiceProperties{ FileServicePropertiesProperties: &storage.FileServicePropertiesProperties{ ShareDeleteRetentionPolicy: &storage.DeleteRetentionPolicy{ - Enabled: ptr.To(true), + Enabled: to.Ptr(true), }, }, } @@ -1739,7 +1738,7 @@ func TestIsDisableFileServiceDeleteRetentionPolicyEqual(t *testing.T) { deleteRetentionPolicyDisabled := storage.FileServiceProperties{ FileServicePropertiesProperties: &storage.FileServicePropertiesProperties{ ShareDeleteRetentionPolicy: &storage.DeleteRetentionPolicy{ - Enabled: ptr.To(false), + Enabled: to.Ptr(false), }, }, } @@ -1774,7 +1773,7 @@ func TestIsDisableFileServiceDeleteRetentionPolicyEqual(t *testing.T) { AccountProperties: &storage.AccountProperties{}, }, accountOptions: &AccountOptions{ - DisableFileServiceDeleteRetentionPolicy: ptr.To(false), + DisableFileServiceDeleteRetentionPolicy: to.Ptr(false), }, expectedResult: false, }, @@ -1785,7 +1784,7 @@ func TestIsDisableFileServiceDeleteRetentionPolicyEqual(t *testing.T) { AccountProperties: &storage.AccountProperties{}, }, accountOptions: &AccountOptions{ - DisableFileServiceDeleteRetentionPolicy: ptr.To(true), + DisableFileServiceDeleteRetentionPolicy: to.Ptr(true), }, serviceProperties: &deleteRetentionPolicyEnabled, expectedResult: false, @@ -1797,7 +1796,7 @@ func TestIsDisableFileServiceDeleteRetentionPolicyEqual(t *testing.T) { AccountProperties: &storage.AccountProperties{}, }, accountOptions: &AccountOptions{ - DisableFileServiceDeleteRetentionPolicy: ptr.To(false), + DisableFileServiceDeleteRetentionPolicy: to.Ptr(false), }, serviceProperties: &deleteRetentionPolicyEnabled, servicePropertiesRetError: fmt.Errorf("GetServiceProperties return error"), @@ -1810,7 +1809,7 @@ func TestIsDisableFileServiceDeleteRetentionPolicyEqual(t *testing.T) { AccountProperties: &storage.AccountProperties{}, }, accountOptions: &AccountOptions{ - DisableFileServiceDeleteRetentionPolicy: ptr.To(false), + DisableFileServiceDeleteRetentionPolicy: to.Ptr(false), }, serviceProperties: &deleteRetentionPolicyDisabled, expectedResult: false, @@ -1822,7 +1821,7 @@ func TestIsDisableFileServiceDeleteRetentionPolicyEqual(t *testing.T) { AccountProperties: &storage.AccountProperties{}, }, accountOptions: &AccountOptions{ - DisableFileServiceDeleteRetentionPolicy: ptr.To(true), + DisableFileServiceDeleteRetentionPolicy: to.Ptr(true), }, serviceProperties: &deleteRetentionPolicyDisabled, expectedResult: true, @@ -1834,7 +1833,7 @@ func TestIsDisableFileServiceDeleteRetentionPolicyEqual(t *testing.T) { AccountProperties: &storage.AccountProperties{}, }, accountOptions: &AccountOptions{ - DisableFileServiceDeleteRetentionPolicy: ptr.To(false), + DisableFileServiceDeleteRetentionPolicy: to.Ptr(false), }, serviceProperties: &deleteRetentionPolicyEnabled, expectedResult: true, @@ -1846,7 +1845,7 @@ func TestIsDisableFileServiceDeleteRetentionPolicyEqual(t *testing.T) { AccountProperties: &storage.AccountProperties{}, }, accountOptions: &AccountOptions{ - DisableFileServiceDeleteRetentionPolicy: ptr.To(false), + DisableFileServiceDeleteRetentionPolicy: to.Ptr(false), }, serviceProperties: &incompleteServiceProperties, expectedResult: true, @@ -1891,7 +1890,7 @@ func TestIsSoftDeleteBlobsEqual(t *testing.T) { property: storage.BlobServiceProperties{ BlobServicePropertiesProperties: &storage.BlobServicePropertiesProperties{ DeleteRetentionPolicy: &storage.DeleteRetentionPolicy{ - Enabled: ptr.To(false), + Enabled: to.Ptr(false), }, }, }, @@ -1907,8 +1906,8 @@ func TestIsSoftDeleteBlobsEqual(t *testing.T) { property: storage.BlobServiceProperties{ BlobServicePropertiesProperties: &storage.BlobServicePropertiesProperties{ DeleteRetentionPolicy: &storage.DeleteRetentionPolicy{ - Enabled: ptr.To(true), - Days: ptr.To(int32(7)), + Enabled: to.Ptr(true), + Days: to.Ptr(int32(7)), }, }, }, @@ -1922,8 +1921,8 @@ func TestIsSoftDeleteBlobsEqual(t *testing.T) { property: storage.BlobServiceProperties{ BlobServicePropertiesProperties: &storage.BlobServicePropertiesProperties{ DeleteRetentionPolicy: &storage.DeleteRetentionPolicy{ - Enabled: ptr.To(true), - Days: ptr.To(int32(7)), + Enabled: to.Ptr(true), + Days: to.Ptr(int32(7)), }, }, }, @@ -1971,7 +1970,7 @@ func Test_isSoftDeleteContainersEqual(t *testing.T) { property: storage.BlobServiceProperties{ BlobServicePropertiesProperties: &storage.BlobServicePropertiesProperties{ ContainerDeleteRetentionPolicy: &storage.DeleteRetentionPolicy{ - Enabled: ptr.To(false), + Enabled: to.Ptr(false), }, }, }, @@ -1987,8 +1986,8 @@ func Test_isSoftDeleteContainersEqual(t *testing.T) { property: storage.BlobServiceProperties{ BlobServicePropertiesProperties: &storage.BlobServicePropertiesProperties{ ContainerDeleteRetentionPolicy: &storage.DeleteRetentionPolicy{ - Enabled: ptr.To(true), - Days: ptr.To(int32(7)), + Enabled: to.Ptr(true), + Days: to.Ptr(int32(7)), }, }, }, @@ -2002,8 +2001,8 @@ func Test_isSoftDeleteContainersEqual(t *testing.T) { property: storage.BlobServiceProperties{ BlobServicePropertiesProperties: &storage.BlobServicePropertiesProperties{ ContainerDeleteRetentionPolicy: &storage.DeleteRetentionPolicy{ - Enabled: ptr.To(true), - Days: ptr.To(int32(7)), + Enabled: to.Ptr(true), + Days: to.Ptr(int32(7)), }, }, }, @@ -2040,7 +2039,7 @@ func Test_isEnableBlobVersioningEqual(t *testing.T) { BlobServicePropertiesProperties: &storage.BlobServicePropertiesProperties{}, }, accountOptions: &AccountOptions{ - EnableBlobVersioning: ptr.To(false), + EnableBlobVersioning: to.Ptr(false), }, }, want: true, @@ -2050,11 +2049,11 @@ func Test_isEnableBlobVersioningEqual(t *testing.T) { args: args{ property: storage.BlobServiceProperties{ BlobServicePropertiesProperties: &storage.BlobServicePropertiesProperties{ - IsVersioningEnabled: ptr.To(true), + IsVersioningEnabled: to.Ptr(true), }, }, accountOptions: &AccountOptions{ - EnableBlobVersioning: ptr.To(false), + EnableBlobVersioning: to.Ptr(false), }, }, }, @@ -2144,7 +2143,7 @@ func TestAreVNetRulesEqual(t *testing.T) { NetworkRuleSet: &storage.NetworkRuleSet{ VirtualNetworkRules: &[]storage.VirtualNetworkRule{ { - VirtualNetworkResourceID: ptr.To("id"), + VirtualNetworkResourceID: to.Ptr("id"), Action: storage.ActionAllow, State: "state", }, @@ -2166,11 +2165,11 @@ func TestAreVNetRulesEqual(t *testing.T) { NetworkRuleSet: &storage.NetworkRuleSet{ VirtualNetworkRules: &[]storage.VirtualNetworkRule{ { - VirtualNetworkResourceID: ptr.To("id1"), + VirtualNetworkResourceID: to.Ptr("id1"), Action: storage.ActionAllow, }, { - VirtualNetworkResourceID: ptr.To("id2"), + VirtualNetworkResourceID: to.Ptr("id2"), Action: storage.ActionAllow, }, }, @@ -2191,7 +2190,7 @@ func TestAreVNetRulesEqual(t *testing.T) { NetworkRuleSet: &storage.NetworkRuleSet{ VirtualNetworkRules: &[]storage.VirtualNetworkRule{ { - VirtualNetworkResourceID: ptr.To("id1"), + VirtualNetworkResourceID: to.Ptr("id1"), Action: storage.ActionAllow, State: "state", }, diff --git a/pkg/provider/azure_test.go b/pkg/provider/azure_test.go index 6e6d9c4a8d..476af9aa51 100644 --- a/pkg/provider/azure_test.go +++ b/pkg/provider/azure_test.go @@ -31,6 +31,7 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" + "github.com/samber/lo" "github.com/stretchr/testify/assert" "go.uber.org/mock/gomock" v1 "k8s.io/api/core/v1" @@ -41,7 +42,6 @@ import ( cloudprovider "k8s.io/cloud-provider" cloudproviderapi "k8s.io/cloud-provider/api" servicehelpers "k8s.io/cloud-provider/service/helpers" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/azclient" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/configloader" @@ -238,45 +238,45 @@ func setMockPublicIP(az *Cloud, mockPIPsClient *mockpublicipclient.MockInterface } expectedPIP := network.PublicIPAddress{ - Name: ptr.To("testCluster-aservicea"), + Name: to.Ptr("testCluster-aservicea"), Location: &az.Location, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAllocationMethod: network.Static, PublicIPAddressVersion: ipVer, - IPAddress: ptr.To(ipAddr1), + IPAddress: to.Ptr(ipAddr1), }, Tags: map[string]*string{ - consts.ServiceTagKey: ptr.To("default/servicea"), - consts.ClusterNameKey: ptr.To(testClusterName), + consts.ServiceTagKey: to.Ptr("default/servicea"), + consts.ClusterNameKey: to.Ptr(testClusterName), }, Sku: &network.PublicIPAddressSku{ Name: network.PublicIPAddressSkuNameStandard, }, - ID: ptr.To("testCluster-aservice1"), + ID: to.Ptr("testCluster-aservice1"), } a := 'a' var expectedPIPs []network.PublicIPAddress for i := 1; i <= serviceCount; i++ { - expectedPIP.Name = ptr.To(fmt.Sprintf("testCluster-aservice%d%s", i, suffix)) - expectedPIP.ID = ptr.To(fmt.Sprintf("testCluster-aservice%d%s", i, suffix)) + expectedPIP.Name = to.Ptr(fmt.Sprintf("testCluster-aservice%d%s", i, suffix)) + expectedPIP.ID = to.Ptr(fmt.Sprintf("testCluster-aservice%d%s", i, suffix)) expectedPIP.PublicIPAddressPropertiesFormat = &network.PublicIPAddressPropertiesFormat{ PublicIPAllocationMethod: network.Static, PublicIPAddressVersion: ipVer, - IPAddress: ptr.To(ipAddr1), + IPAddress: to.Ptr(ipAddr1), } - expectedPIP.Tags[consts.ServiceTagKey] = ptr.To(fmt.Sprintf("default/service%d", i)) + expectedPIP.Tags[consts.ServiceTagKey] = to.Ptr(fmt.Sprintf("default/service%d", i)) mockPIPsClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, fmt.Sprintf("testCluster-aservice%d%s", i, suffix), gomock.Any()).Return(expectedPIP, nil).AnyTimes() mockPIPsClient.EXPECT().Delete(gomock.Any(), az.ResourceGroup, fmt.Sprintf("testCluster-aservice%d%s", i, suffix)).Return(nil).AnyTimes() expectedPIPs = append(expectedPIPs, expectedPIP) - expectedPIP.Name = ptr.To(fmt.Sprintf("testCluster-aservice%c%s", a, suffix)) - expectedPIP.ID = ptr.To(fmt.Sprintf("testCluster-aservice%c%s", a, suffix)) + expectedPIP.Name = to.Ptr(fmt.Sprintf("testCluster-aservice%c%s", a, suffix)) + expectedPIP.ID = to.Ptr(fmt.Sprintf("testCluster-aservice%c%s", a, suffix)) expectedPIP.PublicIPAddressPropertiesFormat = &network.PublicIPAddressPropertiesFormat{ PublicIPAllocationMethod: network.Static, PublicIPAddressVersion: ipVer, - IPAddress: ptr.To(ipAddra), + IPAddress: to.Ptr(ipAddra), } - expectedPIP.Tags[consts.ServiceTagKey] = ptr.To(fmt.Sprintf("default/service%c", a)) + expectedPIP.Tags[consts.ServiceTagKey] = to.Ptr(fmt.Sprintf("default/service%c", a)) mockPIPsClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, fmt.Sprintf("testCluster-aservice%c%s", a, suffix), gomock.Any()).Return(expectedPIP, nil).AnyTimes() mockPIPsClient.EXPECT().Delete(gomock.Any(), az.ResourceGroup, fmt.Sprintf("testCluster-aservice%c%s", a, suffix)).Return(nil).AnyTimes() expectedPIPs = append(expectedPIPs, expectedPIP) @@ -314,10 +314,10 @@ func setMockLBsDualStack(az *Cloud, ctrl *gomock.Controller, expectedLBs *[]netw LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ BackendAddressPools: &[]network.BackendAddressPool{ { - Name: ptr.To("testCluster"), + Name: to.Ptr("testCluster"), }, { - Name: ptr.To("testCluster-IPv6"), + Name: to.Ptr("testCluster-IPv6"), }, }, }, @@ -325,35 +325,35 @@ func setMockLBsDualStack(az *Cloud, ctrl *gomock.Controller, expectedLBs *[]netw lb.Name = &expectedLBName lb.LoadBalancingRules = &[]network.LoadBalancingRule{ { - Name: ptr.To(fmt.Sprintf("a%s%d-TCP-8081", fullServiceName, serviceIndex)), + Name: to.Ptr(fmt.Sprintf("a%s%d-TCP-8081", fullServiceName, serviceIndex)), }, { - Name: ptr.To(fmt.Sprintf("a%s%d-TCP-8081-IPv6", fullServiceName, serviceIndex)), + Name: to.Ptr(fmt.Sprintf("a%s%d-TCP-8081-IPv6", fullServiceName, serviceIndex)), }, } fips := []network.FrontendIPConfiguration{ { - Name: ptr.To(fmt.Sprintf("a%s%d", fullServiceName, serviceIndex)), - ID: ptr.To("fip"), + Name: to.Ptr(fmt.Sprintf("a%s%d", fullServiceName, serviceIndex)), + ID: to.Ptr("fip"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PrivateIPAllocationMethod: "Dynamic", PrivateIPAddressVersion: network.IPv4, - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To(fmt.Sprintf("testCluster-a%s%d", fullServiceName, serviceIndex))}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr(fmt.Sprintf("testCluster-a%s%d", fullServiceName, serviceIndex))}, }, }, { - Name: ptr.To(fmt.Sprintf("a%s%d-IPv6", fullServiceName, serviceIndex)), - ID: ptr.To("fip-IPv6"), + Name: to.Ptr(fmt.Sprintf("a%s%d-IPv6", fullServiceName, serviceIndex)), + ID: to.Ptr("fip-IPv6"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PrivateIPAllocationMethod: "Dynamic", PrivateIPAddressVersion: network.IPv6, - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To(fmt.Sprintf("testCluster-a%s%d-IPv6", fullServiceName, serviceIndex))}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr(fmt.Sprintf("testCluster-a%s%d-IPv6", fullServiceName, serviceIndex))}, }, }, } if isInternal { - fips[0].Subnet = &network.Subnet{Name: ptr.To("subnet")} - fips[1].Subnet = &network.Subnet{Name: ptr.To("subnet")} + fips[0].Subnet = &network.Subnet{Name: to.Ptr("subnet")} + fips[1].Subnet = &network.Subnet{Name: to.Ptr("subnet")} } lb.FrontendIPConfigurations = &fips @@ -361,36 +361,36 @@ func setMockLBsDualStack(az *Cloud, ctrl *gomock.Controller, expectedLBs *[]netw } else { lbRules := []network.LoadBalancingRule{ { - Name: ptr.To(fmt.Sprintf("a%s%d-TCP-8081", fullServiceName, serviceIndex)), + Name: to.Ptr(fmt.Sprintf("a%s%d-TCP-8081", fullServiceName, serviceIndex)), }, { - Name: ptr.To(fmt.Sprintf("a%s%d-TCP-8081-IPv6", fullServiceName, serviceIndex)), + Name: to.Ptr(fmt.Sprintf("a%s%d-TCP-8081-IPv6", fullServiceName, serviceIndex)), }, } *(*expectedLBs)[lbIndex].LoadBalancingRules = append(*(*expectedLBs)[lbIndex].LoadBalancingRules, lbRules...) fips := []network.FrontendIPConfiguration{ { - Name: ptr.To(fmt.Sprintf("a%s%d", fullServiceName, serviceIndex)), - ID: ptr.To("fip"), + Name: to.Ptr(fmt.Sprintf("a%s%d", fullServiceName, serviceIndex)), + ID: to.Ptr("fip"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PrivateIPAllocationMethod: "Dynamic", PrivateIPAddressVersion: network.IPv4, - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To(fmt.Sprintf("testCluster-a%s%d", fullServiceName, serviceIndex))}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr(fmt.Sprintf("testCluster-a%s%d", fullServiceName, serviceIndex))}, }, }, { - Name: ptr.To(fmt.Sprintf("a%s%d-IPv6", fullServiceName, serviceIndex)), - ID: ptr.To("fip-IPv6"), + Name: to.Ptr(fmt.Sprintf("a%s%d-IPv6", fullServiceName, serviceIndex)), + ID: to.Ptr("fip-IPv6"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PrivateIPAllocationMethod: "Dynamic", PrivateIPAddressVersion: network.IPv6, - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To(fmt.Sprintf("testCluster-a%s%d-IPv6", fullServiceName, serviceIndex))}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr(fmt.Sprintf("testCluster-a%s%d-IPv6", fullServiceName, serviceIndex))}, }, }, } if isInternal { for _, fip := range fips { - fip.Subnet = &network.Subnet{Name: ptr.To("subnet")} + fip.Subnet = &network.Subnet{Name: to.Ptr("subnet")} } } *(*expectedLBs)[lbIndex].FrontendIPConfigurations = append(*(*expectedLBs)[lbIndex].FrontendIPConfigurations, fips...) @@ -430,7 +430,7 @@ func setMockLBs(az *Cloud, ctrl *gomock.Controller, expectedLBs *[]network.LoadB LoadBalancerPropertiesFormat: &network.LoadBalancerPropertiesFormat{ BackendAddressPools: &[]network.BackendAddressPool{ { - Name: ptr.To("testCluster"), + Name: to.Ptr("testCluster"), }, }, }, @@ -438,41 +438,41 @@ func setMockLBs(az *Cloud, ctrl *gomock.Controller, expectedLBs *[]network.LoadB lb.Name = &expectedLBName lb.LoadBalancingRules = &[]network.LoadBalancingRule{ { - Name: ptr.To(fmt.Sprintf("a%s%d-TCP-8081", fullServiceName, serviceIndex)), + Name: to.Ptr(fmt.Sprintf("a%s%d-TCP-8081", fullServiceName, serviceIndex)), }, } fips := []network.FrontendIPConfiguration{ { - Name: ptr.To(fmt.Sprintf("a%s%d", fullServiceName, serviceIndex)), - ID: ptr.To("fip"), + Name: to.Ptr(fmt.Sprintf("a%s%d", fullServiceName, serviceIndex)), + ID: to.Ptr("fip"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PrivateIPAllocationMethod: "Dynamic", - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To(fmt.Sprintf("testCluster-a%s%d", fullServiceName, serviceIndex))}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr(fmt.Sprintf("testCluster-a%s%d", fullServiceName, serviceIndex))}, PrivateIPAddressVersion: network.IPv4, }, }, } if isInternal { - fips[0].Subnet = &network.Subnet{Name: ptr.To("subnet")} + fips[0].Subnet = &network.Subnet{Name: to.Ptr("subnet")} } lb.FrontendIPConfigurations = &fips *expectedLBs = append(*expectedLBs, lb) } else { *(*expectedLBs)[lbIndex].LoadBalancingRules = append(*(*expectedLBs)[lbIndex].LoadBalancingRules, network.LoadBalancingRule{ - Name: ptr.To(fmt.Sprintf("a%s%d-TCP-8081", fullServiceName, serviceIndex)), + Name: to.Ptr(fmt.Sprintf("a%s%d-TCP-8081", fullServiceName, serviceIndex)), }) fip := network.FrontendIPConfiguration{ - Name: ptr.To(fmt.Sprintf("a%s%d", fullServiceName, serviceIndex)), - ID: ptr.To("fip"), + Name: to.Ptr(fmt.Sprintf("a%s%d", fullServiceName, serviceIndex)), + ID: to.Ptr("fip"), FrontendIPConfigurationPropertiesFormat: &network.FrontendIPConfigurationPropertiesFormat{ PrivateIPAllocationMethod: "Dynamic", - PublicIPAddress: &network.PublicIPAddress{ID: ptr.To(fmt.Sprintf("testCluster-a%s%d", fullServiceName, serviceIndex))}, + PublicIPAddress: &network.PublicIPAddress{ID: to.Ptr(fmt.Sprintf("testCluster-a%s%d", fullServiceName, serviceIndex))}, PrivateIPAddressVersion: network.IPv4, }, } if isInternal { - fip.Subnet = &network.Subnet{Name: ptr.To("subnet")} + fip.Subnet = &network.Subnet{Name: to.Ptr("subnet")} } *(*expectedLBs)[lbIndex].FrontendIPConfigurations = append(*(*expectedLBs)[lbIndex].FrontendIPConfigurations, fip) } @@ -1206,20 +1206,20 @@ func TestServiceDefaultsToNoSessionPersistence(t *testing.T) { setMockLBs(az, ctrl, &expectedLBs, "service-sa-omitted", 1, 1, false) expectedPIP := network.PublicIPAddress{ - Name: ptr.To("testCluster-aservicesaomitted1"), + Name: to.Ptr("testCluster-aservicesaomitted1"), Location: &az.Location, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAllocationMethod: network.Static, PublicIPAddressVersion: network.IPv4, }, Tags: map[string]*string{ - consts.ServiceTagKey: ptr.To("aservicesaomitted1"), - consts.ClusterNameKey: ptr.To(testClusterName), + consts.ServiceTagKey: to.Ptr("aservicesaomitted1"), + consts.ClusterNameKey: to.Ptr(testClusterName), }, Sku: &network.PublicIPAddressSku{ Name: network.PublicIPAddressSkuNameStandard, }, - ID: ptr.To("testCluster-aservicesaomitted1"), + ID: to.Ptr("testCluster-aservicesaomitted1"), } mockPIPsClient := mockpublicipclient.NewMockInterface(ctrl) @@ -1262,20 +1262,20 @@ func TestServiceRespectsNoSessionAffinity(t *testing.T) { setMockLBs(az, ctrl, &expectedLBs, "service-sa-none", 1, 1, false) expectedPIP := network.PublicIPAddress{ - Name: ptr.To("testCluster-aservicesanone"), + Name: to.Ptr("testCluster-aservicesanone"), Location: &az.Location, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAllocationMethod: network.Static, PublicIPAddressVersion: network.IPv4, }, Tags: map[string]*string{ - consts.ServiceTagKey: ptr.To("aservicesanone"), - consts.ClusterNameKey: ptr.To(testClusterName), + consts.ServiceTagKey: to.Ptr("aservicesanone"), + consts.ClusterNameKey: to.Ptr(testClusterName), }, Sku: &network.PublicIPAddressSku{ Name: network.PublicIPAddressSkuNameStandard, }, - ID: ptr.To("testCluster-aservicesanone"), + ID: to.Ptr("testCluster-aservicesanone"), } mockPIPsClient := mockpublicipclient.NewMockInterface(ctrl) @@ -1325,20 +1325,20 @@ func TestServiceRespectsClientIPSessionAffinity(t *testing.T) { setMockLBs(az, ctrl, &expectedLBs, "service-sa-clientip", 1, 1, false) expectedPIP := network.PublicIPAddress{ - Name: ptr.To("testCluster-aservicesaclientip"), + Name: to.Ptr("testCluster-aservicesaclientip"), Location: &az.Location, PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ PublicIPAllocationMethod: network.Static, PublicIPAddressVersion: network.IPv4, }, Tags: map[string]*string{ - consts.ServiceTagKey: ptr.To("aservicesaclientip"), - consts.ClusterNameKey: ptr.To(testClusterName), + consts.ServiceTagKey: to.Ptr("aservicesaclientip"), + consts.ClusterNameKey: to.Ptr(testClusterName), }, Sku: &network.PublicIPAddressSku{ Name: network.PublicIPAddressSkuNameStandard, }, - ID: ptr.To("testCluster-aservicesaclientip"), + ID: to.Ptr("testCluster-aservicesaclientip"), } mockPIPsClient := mockpublicipclient.NewMockInterface(ctrl) @@ -1395,12 +1395,12 @@ func TestReconcilePublicIPsWithNewService(t *testing.T) { pipsNames1, pipsNames2 := []string{}, []string{} pipsAddrs1, pipsAddrs2 := []string{}, []string{} for _, pip := range pips { - pipsNames1 = append(pipsNames1, ptr.Deref(pip.Name, "")) - pipsAddrs1 = append(pipsAddrs1, ptr.Deref(pip.PublicIPAddressPropertiesFormat.IPAddress, "")) + pipsNames1 = append(pipsNames1, lo.FromPtrOr(pip.Name, "")) + pipsAddrs1 = append(pipsAddrs1, lo.FromPtrOr(pip.PublicIPAddressPropertiesFormat.IPAddress, "")) } for _, pip := range pips2 { - pipsNames2 = append(pipsNames2, ptr.Deref(pip.Name, "")) - pipsAddrs2 = append(pipsAddrs2, ptr.Deref(pip.PublicIPAddressPropertiesFormat.IPAddress, "")) + pipsNames2 = append(pipsNames2, lo.FromPtrOr(pip.Name, "")) + pipsAddrs2 = append(pipsAddrs2, lo.FromPtrOr(pip.PublicIPAddressPropertiesFormat.IPAddress, "")) } assert.Truef(t, compareStrings(pipsNames1, pipsNames2) && compareStrings(pipsAddrs1, pipsAddrs2), "We should get the exact same public ip resource after a second reconcile") @@ -1697,10 +1697,10 @@ func getTestSecurityGroupCommon(az *Cloud, v4Enabled, v6Enabled bool, services . getRule := func(svc *v1.Service, port v1.ServicePort, src string, isIPv6 bool) *armnetwork.SecurityRule { ruleName := az.getSecurityRuleName(svc, port, src, isIPv6) return &armnetwork.SecurityRule{ - Name: ptr.To(ruleName), + Name: to.Ptr(ruleName), Properties: &armnetwork.SecurityRulePropertiesFormat{ - SourceAddressPrefix: ptr.To(src), - DestinationPortRange: ptr.To(fmt.Sprintf("%d", port.Port)), + SourceAddressPrefix: to.Ptr(src), + DestinationPortRange: to.Ptr(fmt.Sprintf("%d", port.Port)), }, } } @@ -1721,7 +1721,7 @@ func getTestSecurityGroupCommon(az *Cloud, v4Enabled, v6Enabled bool, services . sg := armnetwork.SecurityGroup{ Name: &az.SecurityGroupName, - Etag: ptr.To("0000000-0000-0000-0000-000000000000"), + Etag: to.Ptr("0000000-0000-0000-0000-000000000000"), Properties: &armnetwork.SecurityGroupPropertiesFormat{ SecurityRules: rules, }, @@ -1764,13 +1764,13 @@ func validateLoadBalancer(t *testing.T, loadBalancer *network.LoadBalancer, serv } expectedFrontendIP := ExpectedFrontendIPInfo{ Name: az.getDefaultFrontendIPConfigName(&services[i]), - Subnet: ptr.To(expectedSubnetName), + Subnet: to.Ptr(expectedSubnetName), } expectedFrontendIPs = append(expectedFrontendIPs, expectedFrontendIP) if svcIPFamilyCount == 2 { expectedFrontendIP := ExpectedFrontendIPInfo{ Name: az.getDefaultFrontendIPConfigName(&services[i]) + "-" + consts.IPVersionIPv6String, - Subnet: ptr.To(expectedSubnetName), + Subnet: to.Ptr(expectedSubnetName), } expectedFrontendIPs = append(expectedFrontendIPs, expectedFrontendIP) } @@ -1851,7 +1851,7 @@ func validateLoadBalancer(t *testing.T, loadBalancer *network.LoadBalancer, serv frontendIPs := *loadBalancer.FrontendIPConfigurations for _, expectedFrontendIP := range expectedFrontendIPs { if !expectedFrontendIP.existsIn(frontendIPs) { - t.Errorf("Expected the loadbalancer to have frontend IP %s/%s. Found %s", expectedFrontendIP.Name, ptr.Deref(expectedFrontendIP.Subnet, ""), describeFIPs(frontendIPs)) + t.Errorf("Expected the loadbalancer to have frontend IP %s/%s. Found %s", expectedFrontendIP.Name, lo.FromPtrOr(expectedFrontendIP.Subnet, ""), describeFIPs(frontendIPs)) } } @@ -1872,7 +1872,7 @@ type ExpectedFrontendIPInfo struct { } func (expected ExpectedFrontendIPInfo) matches(frontendIP network.FrontendIPConfiguration) bool { - return strings.EqualFold(expected.Name, ptr.Deref(frontendIP.Name, "")) && strings.EqualFold(ptr.Deref(expected.Subnet, ""), ptr.Deref(subnetName(frontendIP), "")) + return strings.EqualFold(expected.Name, lo.FromPtrOr(frontendIP.Name, "")) && strings.EqualFold(lo.FromPtrOr(expected.Subnet, ""), lo.FromPtrOr(subnetName(frontendIP), "")) } func (expected ExpectedFrontendIPInfo) existsIn(frontendIPs []network.FrontendIPConfiguration) bool { @@ -1896,9 +1896,9 @@ func describeFIPs(frontendIPs []network.FrontendIPConfiguration) string { for _, actualFIP := range frontendIPs { actualSubnetName := "" if actualFIP.Subnet != nil { - actualSubnetName = ptr.Deref(actualFIP.Subnet.Name, "") + actualSubnetName = lo.FromPtrOr(actualFIP.Subnet.Name, "") } - actualFIPText := fmt.Sprintf("%s/%s ", ptr.Deref(actualFIP.Name, ""), actualSubnetName) + actualFIPText := fmt.Sprintf("%s/%s ", lo.FromPtrOr(actualFIP.Name, ""), actualSubnetName) description = description + actualFIPText } return description @@ -1929,10 +1929,10 @@ func validatePublicIP(t *testing.T, publicIP *network.PublicIPAddress, service * } serviceName := getServiceName(service) - assert.Equalf(t, serviceName, ptr.Deref(publicIP.Tags[consts.ServiceTagKey], ""), + assert.Equalf(t, serviceName, lo.FromPtrOr(publicIP.Tags[consts.ServiceTagKey], ""), "Expected publicIP resource has matching tags[%s]", consts.ServiceTagKey) assert.NotNilf(t, publicIP.Tags[consts.ClusterNameKey], "Expected publicIP resource does not have tags[%s]", consts.ClusterNameKey) - assert.Equalf(t, testClusterName, ptr.Deref(publicIP.Tags[consts.ClusterNameKey], ""), + assert.Equalf(t, testClusterName, lo.FromPtrOr(publicIP.Tags[consts.ClusterNameKey], ""), "Expected publicIP resource has matching tags[%s]", consts.ClusterNameKey) // We cannot use Service LoadBalancerIP to compare with @@ -1945,14 +1945,14 @@ func TestGetNextAvailablePriority(t *testing.T) { for i := int32(consts.LoadBalancerMinimumPriority); i < consts.LoadBalancerMinimumPriority+50; i++ { rules50 = append(rules50, &armnetwork.SecurityRule{ Properties: &armnetwork.SecurityRulePropertiesFormat{ - Priority: ptr.To(i), + Priority: to.Ptr(i), }, }) } for i := int32(consts.LoadBalancerMinimumPriority); i < consts.LoadBalancerMaximumPriority; i++ { rulesTooMany = append(rulesTooMany, &armnetwork.SecurityRule{ Properties: &armnetwork.SecurityRulePropertiesFormat{ - Priority: ptr.To(i), + Priority: to.Ptr(i), }, }) } diff --git a/pkg/provider/azure_utils.go b/pkg/provider/azure_utils.go index 4088ec6ef0..c0d3cab471 100644 --- a/pkg/provider/azure_utils.go +++ b/pkg/provider/azure_utils.go @@ -28,11 +28,10 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - + "github.com/samber/lo" v1 "k8s.io/api/core/v1" "k8s.io/klog/v2" utilnet "k8s.io/utils/net" - "k8s.io/utils/ptr" azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" @@ -90,7 +89,7 @@ func parseTags(tags string, tagsMap map[string]string) map[string]*string { klog.Warning("parseTags: empty key, ignoring this key-value pair") continue } - formatted[k] = ptr.To(v) + formatted[k] = lo.ToPtr(v) } } @@ -106,7 +105,7 @@ func parseTags(tags string, tagsMap map[string]string) map[string]*string { klog.V(4).Infof("parseTags: found identical keys: %s from tags and %s from tagsMap (case-insensitive), %s will replace %s", k, key, key, k) delete(formatted, k) } - formatted[key] = ptr.To(value) + formatted[key] = lo.ToPtr(value) } } @@ -134,7 +133,7 @@ func (az *Cloud) reconcileTags(currentTagsOnResource, newTags map[string]*string } for _, systemTag := range systemTags { - systemTagsMap[systemTag] = ptr.To("") + systemTagsMap[systemTag] = lo.ToPtr("") } } @@ -145,7 +144,7 @@ func (az *Cloud) reconcileTags(currentTagsOnResource, newTags map[string]*string if !found { currentTagsOnResource[k] = v changed = true - } else if !strings.EqualFold(ptr.Deref(v, ""), ptr.Deref(currentTagsOnResource[key], "")) { + } else if !strings.EqualFold(lo.FromPtrOr(v, ""), lo.FromPtrOr(currentTagsOnResource[key], "")) { currentTagsOnResource[key] = v changed = true } @@ -156,7 +155,7 @@ func (az *Cloud) reconcileTags(currentTagsOnResource, newTags map[string]*string for k := range currentTagsOnResource { if _, ok := newTags[k]; !ok { if found, _ := findKeyInMapCaseInsensitive(systemTagsMap, k); !found { - klog.V(2).Infof("reconcileTags: delete tag %s: %s", k, ptr.Deref(currentTagsOnResource[k], "")) + klog.V(2).Infof("reconcileTags: delete tag %s: %s", k, lo.FromPtrOr(currentTagsOnResource[k], "")) delete(currentTagsOnResource, k) changed = true } @@ -226,11 +225,11 @@ func sameContentInSlices(s1 []string, s2 []string) bool { func removeDuplicatedSecurityRules(rules []*armnetwork.SecurityRule) []*armnetwork.SecurityRule { ruleNames := make(map[string]bool) for i := len(rules) - 1; i >= 0; i-- { - if _, ok := ruleNames[ptr.Deref(rules[i].Name, "")]; ok { - klog.Warningf("Found duplicated rule %s, will be removed.", ptr.Deref(rules[i].Name, "")) + if _, ok := ruleNames[lo.FromPtrOr(rules[i].Name, "")]; ok { + klog.Warningf("Found duplicated rule %s, will be removed.", lo.FromPtrOr(rules[i].Name, "")) rules = append(rules[:i], rules[i+1:]...) } - ruleNames[ptr.Deref(rules[i].Name, "")] = true + ruleNames[lo.FromPtrOr(rules[i].Name, "")] = true } return rules } @@ -408,7 +407,7 @@ func (az *Cloud) isFIPIPv6(service *v1.Service, fip *network.FrontendIPConfigura } return service.Spec.IPFamilies[0] == v1.IPv6Protocol, nil } - return managedResourceHasIPv6Suffix(ptr.Deref(fip.Name, "")), nil + return managedResourceHasIPv6Suffix(lo.FromPtrOr(fip.Name, "")), nil } // getResourceIDPrefix returns a substring from the provided one between beginning and the last "/". @@ -447,7 +446,7 @@ func countIPsOnBackendPool(backendPool network.BackendAddressPool) int { var ipsCount int for _, loadBalancerBackendAddress := range *backendPool.LoadBalancerBackendAddresses { if loadBalancerBackendAddress.LoadBalancerBackendAddressPropertiesFormat != nil && - ptr.Deref(loadBalancerBackendAddress.IPAddress, "") != "" { + lo.FromPtrOr(loadBalancerBackendAddress.IPAddress, "") != "" { ipsCount++ } } diff --git a/pkg/provider/azure_utils_test.go b/pkg/provider/azure_utils_test.go index cf01c643ef..9e01fe0b3d 100644 --- a/pkg/provider/azure_utils_test.go +++ b/pkg/provider/azure_utils_test.go @@ -22,17 +22,16 @@ import ( "sync" "testing" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" "github.com/stretchr/testify/assert" - "go.uber.org/mock/gomock" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/utils/ptr" azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" @@ -47,75 +46,75 @@ func TestReconcileTags(t *testing.T) { { description: "reconcileTags should add missing tags and update existing tags", currentTagsOnResource: map[string]*string{ - "a": ptr.To("b"), + "a": to.Ptr("b"), }, newTags: map[string]*string{ - "a": ptr.To("c"), - "b": ptr.To("d"), + "a": to.Ptr("c"), + "b": to.Ptr("d"), }, expectedTags: map[string]*string{ - "a": ptr.To("c"), - "b": ptr.To("d"), + "a": to.Ptr("c"), + "b": to.Ptr("d"), }, expectedChanged: true, }, { description: "reconcileTags should remove the tags that are not included in systemTags", currentTagsOnResource: map[string]*string{ - "a": ptr.To("b"), - "c": ptr.To("d"), + "a": to.Ptr("b"), + "c": to.Ptr("d"), }, newTags: map[string]*string{ - "a": ptr.To("c"), + "a": to.Ptr("c"), }, systemTags: "a, b", expectedTags: map[string]*string{ - "a": ptr.To("c"), + "a": to.Ptr("c"), }, expectedChanged: true, }, { description: "reconcileTags should ignore the case of keys when comparing", currentTagsOnResource: map[string]*string{ - "A": ptr.To("b"), - "c": ptr.To("d"), + "A": to.Ptr("b"), + "c": to.Ptr("d"), }, newTags: map[string]*string{ - "a": ptr.To("b"), - "C": ptr.To("d"), + "a": to.Ptr("b"), + "C": to.Ptr("d"), }, expectedTags: map[string]*string{ - "A": ptr.To("b"), - "c": ptr.To("d"), + "A": to.Ptr("b"), + "c": to.Ptr("d"), }, }, { description: "reconcileTags should ignore the case of values when comparing", currentTagsOnResource: map[string]*string{ - "A": ptr.To("b"), - "c": ptr.To("d"), + "A": to.Ptr("b"), + "c": to.Ptr("d"), }, newTags: map[string]*string{ - "a": ptr.To("B"), - "C": ptr.To("D"), + "a": to.Ptr("B"), + "C": to.Ptr("D"), }, expectedTags: map[string]*string{ - "A": ptr.To("b"), - "c": ptr.To("d"), + "A": to.Ptr("b"), + "c": to.Ptr("d"), }, }, { description: "reconcileTags should ignore the case of keys when checking systemTags", currentTagsOnResource: map[string]*string{ - "a": ptr.To("b"), - "c": ptr.To("d"), + "a": to.Ptr("b"), + "c": to.Ptr("d"), }, newTags: map[string]*string{ - "a": ptr.To("c"), + "a": to.Ptr("c"), }, systemTags: "A, b", expectedTags: map[string]*string{ - "a": ptr.To("c"), + "a": to.Ptr("c"), }, expectedChanged: true, }, @@ -242,18 +241,18 @@ func TestRemoveDuplicatedSecurityRules(t *testing.T) { description: "no duplicated rules", rules: []*armnetwork.SecurityRule{ { - Name: ptr.To("rule1"), + Name: to.Ptr("rule1"), }, { - Name: ptr.To("rule2"), + Name: to.Ptr("rule2"), }, }, expected: []*armnetwork.SecurityRule{ { - Name: ptr.To("rule1"), + Name: to.Ptr("rule1"), }, { - Name: ptr.To("rule2"), + Name: to.Ptr("rule2"), }, }, }, @@ -261,21 +260,21 @@ func TestRemoveDuplicatedSecurityRules(t *testing.T) { description: "duplicated rules", rules: []*armnetwork.SecurityRule{ { - Name: ptr.To("rule1"), + Name: to.Ptr("rule1"), }, { - Name: ptr.To("rule2"), + Name: to.Ptr("rule2"), }, { - Name: ptr.To("rule1"), + Name: to.Ptr("rule1"), }, }, expected: []*armnetwork.SecurityRule{ { - Name: ptr.To("rule2"), + Name: to.Ptr("rule2"), }, { - Name: ptr.To("rule1"), + Name: to.Ptr("rule1"), }, }, }, @@ -795,7 +794,7 @@ func TestIsFIPIPv6(t *testing.T) { }, }, fip: &network.FrontendIPConfiguration{ - Name: ptr.To("fip"), + Name: to.Ptr("fip"), }, expectedIsIPv6: false, }, @@ -807,7 +806,7 @@ func TestIsFIPIPv6(t *testing.T) { }, }, fip: &network.FrontendIPConfiguration{ - Name: ptr.To("fip-IPv6"), + Name: to.Ptr("fip-IPv6"), }, expectedIsIPv6: true, }, @@ -858,21 +857,21 @@ func TestIsInternalLoadBalancer(t *testing.T) { { name: "internal load balancer", lb: network.LoadBalancer{ - Name: ptr.To("test-internal"), + Name: to.Ptr("test-internal"), }, expected: true, }, { name: "internal load balancer", lb: network.LoadBalancer{ - Name: ptr.To("TEST-INTERNAL"), + Name: to.Ptr("TEST-INTERNAL"), }, expected: true, }, { name: "not internal load balancer", lb: network.LoadBalancer{ - Name: ptr.To("test"), + Name: to.Ptr("test"), }, expected: false, }, @@ -902,13 +901,13 @@ func TestToArmcomputeDisk(t *testing.T) { args: args{ disks: []compute.DataDisk{ { - Name: ptr.To("disk1"), + Name: to.Ptr("disk1"), }, }, }, want: []*armcompute.DataDisk{ { - Name: ptr.To("disk1"), + Name: to.Ptr("disk1"), }, }, wantErr: false, diff --git a/pkg/provider/azure_vmsets_repo.go b/pkg/provider/azure_vmsets_repo.go index 00c13e6a66..75edf40cc5 100644 --- a/pkg/provider/azure_vmsets_repo.go +++ b/pkg/provider/azure_vmsets_repo.go @@ -23,11 +23,11 @@ import ( "time" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" + "github.com/samber/lo" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/wait" cloudprovider "k8s.io/cloud-provider" "k8s.io/klog/v2" - "k8s.io/utils/ptr" azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" @@ -137,7 +137,7 @@ func (az *Cloud) newVMCache() (azcache.Resource, error) { } if vm.VirtualMachineProperties != nil && - strings.EqualFold(ptr.Deref(vm.VirtualMachineProperties.ProvisioningState, ""), string(consts.ProvisioningStateDeleting)) { + strings.EqualFold(lo.FromPtrOr(vm.VirtualMachineProperties.ProvisioningState, ""), string(consts.ProvisioningStateDeleting)) { klog.V(2).Infof("Virtual machine %q is under deleting", key) return nil, nil } diff --git a/pkg/provider/azure_vmss.go b/pkg/provider/azure_vmss.go index 335cccf713..3d2149c75e 100644 --- a/pkg/provider/azure_vmss.go +++ b/pkg/provider/azure_vmss.go @@ -26,15 +26,15 @@ import ( "sync" "sync/atomic" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - + "github.com/samber/lo" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/types" utilerrors "k8s.io/apimachinery/pkg/util/errors" cloudprovider "k8s.io/cloud-provider" "k8s.io/klog/v2" - "k8s.io/utils/ptr" azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" @@ -300,7 +300,7 @@ func (ss *ScaleSet) GetPowerStatusByNodeName(ctx context.Context, name string) ( if vm.IsVirtualMachineScaleSetVM() { v := vm.AsVirtualMachineScaleSetVM() if v.InstanceView != nil { - return vmutil.GetVMPowerState(ptr.Deref(v.Name, ""), v.InstanceView.Statuses), nil + return vmutil.GetVMPowerState(lo.FromPtrOr(v.Name, ""), v.InstanceView.Statuses), nil } } @@ -335,7 +335,7 @@ func (ss *ScaleSet) GetProvisioningStateByNodeName(ctx context.Context, name str return provisioningState, nil } - return ptr.Deref(vm.VirtualMachineScaleSetVMProperties.ProvisioningState, ""), nil + return lo.FromPtrOr(vm.VirtualMachineScaleSetVMProperties.ProvisioningState, ""), nil } // getCachedVirtualMachineByInstanceID gets scaleSetVMInfo from cache. @@ -701,7 +701,7 @@ func (ss *ScaleSet) GetPrivateIPsByNodeName(ctx context.Context, nodeName string func (ss *ScaleSet) getPrimaryInterfaceID(vm *virtualmachine.VirtualMachine) (string, error) { machine := vm.AsVirtualMachineScaleSetVM() if machine.NetworkProfile == nil || machine.NetworkProfile.NetworkInterfaces == nil { - return "", fmt.Errorf("failed to find the network interfaces for vm %s", ptr.Deref(machine.Name, "")) + return "", fmt.Errorf("failed to find the network interfaces for vm %s", lo.FromPtrOr(machine.Name, "")) } if len(*machine.NetworkProfile.NetworkInterfaces) == 1 { @@ -709,12 +709,12 @@ func (ss *ScaleSet) getPrimaryInterfaceID(vm *virtualmachine.VirtualMachine) (st } for _, ref := range *machine.NetworkProfile.NetworkInterfaces { - if ptr.Deref(ref.Primary, false) { + if lo.FromPtrOr(ref.Primary, false) { return *ref.ID, nil } } - return "", fmt.Errorf("failed to find a primary nic for the vm. vmname=%q", ptr.Deref(machine.Name, "")) + return "", fmt.Errorf("failed to find a primary nic for the vm. vmname=%q", lo.FromPtrOr(machine.Name, "")) } // machineName is composed of computerNamePrefix and 36-based instanceID. @@ -1140,7 +1140,7 @@ func (ss *ScaleSet) EnsureHostInPool(ctx context.Context, _ *v1.Service, nodeNam // Compose a new vmssVM with added backendPoolID. newBackendPools = append(newBackendPools, compute.SubResource{ - ID: ptr.To(backendPoolID), + ID: to.Ptr(backendPoolID), }) primaryIPConfiguration.LoadBalancerBackendAddressPools = &newBackendPools newVM := &compute.VirtualMachineScaleSetVM{ @@ -1307,7 +1307,7 @@ func (ss *ScaleSet) ensureVMSSInPool(ctx context.Context, _ *v1.Service, nodes [ // Compose a new vmss with added backendPoolID. loadBalancerBackendAddressPools = append(loadBalancerBackendAddressPools, compute.SubResource{ - ID: ptr.To(backendPoolID), + ID: to.Ptr(backendPoolID), }) primaryIPConfig.LoadBalancerBackendAddressPools = &loadBalancerBackendAddressPools newVMSS := compute.VirtualMachineScaleSet{ @@ -1687,7 +1687,7 @@ func (ss *ScaleSet) ensureBackendPoolDeletedFromVMSS(ctx context.Context, backen vmssUniformMap.Range(func(_, value interface{}) bool { vmssEntry := value.(*VMSSEntry) - if ptr.Deref(vmssEntry.VMSS.Name, "") == vmSetName { + if lo.FromPtrOr(vmssEntry.VMSS.Name, "") == vmSetName { found = true return false } @@ -1706,7 +1706,7 @@ func (ss *ScaleSet) ensureBackendPoolDeletedFromVMSS(ctx context.Context, backen vmssFlexMap := cachedFlex.(*sync.Map) vmssFlexMap.Range(func(_, value interface{}) bool { vmssFlex := value.(*compute.VirtualMachineScaleSet) - if ptr.Deref(vmssFlex.Name, "") == vmSetName { + if lo.FromPtrOr(vmssFlex.Name, "") == vmSetName { found = true return false } @@ -1750,34 +1750,34 @@ func (ss *ScaleSet) ensureBackendPoolDeletedFromVmssUniform(ctx context.Context, } else if v, ok := value.(*compute.VirtualMachineScaleSet); ok { vmss = v } - klog.V(2).Infof("ensureBackendPoolDeletedFromVmssUniform: vmss %q, backendPoolIDs %q", ptr.Deref(vmss.Name, ""), backendPoolIDs) + klog.V(2).Infof("ensureBackendPoolDeletedFromVmssUniform: vmss %q, backendPoolIDs %q", lo.FromPtrOr(vmss.Name, ""), backendPoolIDs) // When vmss is being deleted, CreateOrUpdate API would report "the vmss is being deleted" error. // Since it is being deleted, we shouldn't send more CreateOrUpdate requests for it. if vmss.ProvisioningState != nil && strings.EqualFold(*vmss.ProvisioningState, consts.ProvisionStateDeleting) { - klog.V(3).Infof("ensureBackendPoolDeletedFromVMSS: found vmss %s being deleted, skipping", ptr.Deref(vmss.Name, "")) + klog.V(3).Infof("ensureBackendPoolDeletedFromVMSS: found vmss %s being deleted, skipping", lo.FromPtrOr(vmss.Name, "")) return true } if vmss.VirtualMachineProfile == nil { - klog.V(4).Infof("ensureBackendPoolDeletedFromVMSS: vmss %s has no VirtualMachineProfile, skipping", ptr.Deref(vmss.Name, "")) + klog.V(4).Infof("ensureBackendPoolDeletedFromVMSS: vmss %s has no VirtualMachineProfile, skipping", lo.FromPtrOr(vmss.Name, "")) return true } if vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations == nil { - klog.V(4).Infof("ensureBackendPoolDeletedFromVMSS: cannot obtain the primary network interface configuration, of vmss %s", ptr.Deref(vmss.Name, "")) + klog.V(4).Infof("ensureBackendPoolDeletedFromVMSS: cannot obtain the primary network interface configuration, of vmss %s", lo.FromPtrOr(vmss.Name, "")) return true } vmssNIC := *vmss.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations - primaryNIC, err := getPrimaryNetworkInterfaceConfiguration(vmssNIC, ptr.Deref(vmss.Name, "")) + primaryNIC, err := getPrimaryNetworkInterfaceConfiguration(vmssNIC, lo.FromPtrOr(vmss.Name, "")) if err != nil { - klog.Errorf("ensureBackendPoolDeletedFromVMSS: failed to get the primary network interface config of the VMSS %s: %v", ptr.Deref(vmss.Name, ""), err) + klog.Errorf("ensureBackendPoolDeletedFromVMSS: failed to get the primary network interface config of the VMSS %s: %v", lo.FromPtrOr(vmss.Name, ""), err) errorList = append(errorList, err) return true } handleBackendPool := func(backendPoolID string) bool { - primaryIPConfig, err := getPrimaryIPConfigFromVMSSNetworkConfig(primaryNIC, backendPoolID, ptr.Deref(vmss.Name, "")) + primaryIPConfig, err := getPrimaryIPConfigFromVMSSNetworkConfig(primaryNIC, backendPoolID, lo.FromPtrOr(vmss.Name, "")) if err != nil { - klog.Errorf("ensureBackendPoolDeletedFromVMSS: failed to find the primary IP config from the VMSS %s's network config : %v", ptr.Deref(vmss.Name, ""), err) + klog.Errorf("ensureBackendPoolDeletedFromVMSS: failed to find the primary IP config from the VMSS %s's network config : %v", lo.FromPtrOr(vmss.Name, ""), err) errorList = append(errorList, err) return true } @@ -1786,10 +1786,10 @@ func (ss *ScaleSet) ensureBackendPoolDeletedFromVmssUniform(ctx context.Context, loadBalancerBackendAddressPools = *primaryIPConfig.LoadBalancerBackendAddressPools } for _, loadBalancerBackendAddressPool := range loadBalancerBackendAddressPools { - klog.V(4).Infof("ensureBackendPoolDeletedFromVMSS: loadBalancerBackendAddressPool (%s) on vmss (%s)", ptr.Deref(loadBalancerBackendAddressPool.ID, ""), ptr.Deref(vmss.Name, "")) - if strings.EqualFold(ptr.Deref(loadBalancerBackendAddressPool.ID, ""), backendPoolID) { - klog.V(4).Infof("ensureBackendPoolDeletedFromVMSS: found vmss %s with backend pool %s, removing it", ptr.Deref(vmss.Name, ""), backendPoolID) - vmssNamesMap[ptr.Deref(vmss.Name, "")] = true + klog.V(4).Infof("ensureBackendPoolDeletedFromVMSS: loadBalancerBackendAddressPool (%s) on vmss (%s)", lo.FromPtrOr(loadBalancerBackendAddressPool.ID, ""), lo.FromPtrOr(vmss.Name, "")) + if strings.EqualFold(lo.FromPtrOr(loadBalancerBackendAddressPool.ID, ""), backendPoolID) { + klog.V(4).Infof("ensureBackendPoolDeletedFromVMSS: found vmss %s with backend pool %s, removing it", lo.FromPtrOr(vmss.Name, ""), backendPoolID) + vmssNamesMap[lo.FromPtrOr(vmss.Name, "")] = true } } return true @@ -2012,7 +2012,7 @@ func (ss *ScaleSet) EnsureBackendPoolDeleted(ctx context.Context, service *v1.Se for backendPoolID, vmssUniformBackendIPConfigurations := range vmssUniformBackendIPConfigurationsMap { vmssUniformBackendIPConfigurations := vmssUniformBackendIPConfigurations vmssUniformBackendPools = append(vmssUniformBackendPools, network.BackendAddressPool{ - ID: ptr.To(backendPoolID), + ID: to.Ptr(backendPoolID), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ BackendIPConfigurations: &vmssUniformBackendIPConfigurations, }, @@ -2032,7 +2032,7 @@ func (ss *ScaleSet) EnsureBackendPoolDeleted(ctx context.Context, service *v1.Se for backendPoolID, vmssFlexBackendIPConfigurations := range vmssFlexBackendIPConfigurationsMap { vmssFlexBackendIPConfigurations := vmssFlexBackendIPConfigurations vmssFlexBackendPools = append(vmssFlexBackendPools, network.BackendAddressPool{ - ID: ptr.To(backendPoolID), + ID: to.Ptr(backendPoolID), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ BackendIPConfigurations: &vmssFlexBackendIPConfigurations, }, @@ -2052,7 +2052,7 @@ func (ss *ScaleSet) EnsureBackendPoolDeleted(ctx context.Context, service *v1.Se for backendPoolID, avSetBackendIPConfigurations := range avSetBackendIPConfigurationsMap { avSetBackendIPConfigurations := avSetBackendIPConfigurations avSetBackendPools = append(avSetBackendPools, network.BackendAddressPool{ - ID: ptr.To(backendPoolID), + ID: to.Ptr(backendPoolID), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ BackendIPConfigurations: &avSetBackendIPConfigurations, }, @@ -2100,15 +2100,15 @@ func (ss *ScaleSet) GetNodeCIDRMasksByProviderID(ctx context.Context, providerID var ipv4Mask, ipv6Mask int if v4, ok := vmss.Tags[consts.VMSetCIDRIPV4TagKey]; ok && v4 != nil { - ipv4Mask, err = strconv.Atoi(ptr.Deref(v4, "")) + ipv4Mask, err = strconv.Atoi(lo.FromPtrOr(v4, "")) if err != nil { - klog.Errorf("GetNodeCIDRMasksByProviderID: error when paring the value of the ipv4 mask size %s: %v", ptr.Deref(v4, ""), err) + klog.Errorf("GetNodeCIDRMasksByProviderID: error when paring the value of the ipv4 mask size %s: %v", lo.FromPtrOr(v4, ""), err) } } if v6, ok := vmss.Tags[consts.VMSetCIDRIPV6TagKey]; ok && v6 != nil { - ipv6Mask, err = strconv.Atoi(ptr.Deref(v6, "")) + ipv6Mask, err = strconv.Atoi(lo.FromPtrOr(v6, "")) if err != nil { - klog.Errorf("GetNodeCIDRMasksByProviderID: error when paring the value of the ipv6 mask size%s: %v", ptr.Deref(v6, ""), err) + klog.Errorf("GetNodeCIDRMasksByProviderID: error when paring the value of the ipv6 mask size%s: %v", lo.FromPtrOr(v6, ""), err) } } diff --git a/pkg/provider/azure_vmss_cache.go b/pkg/provider/azure_vmss_cache.go index e011f85e9a..ef3139e703 100644 --- a/pkg/provider/azure_vmss_cache.go +++ b/pkg/provider/azure_vmss_cache.go @@ -24,9 +24,8 @@ import ( "time" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - + "github.com/samber/lo" "k8s.io/klog/v2" - "k8s.io/utils/ptr" azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" @@ -194,13 +193,13 @@ func (ss *ScaleSet) newVMSSVirtualMachinesCache() (azcache.Resource, error) { vmssVMCacheEntry := &VMSSVirtualMachineEntry{ ResourceGroup: resourceGroupName, VMSSName: vmssName, - InstanceID: ptr.Deref(vm.InstanceID, ""), + InstanceID: lo.FromPtrOr(vm.InstanceID, ""), VirtualMachine: &vm, LastUpdate: time.Now().UTC(), } // set cache entry to nil when the VM is under deleting. if vm.VirtualMachineScaleSetVMProperties != nil && - strings.EqualFold(ptr.Deref(vm.VirtualMachineScaleSetVMProperties.ProvisioningState, ""), string(consts.ProvisioningStateDeleting)) { + strings.EqualFold(lo.FromPtrOr(vm.VirtualMachineScaleSetVMProperties.ProvisioningState, ""), string(consts.ProvisioningStateDeleting)) { klog.V(4).Infof("VMSS virtualMachine %q is under deleting, setting its cache to nil", computerName) vmssVMCacheEntry.VirtualMachine = nil } @@ -342,14 +341,14 @@ func (ss *ScaleSet) newNonVmssUniformNodesCache() (azcache.Resource, error) { for _, vm := range vms { if vm.OsProfile != nil && vm.OsProfile.ComputerName != nil { if vm.VirtualMachineScaleSet != nil { - vmssFlexVMNodeNames.Insert(strings.ToLower(ptr.Deref(vm.OsProfile.ComputerName, ""))) + vmssFlexVMNodeNames.Insert(strings.ToLower(lo.FromPtrOr(vm.OsProfile.ComputerName, ""))) if vm.ID != nil { - vmssFlexVMProviderIDs.Insert(ss.ProviderName() + "://" + ptr.Deref(vm.ID, "")) + vmssFlexVMProviderIDs.Insert(ss.ProviderName() + "://" + lo.FromPtrOr(vm.ID, "")) } } else { - avSetVMNodeNames.Insert(strings.ToLower(ptr.Deref(vm.OsProfile.ComputerName, ""))) + avSetVMNodeNames.Insert(strings.ToLower(lo.FromPtrOr(vm.OsProfile.ComputerName, ""))) if vm.ID != nil { - avSetVMProviderIDs.Insert(ss.ProviderName() + "://" + ptr.Deref(vm.ID, "")) + avSetVMProviderIDs.Insert(ss.ProviderName() + "://" + lo.FromPtrOr(vm.ID, "")) } } } @@ -529,9 +528,9 @@ func (az *Cloud) GetVMNameByIPConfigurationName(ctx context.Context, nicResource return "", fmt.Errorf("failed to get interface of name %s: %w", nicName, rerr.Error()) } if nic.InterfacePropertiesFormat == nil || nic.InterfacePropertiesFormat.VirtualMachine == nil || nic.InterfacePropertiesFormat.VirtualMachine.ID == nil { - return "", fmt.Errorf("failed to get vm ID of nic %s", ptr.Deref(nic.Name, "")) + return "", fmt.Errorf("failed to get vm ID of nic %s", lo.FromPtrOr(nic.Name, "")) } - vmID := ptr.Deref(nic.InterfacePropertiesFormat.VirtualMachine.ID, "") + vmID := lo.FromPtrOr(nic.InterfacePropertiesFormat.VirtualMachine.ID, "") matches := vmIDRE.FindStringSubmatch(vmID) if len(matches) != 2 { return "", fmt.Errorf("invalid virtual machine ID %s", vmID) diff --git a/pkg/provider/azure_vmss_cache_test.go b/pkg/provider/azure_vmss_cache_test.go index 87bb9a6393..b976249a4c 100644 --- a/pkg/provider/azure_vmss_cache_test.go +++ b/pkg/provider/azure_vmss_cache_test.go @@ -23,14 +23,13 @@ import ( "net/http" "testing" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" + "github.com/samber/lo" "github.com/stretchr/testify/assert" - "go.uber.org/mock/gomock" - cloudprovider "k8s.io/cloud-provider" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/interfaceclient/mockinterfaceclient" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmclient/mockvmclient" @@ -66,18 +65,18 @@ func TestVMSSVMCache(t *testing.T) { // validate getting VMSS VM via cache. for i := range expectedVMs { vm := expectedVMs[i] - vmName := ptr.Deref(vm.OsProfile.ComputerName, "") + vmName := lo.FromPtrOr(vm.OsProfile.ComputerName, "") realVM, err := ss.getVmssVM(context.TODO(), vmName, azcache.CacheReadTypeDefault) assert.NoError(t, err) assert.NotNil(t, realVM) assert.Equal(t, "vmss", realVM.VMSSName) - assert.Equal(t, ptr.Deref(vm.InstanceID, ""), realVM.InstanceID) + assert.Equal(t, lo.FromPtrOr(vm.InstanceID, ""), realVM.InstanceID) assert.Equal(t, &vm, realVM.AsVirtualMachineScaleSetVM()) } // validate DeleteCacheForNode(). vm := expectedVMs[0] - vmName := ptr.Deref(vm.OsProfile.ComputerName, "") + vmName := lo.FromPtrOr(vm.OsProfile.ComputerName, "") err = ss.DeleteCacheForNode(context.TODO(), vmName) assert.NoError(t, err) @@ -85,7 +84,7 @@ func TestVMSSVMCache(t *testing.T) { realVM, err := ss.getVmssVM(context.TODO(), vmName, azcache.CacheReadTypeDefault) assert.NoError(t, err) assert.Equal(t, "vmss", realVM.VMSSName) - assert.Equal(t, ptr.Deref(vm.InstanceID, ""), realVM.InstanceID) + assert.Equal(t, lo.FromPtrOr(vm.InstanceID, ""), realVM.InstanceID) assert.Equal(t, &vm, realVM.AsVirtualMachineScaleSetVM()) } @@ -103,7 +102,7 @@ func TestVMSSVMCacheWithDeletingNodes(t *testing.T) { ss.VirtualMachineScaleSetVMsClient = mockVMSSVMClient expectedScaleSet := compute.VirtualMachineScaleSet{ - Name: ptr.To(testVMSSName), + Name: to.Ptr(testVMSSName), VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{}, } mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()).Return([]compute.VirtualMachineScaleSet{expectedScaleSet}, nil).AnyTimes() @@ -113,8 +112,8 @@ func TestVMSSVMCacheWithDeletingNodes(t *testing.T) { for i := range expectedVMs { vm := expectedVMs[i] - vmName := ptr.Deref(vm.OsProfile.ComputerName, "") - assert.Equal(t, vm.ProvisioningState, ptr.To(string(consts.ProvisioningStateDeleting))) + vmName := lo.FromPtrOr(vm.OsProfile.ComputerName, "") + assert.Equal(t, vm.ProvisioningState, to.Ptr(string(consts.ProvisioningStateDeleting))) realVM, err := ss.getVmssVM(context.TODO(), vmName, azcache.CacheReadTypeDefault) assert.Nil(t, realVM) @@ -143,11 +142,11 @@ func TestVMSSVMCacheClearedWhenRGDeleted(t *testing.T) { // validate getting VMSS VM via cache. vm := expectedVMs[0] - vmName := ptr.Deref(vm.OsProfile.ComputerName, "") + vmName := lo.FromPtrOr(vm.OsProfile.ComputerName, "") realVM, err := ss.getVmssVM(context.TODO(), vmName, azcache.CacheReadTypeDefault) assert.NoError(t, err) assert.Equal(t, "vmss", realVM.VMSSName) - assert.Equal(t, ptr.Deref(vm.InstanceID, ""), realVM.InstanceID) + assert.Equal(t, lo.FromPtrOr(vm.InstanceID, ""), realVM.InstanceID) assert.Equal(t, &vm, realVM.AsVirtualMachineScaleSetVM()) // verify cache has test vmss. @@ -332,7 +331,7 @@ func buildTestNICWithVMName(vmName string) network.Interface { Name: &vmName, InterfacePropertiesFormat: &network.InterfacePropertiesFormat{ VirtualMachine: &network.SubResource{ - ID: ptr.To(fmt.Sprintf("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/%s", vmName)), + ID: to.Ptr(fmt.Sprintf("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/%s", vmName)), }, }, } @@ -345,7 +344,7 @@ func TestGetVMManagementTypeByIPConfigurationID(t *testing.T) { testVM1 := generateVmssFlexTestVMWithoutInstanceView(testVM1Spec) testVM2 := generateVmssFlexTestVMWithoutInstanceView(testVM2Spec) testVM2.VirtualMachineScaleSet = nil - testVM2.VirtualMachineProperties.OsProfile.ComputerName = ptr.To("testvm2") + testVM2.VirtualMachineProperties.OsProfile.ComputerName = to.Ptr("testvm2") testVMList := []compute.VirtualMachine{ testVM1, diff --git a/pkg/provider/azure_vmss_repo_test.go b/pkg/provider/azure_vmss_repo_test.go index 4528990c08..6d477d3a4e 100644 --- a/pkg/provider/azure_vmss_repo_test.go +++ b/pkg/provider/azure_vmss_repo_test.go @@ -22,15 +22,13 @@ import ( "net/http" "testing" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" "github.com/stretchr/testify/assert" - "go.uber.org/mock/gomock" - "k8s.io/apimachinery/pkg/util/wait" cloudprovider "k8s.io/cloud-provider" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/interfaceclient/mockinterfaceclient" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/publicipclient/mockpublicipclient" @@ -65,7 +63,7 @@ func TestCreateOrUpdateVMSS(t *testing.T) { { vmss: compute.VirtualMachineScaleSet{ VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{ - ProvisioningState: ptr.To(consts.ProvisionStateDeleting), + ProvisioningState: to.Ptr(consts.ProvisionStateDeleting), }, }, }, @@ -139,14 +137,14 @@ func TestGetPrivateIPsForMachine(t *testing.T) { expectedVM := compute.VirtualMachine{ VirtualMachineProperties: &compute.VirtualMachineProperties{ - AvailabilitySet: &compute.SubResource{ID: ptr.To("availability-set")}, + AvailabilitySet: &compute.SubResource{ID: to.Ptr("availability-set")}, NetworkProfile: &compute.NetworkProfile{ NetworkInterfaces: &[]compute.NetworkInterfaceReference{ { NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{ - Primary: ptr.To(true), + Primary: to.Ptr(true), }, - ID: ptr.To("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic"), + ID: to.Ptr("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic"), }, }, }, @@ -158,7 +156,7 @@ func TestGetPrivateIPsForMachine(t *testing.T) { IPConfigurations: &[]network.InterfaceIPConfiguration{ { InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ - PrivateIPAddress: ptr.To("1.2.3.4"), + PrivateIPAddress: to.Ptr("1.2.3.4"), }, }, }, @@ -201,14 +199,14 @@ func TestGetIPForMachineWithRetry(t *testing.T) { expectedVM := compute.VirtualMachine{ VirtualMachineProperties: &compute.VirtualMachineProperties{ - AvailabilitySet: &compute.SubResource{ID: ptr.To("availability-set")}, + AvailabilitySet: &compute.SubResource{ID: to.Ptr("availability-set")}, NetworkProfile: &compute.NetworkProfile{ NetworkInterfaces: &[]compute.NetworkInterfaceReference{ { NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{ - Primary: ptr.To(true), + Primary: to.Ptr(true), }, - ID: ptr.To("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic"), + ID: to.Ptr("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic"), }, }, }, @@ -220,9 +218,9 @@ func TestGetIPForMachineWithRetry(t *testing.T) { IPConfigurations: &[]network.InterfaceIPConfiguration{ { InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ - PrivateIPAddress: ptr.To("1.2.3.4"), + PrivateIPAddress: to.Ptr("1.2.3.4"), PublicIPAddress: &network.PublicIPAddress{ - ID: ptr.To("test/pip"), + ID: to.Ptr("test/pip"), }, }, }, @@ -231,9 +229,9 @@ func TestGetIPForMachineWithRetry(t *testing.T) { } expectedPIP := network.PublicIPAddress{ - Name: ptr.To("pip"), + Name: to.Ptr("pip"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To("5.6.7.8"), + IPAddress: to.Ptr("5.6.7.8"), }, } diff --git a/pkg/provider/azure_vmss_test.go b/pkg/provider/azure_vmss_test.go index e0d6aad139..e040920054 100644 --- a/pkg/provider/azure_vmss_test.go +++ b/pkg/provider/azure_vmss_test.go @@ -23,17 +23,17 @@ import ( "strings" "testing" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" + "github.com/samber/lo" "github.com/stretchr/testify/assert" "go.uber.org/mock/gomock" - v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" utilerrors "k8s.io/apimachinery/pkg/util/errors" cloudprovider "k8s.io/cloud-provider" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/interfaceclient/mockinterfaceclient" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/publicipclient/mockpublicipclient" @@ -80,7 +80,7 @@ func buildTestOSSpecificVMSSWithLB(name, namePrefix string, lbBackendpoolIDs []s OsType: compute.OperatingSystemTypesWindows, }, ImageReference: &compute.ImageReference{ - ID: ptr.To("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/AKS-Windows/providers/Microsoft.Compute/galleries/AKSWindows/images/windows-2019-containerd/versions/17763.5820.240516"), + ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/AKS-Windows/providers/Microsoft.Compute/galleries/AKSWindows/images/windows-2019-containerd/versions/17763.5820.240516"), }, } case windows2022: @@ -89,7 +89,7 @@ func buildTestOSSpecificVMSSWithLB(name, namePrefix string, lbBackendpoolIDs []s OsType: compute.OperatingSystemTypesWindows, }, ImageReference: &compute.ImageReference{ - ID: ptr.To("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/AKS-Windows/providers/Microsoft.Compute/galleries/AKSWindows/images/windows-2022-containerd/versions/20348.5820.240516"), + ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/AKS-Windows/providers/Microsoft.Compute/galleries/AKSWindows/images/windows-2022-containerd/versions/20348.5820.240516"), }, } } @@ -99,8 +99,8 @@ func buildTestOSSpecificVMSSWithLB(name, namePrefix string, lbBackendpoolIDs []s func buildTestVMSSWithLB(name, namePrefix string, lbBackendpoolIDs []string, ipv6 bool) compute.VirtualMachineScaleSet { lbBackendpoolsV4, lbBackendpoolsV6 := make([]compute.SubResource, 0), make([]compute.SubResource, 0) for _, id := range lbBackendpoolIDs { - lbBackendpoolsV4 = append(lbBackendpoolsV4, compute.SubResource{ID: ptr.To(id)}) - lbBackendpoolsV6 = append(lbBackendpoolsV6, compute.SubResource{ID: ptr.To(id + "-" + consts.IPVersionIPv6String)}) + lbBackendpoolsV4 = append(lbBackendpoolsV4, compute.SubResource{ID: to.Ptr(id)}) + lbBackendpoolsV6 = append(lbBackendpoolsV6, compute.SubResource{ID: to.Ptr(id + "-" + consts.IPVersionIPv6String)}) } ipConfig := []compute.VirtualMachineScaleSetIPConfiguration{ { @@ -122,7 +122,7 @@ func buildTestVMSSWithLB(name, namePrefix string, lbBackendpoolIDs []string, ipv Name: &name, VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{ OrchestrationMode: compute.Uniform, - ProvisioningState: ptr.To("Running"), + ProvisioningState: to.Ptr("Running"), VirtualMachineProfile: &compute.VirtualMachineScaleSetVMProfile{ OsProfile: &compute.VirtualMachineScaleSetOSProfile{ ComputerNamePrefix: &namePrefix, @@ -131,7 +131,7 @@ func buildTestVMSSWithLB(name, namePrefix string, lbBackendpoolIDs []string, ipv NetworkInterfaceConfigurations: &[]compute.VirtualMachineScaleSetNetworkConfiguration{ { VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ - Primary: ptr.To(true), + Primary: to.Ptr(true), IPConfigurations: &ipConfig, }, }, @@ -176,44 +176,44 @@ func buildTestVirtualMachineEnv(ss *Cloud, scaleSetName, zone string, faultDomai { ID: &interfaceID, NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{ - Primary: ptr.To(true), + Primary: to.Ptr(true), }, }, } ipConfigurations := []compute.VirtualMachineScaleSetIPConfiguration{ { - Name: ptr.To("ipconfig1"), + Name: to.Ptr("ipconfig1"), VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ - Primary: ptr.To(true), - LoadBalancerBackendAddressPools: &[]compute.SubResource{{ID: ptr.To(testLBBackendpoolID0)}}, + Primary: to.Ptr(true), + LoadBalancerBackendAddressPools: &[]compute.SubResource{{ID: to.Ptr(testLBBackendpoolID0)}}, PrivateIPAddressVersion: compute.IPv4, }, }, } if isIPv6 { ipConfigurations = append(ipConfigurations, compute.VirtualMachineScaleSetIPConfiguration{ - Name: ptr.To("ipconfigv6"), + Name: to.Ptr("ipconfigv6"), VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ - Primary: ptr.To(false), - LoadBalancerBackendAddressPools: &[]compute.SubResource{{ID: ptr.To(testLBBackendpoolID0v6)}}, + Primary: to.Ptr(false), + LoadBalancerBackendAddressPools: &[]compute.SubResource{{ID: to.Ptr(testLBBackendpoolID0v6)}}, PrivateIPAddressVersion: compute.IPv6, }, }) } networkConfigurations := []compute.VirtualMachineScaleSetNetworkConfiguration{ { - Name: ptr.To("vmss-nic"), - ID: ptr.To("fakeNetworkConfiguration"), + Name: to.Ptr("vmss-nic"), + ID: to.Ptr("fakeNetworkConfiguration"), VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ IPConfigurations: &ipConfigurations, - Primary: ptr.To(true), + Primary: to.Ptr(true), }, }, } vmssVM := compute.VirtualMachineScaleSetVM{ VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ - ProvisioningState: ptr.To(state), + ProvisioningState: to.Ptr(state), OsProfile: &compute.OSProfile{ ComputerName: &nodeName, }, @@ -226,7 +226,7 @@ func buildTestVirtualMachineEnv(ss *Cloud, scaleSetName, zone string, faultDomai InstanceView: &compute.VirtualMachineScaleSetVMInstanceView{ PlatformFaultDomain: &faultDomain, Statuses: &[]compute.InstanceViewStatus{ - {Code: ptr.To(testVMPowerState)}, + {Code: to.Ptr(testVMPowerState)}, }, }, }, @@ -234,7 +234,7 @@ func buildTestVirtualMachineEnv(ss *Cloud, scaleSetName, zone string, faultDomai InstanceID: &instanceID, Name: &vmName, Location: &ss.Location, - Sku: &compute.Sku{Name: ptr.To("sku")}, + Sku: &compute.Sku{Name: to.Ptr("sku")}, } if zone != "" { zones := []string{zone} @@ -243,16 +243,16 @@ func buildTestVirtualMachineEnv(ss *Cloud, scaleSetName, zone string, faultDomai // set interfaces. expectedInterface = network.Interface{ - Name: ptr.To("nic"), + Name: to.Ptr("nic"), ID: &interfaceID, InterfacePropertiesFormat: &network.InterfacePropertiesFormat{ IPConfigurations: &[]network.InterfaceIPConfiguration{ { InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ - Primary: ptr.To(true), - PrivateIPAddress: ptr.To(fakePrivateIP), + Primary: to.Ptr(true), + PrivateIPAddress: to.Ptr(fakePrivateIP), PublicIPAddress: &network.PublicIPAddress{ - ID: ptr.To(publicAddressID), + ID: to.Ptr(publicAddressID), }, }, }, @@ -262,9 +262,9 @@ func buildTestVirtualMachineEnv(ss *Cloud, scaleSetName, zone string, faultDomai // set public IPs. expectedPIP = network.PublicIPAddress{ - ID: ptr.To(publicAddressID), + ID: to.Ptr(publicAddressID), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ - IPAddress: ptr.To(fakePublicIP), + IPAddress: to.Ptr(fakePublicIP), }, } @@ -738,7 +738,7 @@ func TestGetVMSS(t *testing.T) { ss.VirtualMachineScaleSetsClient = mockVMSSClient expected := compute.VirtualMachineScaleSet{ - Name: ptr.To(test.existedVMSSName), + Name: to.Ptr(test.existedVMSSName), VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{ VirtualMachineProfile: &compute.VirtualMachineScaleSetVMProfile{}, }, @@ -892,7 +892,7 @@ func TestGetProvisioningStateByNodeName(t *testing.T) { expectedVMSSVMs, _, _ := buildTestVirtualMachineEnv(ss.Cloud, testVMSSName, "", 0, test.vmList, "", false) mockVMSSVMClient := ss.VirtualMachineScaleSetVMsClient.(*mockvmssvmclient.MockInterface) if test.provisioningState != "" { - expectedVMSSVMs[0].ProvisioningState = ptr.To(test.provisioningState) + expectedVMSSVMs[0].ProvisioningState = to.Ptr(test.provisioningState) } else { expectedVMSSVMs[0].ProvisioningState = nil } @@ -929,7 +929,7 @@ func TestGetVmssVMByInstanceID(t *testing.T) { assert.NoError(t, err, "unexpected error when creating test VMSS") expectedVMSS := compute.VirtualMachineScaleSet{ - Name: ptr.To(testVMSSName), + Name: to.Ptr(testVMSSName), VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{ VirtualMachineProfile: &compute.VirtualMachineScaleSetVMProfile{}, }, @@ -978,7 +978,7 @@ func TestGetVmssVMByNodeIdentity(t *testing.T) { assert.NoError(t, err, "unexpected error when creating test VMSS") expectedVMSS := compute.VirtualMachineScaleSet{ - Name: ptr.To(testVMSSName), + Name: to.Ptr(testVMSSName), VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{ VirtualMachineProfile: &compute.VirtualMachineScaleSetVMProfile{}, }, @@ -1087,12 +1087,12 @@ func TestGetPrimaryInterfaceID(t *testing.T) { description: "GetPrimaryInterfaceID should return the ID of the primary NIC on the VMSS VM", existedInterfaces: []compute.NetworkInterfaceReference{ { - ID: ptr.To("1"), + ID: to.Ptr("1"), NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{ - Primary: ptr.To(true), + Primary: to.Ptr(true), }, }, - {ID: ptr.To("2")}, + {ID: to.Ptr("2")}, }, expectedID: "1", }, @@ -1100,15 +1100,15 @@ func TestGetPrimaryInterfaceID(t *testing.T) { description: "GetPrimaryInterfaceID should report an error if there's no primary NIC on the VMSS VM", existedInterfaces: []compute.NetworkInterfaceReference{ { - ID: ptr.To("1"), + ID: to.Ptr("1"), NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{ - Primary: ptr.To(false), + Primary: to.Ptr(false), }, }, { - ID: ptr.To("2"), + ID: to.Ptr("2"), NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{ - Primary: ptr.To(false), + Primary: to.Ptr(false), }, }, }, @@ -1127,7 +1127,7 @@ func TestGetPrimaryInterfaceID(t *testing.T) { existedInterfaces := test.existedInterfaces vm := compute.VirtualMachineScaleSetVM{ - Name: ptr.To("vm"), + Name: to.Ptr("vm"), VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ NetworkProfile: &compute.NetworkProfile{ NetworkInterfaces: &existedInterfaces, @@ -1225,15 +1225,15 @@ func TestGetPrimaryInterface(t *testing.T) { expectedVMSSVMs, expectedInterface, _ := buildTestVirtualMachineEnv(ss.Cloud, testVMSSName, "", 0, test.vmList, "", false) if !test.hasPrimaryInterface { networkInterfaces := *expectedVMSSVMs[0].NetworkProfile.NetworkInterfaces - networkInterfaces[0].Primary = ptr.To(false) + networkInterfaces[0].Primary = to.Ptr(false) networkInterfaces = append(networkInterfaces, compute.NetworkInterfaceReference{ - NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{Primary: ptr.To(false)}, + NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{Primary: to.Ptr(false)}, }) expectedVMSSVMs[0].NetworkProfile.NetworkInterfaces = &networkInterfaces } if test.isInvalidNICID { networkInterfaces := *expectedVMSSVMs[0].NetworkProfile.NetworkInterfaces - networkInterfaces[0].ID = ptr.To("invalid/id/") + networkInterfaces[0].ID = to.Ptr("invalid/id/") expectedVMSSVMs[0].NetworkProfile.NetworkInterfaces = &networkInterfaces } mockVMSSVMClient := ss.VirtualMachineScaleSetVMsClient.(*mockvmssvmclient.MockInterface) @@ -1408,8 +1408,8 @@ func TestListScaleSetVMs(t *testing.T) { { description: "listScaleSetVMs should return the correct vmss vms", existedVMSSVMs: []compute.VirtualMachineScaleSetVM{ - {Name: ptr.To("vmss-vm-000000")}, - {Name: ptr.To("vmss-vm-000001")}, + {Name: to.Ptr("vmss-vm-000000")}, + {Name: to.Ptr("vmss-vm-000001")}, }, }, { @@ -1503,7 +1503,7 @@ func TestGetAgentPoolScaleSets(t *testing.T) { expectedVMSSVMs := []compute.VirtualMachineScaleSetVM{ { VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ - OsProfile: &compute.OSProfile{ComputerName: ptr.To("vmss-vm-000000")}, + OsProfile: &compute.OSProfile{ComputerName: to.Ptr("vmss-vm-000000")}, NetworkProfile: &compute.NetworkProfile{ NetworkInterfaces: &[]compute.NetworkInterfaceReference{}, }, @@ -1511,7 +1511,7 @@ func TestGetAgentPoolScaleSets(t *testing.T) { }, { VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ - OsProfile: &compute.OSProfile{ComputerName: ptr.To("vmss-vm-000001")}, + OsProfile: &compute.OSProfile{ComputerName: to.Ptr("vmss-vm-000001")}, NetworkProfile: &compute.NetworkProfile{ NetworkInterfaces: &[]compute.NetworkInterfaceReference{}, }, @@ -1519,7 +1519,7 @@ func TestGetAgentPoolScaleSets(t *testing.T) { }, { VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ - OsProfile: &compute.OSProfile{ComputerName: ptr.To("vmss-vm-000002")}, + OsProfile: &compute.OSProfile{ComputerName: to.Ptr("vmss-vm-000002")}, NetworkProfile: &compute.NetworkProfile{ NetworkInterfaces: &[]compute.NetworkInterfaceReference{}, }, @@ -1636,7 +1636,7 @@ func TestGetVMSetNames(t *testing.T) { expectedVMSSVMs := []compute.VirtualMachineScaleSetVM{ { VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ - OsProfile: &compute.OSProfile{ComputerName: ptr.To("vmss-vm-000000")}, + OsProfile: &compute.OSProfile{ComputerName: to.Ptr("vmss-vm-000000")}, NetworkProfile: &compute.NetworkProfile{ NetworkInterfaces: &[]compute.NetworkInterfaceReference{}, }, @@ -1644,7 +1644,7 @@ func TestGetVMSetNames(t *testing.T) { }, { VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ - OsProfile: &compute.OSProfile{ComputerName: ptr.To("vmss-vm-000001")}, + OsProfile: &compute.OSProfile{ComputerName: to.Ptr("vmss-vm-000001")}, NetworkProfile: &compute.NetworkProfile{ NetworkInterfaces: &[]compute.NetworkInterfaceReference{}, }, @@ -1652,7 +1652,7 @@ func TestGetVMSetNames(t *testing.T) { }, { VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ - OsProfile: &compute.OSProfile{ComputerName: ptr.To("vmss-vm-000002")}, + OsProfile: &compute.OSProfile{ComputerName: to.Ptr("vmss-vm-000002")}, NetworkProfile: &compute.NetworkProfile{ NetworkInterfaces: &[]compute.NetworkInterfaceReference{}, }, @@ -1660,7 +1660,7 @@ func TestGetVMSetNames(t *testing.T) { }, { VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ - OsProfile: &compute.OSProfile{ComputerName: ptr.To("vmss-vm-000003")}, + OsProfile: &compute.OSProfile{ComputerName: to.Ptr("vmss-vm-000003")}, }, }, } @@ -1683,7 +1683,7 @@ func TestGetPrimaryNetworkInterfaceConfiguration(t *testing.T) { defer ctrl.Finish() networkConfigs := []compute.VirtualMachineScaleSetNetworkConfiguration{ - {Name: ptr.To("config-0")}, + {Name: to.Ptr("config-0")}, } config, err := getPrimaryNetworkInterfaceConfiguration(networkConfigs, testVMSSName) assert.Nil(t, err, "getPrimaryNetworkInterfaceConfiguration should return the correct network config") @@ -1691,15 +1691,15 @@ func TestGetPrimaryNetworkInterfaceConfiguration(t *testing.T) { networkConfigs = []compute.VirtualMachineScaleSetNetworkConfiguration{ { - Name: ptr.To("config-0"), + Name: to.Ptr("config-0"), VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ - Primary: ptr.To(false), + Primary: to.Ptr(false), }, }, { - Name: ptr.To("config-1"), + Name: to.Ptr("config-1"), VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ - Primary: ptr.To(true), + Primary: to.Ptr(true), }, }, } @@ -1709,15 +1709,15 @@ func TestGetPrimaryNetworkInterfaceConfiguration(t *testing.T) { networkConfigs = []compute.VirtualMachineScaleSetNetworkConfiguration{ { - Name: ptr.To("config-0"), + Name: to.Ptr("config-0"), VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ - Primary: ptr.To(false), + Primary: to.Ptr(false), }, }, { - Name: ptr.To("config-1"), + Name: to.Ptr("config-1"), VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ - Primary: ptr.To(false), + Primary: to.Ptr(false), }, }, } @@ -1740,14 +1740,14 @@ func TestGetPrimaryIPConfigFromVMSSNetworkConfig(t *testing.T) { VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ { - Name: ptr.To("config-0"), + Name: to.Ptr("config-0"), }, }, }, }, backendPoolID: testLBBackendpoolID0, expectedIPConfig: &compute.VirtualMachineScaleSetIPConfiguration{ - Name: ptr.To("config-0"), + Name: to.Ptr("config-0"), }, }, { @@ -1756,15 +1756,15 @@ func TestGetPrimaryIPConfigFromVMSSNetworkConfig(t *testing.T) { VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ { - Name: ptr.To("config-0"), + Name: to.Ptr("config-0"), VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ - Primary: ptr.To(false), + Primary: to.Ptr(false), }, }, { - Name: ptr.To("config-1"), + Name: to.Ptr("config-1"), VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ - Primary: ptr.To(true), + Primary: to.Ptr(true), }, }, }, @@ -1772,9 +1772,9 @@ func TestGetPrimaryIPConfigFromVMSSNetworkConfig(t *testing.T) { }, backendPoolID: testLBBackendpoolID0, expectedIPConfig: &compute.VirtualMachineScaleSetIPConfiguration{ - Name: ptr.To("config-1"), + Name: to.Ptr("config-1"), VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ - Primary: ptr.To(true), + Primary: to.Ptr(true), }, }, }, @@ -1784,15 +1784,15 @@ func TestGetPrimaryIPConfigFromVMSSNetworkConfig(t *testing.T) { VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ { - Name: ptr.To("config-0"), + Name: to.Ptr("config-0"), VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ - Primary: ptr.To(false), + Primary: to.Ptr(false), }, }, { - Name: ptr.To("config-1"), + Name: to.Ptr("config-1"), VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ - Primary: ptr.To(false), + Primary: to.Ptr(false), }, }, }, @@ -1807,14 +1807,14 @@ func TestGetPrimaryIPConfigFromVMSSNetworkConfig(t *testing.T) { VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ { - Name: ptr.To("config-0"), + Name: to.Ptr("config-0"), VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ PrivateIPAddressVersion: compute.IPv4, - Primary: ptr.To(true), + Primary: to.Ptr(true), }, }, { - Name: ptr.To("config-0"), + Name: to.Ptr("config-0"), VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ PrivateIPAddressVersion: compute.IPv6, }, @@ -1824,10 +1824,10 @@ func TestGetPrimaryIPConfigFromVMSSNetworkConfig(t *testing.T) { }, backendPoolID: testLBBackendpoolID0, expectedIPConfig: &compute.VirtualMachineScaleSetIPConfiguration{ - Name: ptr.To("config-0"), + Name: to.Ptr("config-0"), VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ PrivateIPAddressVersion: compute.IPv4, - Primary: ptr.To(true), + Primary: to.Ptr(true), }, }, }, @@ -1837,14 +1837,14 @@ func TestGetPrimaryIPConfigFromVMSSNetworkConfig(t *testing.T) { VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ { - Name: ptr.To("config-0"), + Name: to.Ptr("config-0"), VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ PrivateIPAddressVersion: compute.IPv4, - Primary: ptr.To(true), + Primary: to.Ptr(true), }, }, { - Name: ptr.To("config-0-IPv6"), + Name: to.Ptr("config-0-IPv6"), VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ PrivateIPAddressVersion: compute.IPv6, }, @@ -1854,7 +1854,7 @@ func TestGetPrimaryIPConfigFromVMSSNetworkConfig(t *testing.T) { }, backendPoolID: testLBBackendpoolID0v6, expectedIPConfig: &compute.VirtualMachineScaleSetIPConfiguration{ - Name: ptr.To("config-0-IPv6"), + Name: to.Ptr("config-0-IPv6"), VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ PrivateIPAddressVersion: compute.IPv6, }, @@ -1887,15 +1887,15 @@ func TestDeleteBackendPoolFromIPConfig(t *testing.T) { VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ { - Name: ptr.To("config-0"), + Name: to.Ptr("config-0"), VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ - Primary: ptr.To(true), + Primary: to.Ptr(true), LoadBalancerBackendAddressPools: &[]compute.SubResource{ { - ID: ptr.To("backendpool-0"), + ID: to.Ptr("backendpool-0"), }, { - ID: ptr.To("backendpool-1"), + ID: to.Ptr("backendpool-1"), }, }, }, @@ -1907,12 +1907,12 @@ func TestDeleteBackendPoolFromIPConfig(t *testing.T) { VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ { - Name: ptr.To("config-0"), + Name: to.Ptr("config-0"), VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ - Primary: ptr.To(true), + Primary: to.Ptr(true), LoadBalancerBackendAddressPools: &[]compute.SubResource{ { - ID: ptr.To("backendpool-1"), + ID: to.Ptr("backendpool-1"), }, }, }, @@ -1929,12 +1929,12 @@ func TestDeleteBackendPoolFromIPConfig(t *testing.T) { VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ { - Name: ptr.To("config-0"), + Name: to.Ptr("config-0"), VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ - Primary: ptr.To(true), + Primary: to.Ptr(true), LoadBalancerBackendAddressPools: &[]compute.SubResource{ { - ID: ptr.To("backendpool-1"), + ID: to.Ptr("backendpool-1"), }, }, }, @@ -1946,12 +1946,12 @@ func TestDeleteBackendPoolFromIPConfig(t *testing.T) { VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ { - Name: ptr.To("config-0"), + Name: to.Ptr("config-0"), VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ - Primary: ptr.To(true), + Primary: to.Ptr(true), LoadBalancerBackendAddressPools: &[]compute.SubResource{ { - ID: ptr.To("backendpool-1"), + ID: to.Ptr("backendpool-1"), }, }, }, @@ -1968,23 +1968,23 @@ func TestDeleteBackendPoolFromIPConfig(t *testing.T) { VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ { - Name: ptr.To("config-0"), + Name: to.Ptr("config-0"), VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ - Primary: ptr.To(true), + Primary: to.Ptr(true), LoadBalancerBackendAddressPools: &[]compute.SubResource{ { - ID: ptr.To("backendpool-1"), + ID: to.Ptr("backendpool-1"), }, }, }, }, { - Name: ptr.To("config-1"), + Name: to.Ptr("config-1"), VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ - Primary: ptr.To(false), + Primary: to.Ptr(false), LoadBalancerBackendAddressPools: &[]compute.SubResource{ { - ID: ptr.To("backendpool-0-IPv6"), + ID: to.Ptr("backendpool-0-IPv6"), }, }, PrivateIPAddressVersion: compute.IPv6, @@ -1997,20 +1997,20 @@ func TestDeleteBackendPoolFromIPConfig(t *testing.T) { VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ { - Name: ptr.To("config-0"), + Name: to.Ptr("config-0"), VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ - Primary: ptr.To(true), + Primary: to.Ptr(true), LoadBalancerBackendAddressPools: &[]compute.SubResource{ { - ID: ptr.To("backendpool-1"), + ID: to.Ptr("backendpool-1"), }, }, }, }, { - Name: ptr.To("config-1"), + Name: to.Ptr("config-1"), VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ - Primary: ptr.To(false), + Primary: to.Ptr(false), LoadBalancerBackendAddressPools: &[]compute.SubResource{}, PrivateIPAddressVersion: compute.IPv6, }, @@ -2027,15 +2027,15 @@ func TestDeleteBackendPoolFromIPConfig(t *testing.T) { VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ { - Name: ptr.To("config-0"), + Name: to.Ptr("config-0"), VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ - Primary: ptr.To(false), + Primary: to.Ptr(false), }, }, { - Name: ptr.To("config-1"), + Name: to.Ptr("config-1"), VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ - Primary: ptr.To(false), + Primary: to.Ptr(false), }, }, }, @@ -2045,15 +2045,15 @@ func TestDeleteBackendPoolFromIPConfig(t *testing.T) { VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ { - Name: ptr.To("config-0"), + Name: to.Ptr("config-0"), VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ - Primary: ptr.To(false), + Primary: to.Ptr(false), }, }, { - Name: ptr.To("config-1"), + Name: to.Ptr("config-1"), VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ - Primary: ptr.To(false), + Primary: to.Ptr(false), }, }, }, @@ -2069,16 +2069,16 @@ func TestDeleteBackendPoolFromIPConfig(t *testing.T) { VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ { - Name: ptr.To("config-0"), + Name: to.Ptr("config-0"), VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ - Primary: ptr.To(true), + Primary: to.Ptr(true), PrivateIPAddressVersion: compute.IPv4, }, }, { - Name: ptr.To("config-1"), + Name: to.Ptr("config-1"), VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ - Primary: ptr.To(false), + Primary: to.Ptr(false), PrivateIPAddressVersion: compute.IPv4, }, }, @@ -2089,16 +2089,16 @@ func TestDeleteBackendPoolFromIPConfig(t *testing.T) { VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ { - Name: ptr.To("config-0"), + Name: to.Ptr("config-0"), VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ - Primary: ptr.To(true), + Primary: to.Ptr(true), PrivateIPAddressVersion: compute.IPv4, }, }, { - Name: ptr.To("config-1"), + Name: to.Ptr("config-1"), VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ - Primary: ptr.To(false), + Primary: to.Ptr(false), PrivateIPAddressVersion: compute.IPv4, }, }, @@ -2184,32 +2184,32 @@ func TestEnsureHostInPool(t *testing.T) { expectedVMSSName: testVMSSName, expectedInstanceID: "0", expectedVMSSVM: &compute.VirtualMachineScaleSetVM{ - Location: ptr.To("westus"), + Location: to.Ptr("westus"), VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ NetworkProfileConfiguration: &compute.VirtualMachineScaleSetVMNetworkProfileConfiguration{ NetworkInterfaceConfigurations: &[]compute.VirtualMachineScaleSetNetworkConfiguration{ { - Name: ptr.To("vmss-nic"), - ID: ptr.To("fakeNetworkConfiguration"), + Name: to.Ptr("vmss-nic"), + ID: to.Ptr("fakeNetworkConfiguration"), VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ { - Name: ptr.To("ipconfig1"), + Name: to.Ptr("ipconfig1"), VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ - Primary: ptr.To(true), + Primary: to.Ptr(true), LoadBalancerBackendAddressPools: &[]compute.SubResource{ { - ID: ptr.To(testLBBackendpoolID0), + ID: to.Ptr(testLBBackendpoolID0), }, { - ID: ptr.To("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lb-internal/backendAddressPools/backendpool-1"), + ID: to.Ptr("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lb-internal/backendAddressPools/backendpool-1"), }, }, PrivateIPAddressVersion: compute.IPv4, }, }, }, - Primary: ptr.To(true), + Primary: to.Ptr(true), }, }, }, @@ -2254,7 +2254,7 @@ func TestEnsureHostInPool(t *testing.T) { } if test.isVMNotActive { (*expectedVMSSVMs[0].InstanceView.Statuses)[0] = compute.InstanceViewStatus{ - Code: ptr.To("PowerState/deallocated"), + Code: to.Ptr("PowerState/deallocated"), } } mockVMSSVMClient := ss.VirtualMachineScaleSetVMsClient.(*mockvmssvmclient.MockInterface) @@ -2555,7 +2555,7 @@ func TestEnsureVMSSInPool(t *testing.T) { expectedVMSS := buildTestOSSpecificVMSSWithLB(testVMSSName, "vmss-vm-", []string{testLBBackendpoolID0}, test.os, test.setIPv6Config) if test.isVMSSDeallocating { - expectedVMSS.ProvisioningState = ptr.To(consts.ProvisionStateDeleting) + expectedVMSS.ProvisioningState = to.Ptr(consts.ProvisionStateDeleting) } if test.isVMSSNilNICConfig { expectedVMSS.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations = nil @@ -2655,7 +2655,7 @@ func TestEnsureHostsInPool(t *testing.T) { assert.NoError(t, err, test.description) ss.LoadBalancerSku = consts.LoadBalancerSkuStandard - ss.ExcludeMasterFromStandardLB = ptr.To(true) + ss.ExcludeMasterFromStandardLB = to.Ptr(true) expectedVMSS := buildTestVMSSWithLB(testVMSSName, "vmss-vm-", []string{testLBBackendpoolID0}, false) mockVMSSClient := ss.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface) @@ -2714,33 +2714,33 @@ func TestEnsureBackendPoolDeletedFromNodeCommon(t *testing.T) { expectedVMSSName: testVMSSName, expectedInstanceID: "0", expectedVMSSVM: &compute.VirtualMachineScaleSetVM{ - Location: ptr.To("westus"), + Location: to.Ptr("westus"), VirtualMachineScaleSetVMProperties: &compute.VirtualMachineScaleSetVMProperties{ NetworkProfileConfiguration: &compute.VirtualMachineScaleSetVMNetworkProfileConfiguration{ NetworkInterfaceConfigurations: &[]compute.VirtualMachineScaleSetNetworkConfiguration{ { - Name: ptr.To("vmss-nic"), - ID: ptr.To("fakeNetworkConfiguration"), + Name: to.Ptr("vmss-nic"), + ID: to.Ptr("fakeNetworkConfiguration"), VirtualMachineScaleSetNetworkConfigurationProperties: &compute.VirtualMachineScaleSetNetworkConfigurationProperties{ IPConfigurations: &[]compute.VirtualMachineScaleSetIPConfiguration{ { - Name: ptr.To("ipconfig1"), + Name: to.Ptr("ipconfig1"), VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ - Primary: ptr.To(true), + Primary: to.Ptr(true), LoadBalancerBackendAddressPools: &[]compute.SubResource{}, PrivateIPAddressVersion: compute.IPv4, }, }, { - Name: ptr.To("ipconfigv6"), + Name: to.Ptr("ipconfigv6"), VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ - Primary: ptr.To(false), + Primary: to.Ptr(false), LoadBalancerBackendAddressPools: &[]compute.SubResource{}, PrivateIPAddressVersion: compute.IPv6, }, }, }, - Primary: ptr.To(true), + Primary: to.Ptr(true), }, }, }, @@ -2771,7 +2771,7 @@ func TestEnsureBackendPoolDeletedFromNodeCommon(t *testing.T) { } if test.isVMNotActive { (*expectedVMSSVMs[0].InstanceView.Statuses)[0] = compute.InstanceViewStatus{ - Code: ptr.To("PowerState/deallocated"), + Code: to.Ptr("PowerState/deallocated"), } } mockVMSSVMClient := ss.VirtualMachineScaleSetVMsClient.(*mockvmssvmclient.MockInterface) @@ -2854,7 +2854,7 @@ func TestEnsureBackendPoolDeletedFromVMSS(t *testing.T) { expectedVMSS := buildTestVMSSWithLB(testVMSSName, "vmss-vm-", []string{testLBBackendpoolID0}, false) if test.isVMSSDeallocating { - expectedVMSS.ProvisioningState = ptr.To(consts.ProvisionStateDeleting) + expectedVMSS.ProvisioningState = to.Ptr(consts.ProvisionStateDeleting) } if test.isVMSSNilNICConfig { expectedVMSS.VirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations = nil @@ -2899,25 +2899,25 @@ func TestEnsureBackendPoolDeleted(t *testing.T) { backendpoolID: testLBBackendpoolID0, backendAddressPools: &[]network.BackendAddressPool{ { - ID: ptr.To(testLBBackendpoolID0), + ID: to.Ptr(testLBBackendpoolID0), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ BackendIPConfigurations: &[]network.InterfaceIPConfiguration{ { - Name: ptr.To("ip-1"), - ID: ptr.To("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss/virtualMachines/0/networkInterfaces/nic"), + Name: to.Ptr("ip-1"), + ID: to.Ptr("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss/virtualMachines/0/networkInterfaces/nic"), }, { - Name: ptr.To("ip-2"), + Name: to.Ptr("ip-2"), }, { - Name: ptr.To("ip-3"), - ID: ptr.To("/invalid/id"), + Name: to.Ptr("ip-3"), + ID: to.Ptr("/invalid/id"), }, }, }, }, { - ID: ptr.To(testLBBackendpoolID1), + ID: to.Ptr(testLBBackendpoolID1), }, }, expectedVMSSVMPutTimes: 1, @@ -2927,18 +2927,18 @@ func TestEnsureBackendPoolDeleted(t *testing.T) { backendpoolID: testLBBackendpoolID0, backendAddressPools: &[]network.BackendAddressPool{ { - ID: ptr.To(testLBBackendpoolID0), + ID: to.Ptr(testLBBackendpoolID0), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ BackendIPConfigurations: &[]network.InterfaceIPConfiguration{ { - Name: ptr.To("ip-1"), - ID: ptr.To("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss/virtualMachines/0/networkInterfaces/nic"), + Name: to.Ptr("ip-1"), + ID: to.Ptr("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss/virtualMachines/0/networkInterfaces/nic"), }, }, }, }, { - ID: ptr.To(testLBBackendpoolID1), + ID: to.Ptr(testLBBackendpoolID1), }, }, expectedVMSSVMPutTimes: 1, @@ -2950,18 +2950,18 @@ func TestEnsureBackendPoolDeleted(t *testing.T) { backendpoolID: testLBBackendpoolID0, backendAddressPools: &[]network.BackendAddressPool{ { - ID: ptr.To(testLBBackendpoolID0), + ID: to.Ptr(testLBBackendpoolID0), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ BackendIPConfigurations: &[]network.InterfaceIPConfiguration{ { - Name: ptr.To("ip-1"), - ID: ptr.To("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss/virtualMachines/6/networkInterfaces/nic"), + Name: to.Ptr("ip-1"), + ID: to.Ptr("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss/virtualMachines/6/networkInterfaces/nic"), }, }, }, }, { - ID: ptr.To(testLBBackendpoolID1), + ID: to.Ptr(testLBBackendpoolID1), }, }, }, @@ -3009,34 +3009,34 @@ func TestEnsureBackendPoolDeletedConcurrently(t *testing.T) { backendAddressPools := &[]network.BackendAddressPool{ { - ID: ptr.To(testLBBackendpoolID0), + ID: to.Ptr(testLBBackendpoolID0), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ BackendIPConfigurations: &[]network.InterfaceIPConfiguration{ { - Name: ptr.To("ip-1"), - ID: ptr.To("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss-0/virtualMachines/0/networkInterfaces/nic"), + Name: to.Ptr("ip-1"), + ID: to.Ptr("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss-0/virtualMachines/0/networkInterfaces/nic"), }, }, }, }, { - ID: ptr.To(testLBBackendpoolID1), + ID: to.Ptr(testLBBackendpoolID1), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ BackendIPConfigurations: &[]network.InterfaceIPConfiguration{ { - Name: ptr.To("ip-1"), - ID: ptr.To("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss-1/virtualMachines/0/networkInterfaces/nic"), + Name: to.Ptr("ip-1"), + ID: to.Ptr("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmss-1/virtualMachines/0/networkInterfaces/nic"), }, }, }, }, { - ID: ptr.To(testLBBackendpoolID2), + ID: to.Ptr(testLBBackendpoolID2), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ BackendIPConfigurations: &[]network.InterfaceIPConfiguration{ { - Name: ptr.To("ip-1"), - ID: ptr.To("/subscriptions/sub/resourceGroups/rg1/providers/Microsoft.Compute/virtualMachineScaleSets/vmss-0/virtualMachines/0/networkInterfaces/nic"), + Name: to.Ptr("ip-1"), + ID: to.Ptr("/subscriptions/sub/resourceGroups/rg1/providers/Microsoft.Compute/virtualMachineScaleSets/vmss-0/virtualMachines/0/networkInterfaces/nic"), }, }, }, @@ -3052,7 +3052,7 @@ func TestEnsureBackendPoolDeletedConcurrently(t *testing.T) { vmssVMNetworkConfigs := expectedVMSSVMs[0].NetworkProfileConfiguration vmssVMIPConfigs := (*vmssVMNetworkConfigs.NetworkInterfaceConfigurations)[0].VirtualMachineScaleSetNetworkConfigurationProperties.IPConfigurations lbBackendpools := (*vmssVMIPConfigs)[0].LoadBalancerBackendAddressPools - *lbBackendpools = append(*lbBackendpools, compute.SubResource{ID: ptr.To(testLBBackendpoolID1)}) + *lbBackendpools = append(*lbBackendpools, compute.SubResource{ID: to.Ptr(testLBBackendpoolID1)}) } mockVMClient := ss.VirtualMachinesClient.(*mockvmclient.MockInterface) @@ -3106,8 +3106,8 @@ func TestGetNodeCIDRMasksByProviderID(t *testing.T) { description: "GetNodeCIDRMaksByProviderID should return the correct mask sizes", providerID: "azure:///subscriptions/sub/resourceGroups/rg1/providers/Microsoft.Compute/virtualMachineScaleSets/vmss/virtualMachines/0", tags: map[string]*string{ - consts.VMSetCIDRIPV4TagKey: ptr.To("24"), - consts.VMSetCIDRIPV6TagKey: ptr.To("64"), + consts.VMSetCIDRIPV4TagKey: to.Ptr("24"), + consts.VMSetCIDRIPV6TagKey: to.Ptr("64"), }, expectedIPV4MaskSize: 24, expectedIPV6MaskSize: 64, @@ -3116,7 +3116,7 @@ func TestGetNodeCIDRMasksByProviderID(t *testing.T) { description: "GetNodeCIDRMaksByProviderID should return the correct mask sizes even if some of the tags are not specified", providerID: "azure:///subscriptions/sub/resourceGroups/rg1/providers/Microsoft.Compute/virtualMachineScaleSets/vmss/virtualMachines/0", tags: map[string]*string{ - consts.VMSetCIDRIPV4TagKey: ptr.To("24"), + consts.VMSetCIDRIPV4TagKey: to.Ptr("24"), }, expectedIPV4MaskSize: 24, }, @@ -3124,8 +3124,8 @@ func TestGetNodeCIDRMasksByProviderID(t *testing.T) { description: "GetNodeCIDRMaksByProviderID should not fail even if some of the tag is invalid", providerID: "azure:///subscriptions/sub/resourceGroups/rg1/providers/Microsoft.Compute/virtualMachineScaleSets/vmss/virtualMachines/0", tags: map[string]*string{ - consts.VMSetCIDRIPV4TagKey: ptr.To("abc"), - consts.VMSetCIDRIPV6TagKey: ptr.To("64"), + consts.VMSetCIDRIPV4TagKey: to.Ptr("abc"), + consts.VMSetCIDRIPV6TagKey: to.Ptr("64"), }, expectedIPV6MaskSize: 64, }, @@ -3135,7 +3135,7 @@ func TestGetNodeCIDRMasksByProviderID(t *testing.T) { assert.NoError(t, err) expectedVMSS := compute.VirtualMachineScaleSet{ - Name: ptr.To("vmss"), + Name: to.Ptr("vmss"), Tags: tc.tags, VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{ OrchestrationMode: compute.Uniform, @@ -3164,24 +3164,24 @@ func TestGetAgentPoolVMSetNamesMixedInstances(t *testing.T) { existingVMs := []compute.VirtualMachine{ { - Name: ptr.To("vm-0"), + Name: to.Ptr("vm-0"), VirtualMachineProperties: &compute.VirtualMachineProperties{ OsProfile: &compute.OSProfile{ - ComputerName: ptr.To("vm-0"), + ComputerName: to.Ptr("vm-0"), }, AvailabilitySet: &compute.SubResource{ - ID: ptr.To("vmas-0"), + ID: to.Ptr("vmas-0"), }, }, }, { - Name: ptr.To("vm-1"), + Name: to.Ptr("vm-1"), VirtualMachineProperties: &compute.VirtualMachineProperties{ OsProfile: &compute.OSProfile{ - ComputerName: ptr.To("vm-1"), + ComputerName: to.Ptr("vm-1"), }, AvailabilitySet: &compute.SubResource{ - ID: ptr.To("vmas-1"), + ID: to.Ptr("vmas-1"), }, }, }, @@ -3280,9 +3280,9 @@ func TestScaleSet_VMSSBatchSize(t *testing.T) { ss.Cloud.PutVMSSVMBatchSize = BatchSize scaleSet := compute.VirtualMachineScaleSet{ - Name: ptr.To("foo"), + Name: to.Ptr("foo"), Tags: map[string]*string{ - consts.VMSSTagForBatchOperation: ptr.To(""), + consts.VMSSTagForBatchOperation: to.Ptr(""), }, VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{ OrchestrationMode: compute.Uniform, @@ -3292,7 +3292,7 @@ func TestScaleSet_VMSSBatchSize(t *testing.T) { mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()). Return([]compute.VirtualMachineScaleSet{scaleSet}, nil) - batchSize, err := ss.VMSSBatchSize(context.TODO(), ptr.Deref(scaleSet.Name, "")) + batchSize, err := ss.VMSSBatchSize(context.TODO(), lo.FromPtrOr(scaleSet.Name, "")) assert.NoError(t, err) assert.Equal(t, BatchSize, batchSize) }) @@ -3305,7 +3305,7 @@ func TestScaleSet_VMSSBatchSize(t *testing.T) { ss.Cloud.PutVMSSVMBatchSize = BatchSize scaleSet := compute.VirtualMachineScaleSet{ - Name: ptr.To("bar"), + Name: to.Ptr("bar"), VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{ OrchestrationMode: compute.Uniform, }, @@ -3314,7 +3314,7 @@ func TestScaleSet_VMSSBatchSize(t *testing.T) { mockVMSSClient.EXPECT().List(gomock.Any(), gomock.Any()). Return([]compute.VirtualMachineScaleSet{scaleSet}, nil) - batchSize, err := ss.VMSSBatchSize(context.TODO(), ptr.Deref(scaleSet.Name, "")) + batchSize, err := ss.VMSSBatchSize(context.TODO(), lo.FromPtrOr(scaleSet.Name, "")) assert.NoError(t, err) assert.Equal(t, 0, batchSize) }) diff --git a/pkg/provider/azure_vmssflex.go b/pkg/provider/azure_vmssflex.go index 666fe2948a..448c2111cc 100644 --- a/pkg/provider/azure_vmssflex.go +++ b/pkg/provider/azure_vmssflex.go @@ -25,15 +25,15 @@ import ( "sync" "sync/atomic" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - + "github.com/samber/lo" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/types" utilerrors "k8s.io/apimachinery/pkg/util/errors" cloudprovider "k8s.io/cloud-provider" "k8s.io/klog/v2" - "k8s.io/utils/ptr" azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" @@ -171,7 +171,7 @@ func (fs *FlexScaleSet) GetVMSetNames(ctx context.Context, service *v1.Service, // providerID example: // azure:///subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/flexprofile-mp-0_df53ee36 // Different from vmas where vm name is always equal to nodeName, we need to further map vmName to actual nodeName in vmssflex. -// Note: nodeName is always equal ptr.Derefs.ToLower(*vm.OsProfile.ComputerName, "") +// Note: nodeName is always equal lo.FromPtrOrs.ToLower(*vm.OsProfile.ComputerName, "") func (fs *FlexScaleSet) GetNodeNameByProviderID(ctx context.Context, providerID string) (types.NodeName, error) { // NodeName is part of providerID for standard instances. matches := providerIDRE.FindStringSubmatch(providerID) @@ -239,10 +239,10 @@ func (fs *FlexScaleSet) GetZoneByNodeName(ctx context.Context, name string) (clo return cloudprovider.Zone{}, fmt.Errorf("failed to parse zone %q: %w", zones, err) } - failureDomain = fs.makeZone(ptr.Deref(vm.Location, ""), zoneID) + failureDomain = fs.makeZone(lo.FromPtrOr(vm.Location, ""), zoneID) } else if vm.VirtualMachineProperties.InstanceView != nil && vm.VirtualMachineProperties.InstanceView.PlatformFaultDomain != nil { // Availability zone is not used for the node, falling back to fault domain. - failureDomain = strconv.Itoa(int(ptr.Deref(vm.VirtualMachineProperties.InstanceView.PlatformFaultDomain, 0))) + failureDomain = strconv.Itoa(int(lo.FromPtrOr(vm.VirtualMachineProperties.InstanceView.PlatformFaultDomain, 0))) } else { err = fmt.Errorf("failed to get zone info") klog.Errorf("GetZoneByNodeName: got unexpected error %v", err) @@ -251,7 +251,7 @@ func (fs *FlexScaleSet) GetZoneByNodeName(ctx context.Context, name string) (clo zone := cloudprovider.Zone{ FailureDomain: strings.ToLower(failureDomain), - Region: strings.ToLower(ptr.Deref(vm.Location, "")), + Region: strings.ToLower(lo.FromPtrOr(vm.Location, "")), } return zone, nil } @@ -267,7 +267,7 @@ func (fs *FlexScaleSet) GetProvisioningStateByNodeName(ctx context.Context, name return provisioningState, nil } - return ptr.Deref(vm.VirtualMachineProperties.ProvisioningState, ""), nil + return lo.FromPtrOr(vm.VirtualMachineProperties.ProvisioningState, ""), nil } // GetPowerStatusByNodeName returns the powerState for the specified node. @@ -278,7 +278,7 @@ func (fs *FlexScaleSet) GetPowerStatusByNodeName(ctx context.Context, name strin } if vm.InstanceView != nil { - return vmutil.GetVMPowerState(ptr.Deref(vm.Name, ""), vm.InstanceView.Statuses), nil + return vmutil.GetVMPowerState(lo.FromPtrOr(vm.Name, ""), vm.InstanceView.Statuses), nil } // vm.InstanceView or vm.InstanceView.Statuses are nil when the VM is under deleting. @@ -428,15 +428,15 @@ func (fs *FlexScaleSet) GetNodeCIDRMasksByProviderID(ctx context.Context, provid var ipv4Mask, ipv6Mask int if v4, ok := vmssFlex.Tags[consts.VMSetCIDRIPV4TagKey]; ok && v4 != nil { - ipv4Mask, err = strconv.Atoi(ptr.Deref(v4, "")) + ipv4Mask, err = strconv.Atoi(lo.FromPtrOr(v4, "")) if err != nil { - klog.Errorf("GetNodeCIDRMasksByProviderID: error when paring the value of the ipv4 mask size %s: %v", ptr.Deref(v4, ""), err) + klog.Errorf("GetNodeCIDRMasksByProviderID: error when paring the value of the ipv4 mask size %s: %v", lo.FromPtrOr(v4, ""), err) } } if v6, ok := vmssFlex.Tags[consts.VMSetCIDRIPV6TagKey]; ok && v6 != nil { - ipv6Mask, err = strconv.Atoi(ptr.Deref(v6, "")) + ipv6Mask, err = strconv.Atoi(lo.FromPtrOr(v6, "")) if err != nil { - klog.Errorf("GetNodeCIDRMasksByProviderID: error when paring the value of the ipv6 mask size%s: %v", ptr.Deref(v6, ""), err) + klog.Errorf("GetNodeCIDRMasksByProviderID: error when paring the value of the ipv6 mask size%s: %v", lo.FromPtrOr(v6, ""), err) } } @@ -532,7 +532,7 @@ func (fs *FlexScaleSet) EnsureHostInPool(ctx context.Context, service *v1.Servic newBackendPools = append(newBackendPools, network.BackendAddressPool{ - ID: ptr.To(backendPoolID), + ID: to.Ptr(backendPoolID), }) primaryIPConfig.LoadBalancerBackendAddressPools = &newBackendPools @@ -674,7 +674,7 @@ func (fs *FlexScaleSet) ensureVMSSFlexInPool(ctx context.Context, _ *v1.Service, // Compose a new vmss with added backendPoolID. loadBalancerBackendAddressPools = append(loadBalancerBackendAddressPools, compute.SubResource{ - ID: ptr.To(backendPoolID), + ID: to.Ptr(backendPoolID), }) primaryIPConfig.LoadBalancerBackendAddressPools = &loadBalancerBackendAddressPools newVMSS := compute.VirtualMachineScaleSet{ @@ -765,7 +765,7 @@ func (fs *FlexScaleSet) ensureBackendPoolDeletedFromVmssFlex(ctx context.Context vmssFlexes := cached.(*sync.Map) vmssFlexes.Range(func(_, value interface{}) bool { vmssFlex := value.(*compute.VirtualMachineScaleSet) - vmssNamesMap[ptr.Deref(vmssFlex.Name, "")] = true + vmssNamesMap[lo.FromPtrOr(vmssFlex.Name, "")] = true return true }) } else { @@ -876,7 +876,7 @@ func (fs *FlexScaleSet) EnsureBackendPoolDeleted(ctx context.Context, service *v ipConfigurationIDs := []string{} for _, backendPool := range *backendAddressPools { for _, backendPoolID := range backendPoolIDs { - if strings.EqualFold(ptr.Deref(backendPool.ID, ""), backendPoolID) && backendPool.BackendAddressPoolPropertiesFormat != nil && backendPool.BackendIPConfigurations != nil { + if strings.EqualFold(lo.FromPtrOr(backendPool.ID, ""), backendPoolID) && backendPool.BackendAddressPoolPropertiesFormat != nil && backendPool.BackendIPConfigurations != nil { for _, ipConf := range *backendPool.BackendIPConfigurations { if ipConf.ID == nil { continue @@ -962,7 +962,7 @@ func (fs *FlexScaleSet) ensureBackendPoolDeletedFromNode(ctx context.Context, vm } if nic.InterfacePropertiesFormat != nil && nic.InterfacePropertiesFormat.IPConfigurations != nil { - nicName := ptr.Deref(nic.Name, "") + nicName := lo.FromPtrOr(nic.Name, "") nics[nicName] = nic } } @@ -971,7 +971,7 @@ func (fs *FlexScaleSet) ensureBackendPoolDeletedFromNode(ctx context.Context, vm nic := nic newIPConfigs := *nic.IPConfigurations for j, ipConf := range newIPConfigs { - if !ptr.Deref(ipConf.Primary, false) { + if !lo.FromPtrOr(ipConf.Primary, false) { continue } // found primary ip configuration @@ -980,7 +980,7 @@ func (fs *FlexScaleSet) ensureBackendPoolDeletedFromNode(ctx context.Context, vm for k := len(newLBAddressPools) - 1; k >= 0; k-- { pool := newLBAddressPools[k] for _, backendPoolID := range backendPoolIDs { - if strings.EqualFold(ptr.Deref(pool.ID, ""), backendPoolID) { + if strings.EqualFold(lo.FromPtrOr(pool.ID, ""), backendPoolID) { newLBAddressPools = append(newLBAddressPools[:k], newLBAddressPools[k+1:]...) } } @@ -991,10 +991,10 @@ func (fs *FlexScaleSet) ensureBackendPoolDeletedFromNode(ctx context.Context, vm nic.IPConfigurations = &newIPConfigs nicUpdaters = append(nicUpdaters, func() error { - klog.V(2).Infof("EnsureBackendPoolDeleted begins to CreateOrUpdate for NIC(%s, %s) with backendPoolIDs %q", fs.ResourceGroup, ptr.Deref(nic.Name, ""), backendPoolIDs) - rerr := fs.InterfacesClient.CreateOrUpdate(ctx, fs.ResourceGroup, ptr.Deref(nic.Name, ""), nic) + klog.V(2).Infof("EnsureBackendPoolDeleted begins to CreateOrUpdate for NIC(%s, %s) with backendPoolIDs %q", fs.ResourceGroup, lo.FromPtrOr(nic.Name, ""), backendPoolIDs) + rerr := fs.InterfacesClient.CreateOrUpdate(ctx, fs.ResourceGroup, lo.FromPtrOr(nic.Name, ""), nic) if rerr != nil { - klog.Errorf("EnsureBackendPoolDeleted CreateOrUpdate for NIC(%s, %s) failed with error %v", fs.ResourceGroup, ptr.Deref(nic.Name, ""), rerr.Error()) + klog.Errorf("EnsureBackendPoolDeleted CreateOrUpdate for NIC(%s, %s) failed with error %v", fs.ResourceGroup, lo.FromPtrOr(nic.Name, ""), rerr.Error()) return rerr.Error() } nicUpdated.Store(true) diff --git a/pkg/provider/azure_vmssflex_cache.go b/pkg/provider/azure_vmssflex_cache.go index 59c423a8ad..b605924b27 100644 --- a/pkg/provider/azure_vmssflex_cache.go +++ b/pkg/provider/azure_vmssflex_cache.go @@ -25,10 +25,9 @@ import ( "time" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - + "github.com/samber/lo" cloudprovider "k8s.io/cloud-provider" "k8s.io/klog/v2" - "k8s.io/utils/ptr" azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" @@ -186,11 +185,11 @@ func (fs *FlexScaleSet) getNodeVmssFlexID(ctx context.Context, nodeName string) vmssFlexes.Range(func(key, value interface{}) bool { vmssFlexID := key.(string) vmssFlex := value.(*compute.VirtualMachineScaleSet) - vmssPrefix := ptr.Deref(vmssFlex.Name, "") + vmssPrefix := lo.FromPtrOr(vmssFlex.Name, "") if vmssFlex.VirtualMachineProfile != nil && vmssFlex.VirtualMachineProfile.OsProfile != nil && vmssFlex.VirtualMachineProfile.OsProfile.ComputerNamePrefix != nil { - vmssPrefix = ptr.Deref(vmssFlex.VirtualMachineProfile.OsProfile.ComputerNamePrefix, "") + vmssPrefix = lo.FromPtrOr(vmssFlex.VirtualMachineProfile.OsProfile.ComputerNamePrefix, "") } if strings.EqualFold(vmssPrefix, nodeName[:len(nodeName)-6]) { // we should check this vmss first since nodeName and vmssFlex.Name or diff --git a/pkg/provider/azure_vmssflex_cache_test.go b/pkg/provider/azure_vmssflex_cache_test.go index 3bf2e0b2f5..1ede4e9242 100644 --- a/pkg/provider/azure_vmssflex_cache_test.go +++ b/pkg/provider/azure_vmssflex_cache_test.go @@ -22,13 +22,11 @@ import ( "net/http" "testing" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" "github.com/stretchr/testify/assert" - "go.uber.org/mock/gomock" - cloudprovider "k8s.io/cloud-provider" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmclient/mockvmclient" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmssclient/mockvmssclient" @@ -45,13 +43,13 @@ var ( VMName: "testvm1", VMID: "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/testvm1", ComputerName: "vmssflex1000001", - ProvisioningState: ptr.To("Succeeded"), + ProvisioningState: to.Ptr("Succeeded"), VmssFlexID: testVmssFlex1ID, Zones: &[]string{"1", "2", "3"}, - PlatformFaultDomain: ptr.To(int32(1)), + PlatformFaultDomain: to.Ptr(int32(1)), Status: &[]compute.InstanceViewStatus{ { - Code: ptr.To("PowerState/running"), + Code: to.Ptr("PowerState/running"), }, }, NicID: "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/testvm1-nic", @@ -63,13 +61,13 @@ var ( VMName: "testvm2", VMID: "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/testvm2", ComputerName: "vmssflex1000002", - ProvisioningState: ptr.To("Succeeded"), + ProvisioningState: to.Ptr("Succeeded"), VmssFlexID: testVmssFlex1ID, Zones: nil, - PlatformFaultDomain: ptr.To(int32(1)), + PlatformFaultDomain: to.Ptr(int32(1)), Status: &[]compute.InstanceViewStatus{ { - Code: ptr.To("PowerState/running"), + Code: to.Ptr("PowerState/running"), }, }, NicID: "/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/testvm2-nic", @@ -112,12 +110,12 @@ func genreateTestVmssFlexList() []compute.VirtualMachineScaleSet { func genreteTestVmssFlex(vmssFlexName string, testVmssFlexID string) compute.VirtualMachineScaleSet { return compute.VirtualMachineScaleSet{ - ID: ptr.To(testVmssFlexID), - Name: ptr.To(vmssFlexName), + ID: to.Ptr(testVmssFlexID), + Name: to.Ptr(vmssFlexName), VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{ VirtualMachineProfile: &compute.VirtualMachineScaleSetVMProfile{ OsProfile: &compute.VirtualMachineScaleSetOSProfile{ - ComputerNamePrefix: ptr.To(vmssFlexName), + ComputerNamePrefix: to.Ptr(vmssFlexName), }, NetworkProfile: &compute.VirtualMachineScaleSetNetworkProfile{ NetworkInterfaceConfigurations: &[]compute.VirtualMachineScaleSetNetworkConfiguration{ @@ -128,10 +126,10 @@ func genreteTestVmssFlex(vmssFlexName string, testVmssFlexID string) compute.Vir VirtualMachineScaleSetIPConfigurationProperties: &compute.VirtualMachineScaleSetIPConfigurationProperties{ LoadBalancerBackendAddressPools: &[]compute.SubResource{ { - ID: ptr.To(testBackendPoolID0), + ID: to.Ptr(testBackendPoolID0), }, }, - Primary: ptr.To(true), + Primary: to.Ptr(true), }, }, }, @@ -143,8 +141,8 @@ func genreteTestVmssFlex(vmssFlexName string, testVmssFlexID string) compute.Vir OrchestrationMode: compute.Flexible, }, Tags: map[string]*string{ - consts.VMSetCIDRIPV4TagKey: ptr.To("24"), - consts.VMSetCIDRIPV6TagKey: ptr.To("64"), + consts.VMSetCIDRIPV4TagKey: to.Ptr("24"), + consts.VMSetCIDRIPV6TagKey: to.Ptr("64"), }, } } @@ -163,31 +161,31 @@ type VmssFlexTestVMSpec struct { func generateVmssFlexTestVMWithoutInstanceView(spec VmssFlexTestVMSpec) (testVMWithoutInstanceView compute.VirtualMachine) { return compute.VirtualMachine{ - Name: ptr.To(spec.VMName), - ID: ptr.To(spec.VMID), + Name: to.Ptr(spec.VMName), + ID: to.Ptr(spec.VMID), VirtualMachineProperties: &compute.VirtualMachineProperties{ OsProfile: &compute.OSProfile{ - ComputerName: ptr.To(spec.ComputerName), + ComputerName: to.Ptr(spec.ComputerName), }, ProvisioningState: spec.ProvisioningState, VirtualMachineScaleSet: &compute.SubResource{ - ID: ptr.To(spec.VmssFlexID), + ID: to.Ptr(spec.VmssFlexID), }, StorageProfile: &compute.StorageProfile{ OsDisk: &compute.OSDisk{ - Name: ptr.To("osdisk" + spec.VMName), + Name: to.Ptr("osdisk" + spec.VMName), ManagedDisk: &compute.ManagedDiskParameters{ - ID: ptr.To("ManagedID" + spec.VMName), + ID: to.Ptr("ManagedID" + spec.VMName), DiskEncryptionSet: &compute.DiskEncryptionSetParameters{ - ID: ptr.To("DiskEncryptionSetID" + spec.VMName), + ID: to.Ptr("DiskEncryptionSetID" + spec.VMName), }, }, }, DataDisks: &[]compute.DataDisk{ { - Lun: ptr.To(int32(1)), - Name: ptr.To("dataDisk" + spec.VMName), - ManagedDisk: &compute.ManagedDiskParameters{ID: ptr.To("uri")}, + Lun: to.Ptr(int32(1)), + Name: to.Ptr("dataDisk" + spec.VMName), + ManagedDisk: &compute.ManagedDiskParameters{ID: to.Ptr("uri")}, }, }, }, @@ -197,20 +195,20 @@ func generateVmssFlexTestVMWithoutInstanceView(spec VmssFlexTestVMSpec) (testVMW NetworkProfile: &compute.NetworkProfile{ NetworkInterfaces: &[]compute.NetworkInterfaceReference{ { - ID: ptr.To(spec.NicID), + ID: to.Ptr(spec.NicID), }, }, }, }, Zones: spec.Zones, - Location: ptr.To("EastUS"), + Location: to.Ptr("EastUS"), } } func generateVmssFlexTestVMWithOnlyInstanceView(spec VmssFlexTestVMSpec) (testVMWithOnlyInstanceView compute.VirtualMachine) { return compute.VirtualMachine{ - Name: ptr.To(spec.VMName), - ID: ptr.To(spec.VMID), + Name: to.Ptr(spec.VMName), + ID: to.Ptr(spec.VMID), VirtualMachineProperties: &compute.VirtualMachineProperties{ InstanceView: &compute.VirtualMachineInstanceView{ PlatformFaultDomain: spec.PlatformFaultDomain, diff --git a/pkg/provider/azure_vmssflex_test.go b/pkg/provider/azure_vmssflex_test.go index 0adc72a4ee..106f8b4ba5 100644 --- a/pkg/provider/azure_vmssflex_test.go +++ b/pkg/provider/azure_vmssflex_test.go @@ -22,17 +22,15 @@ import ( "fmt" "testing" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" "github.com/stretchr/testify/assert" - "go.uber.org/mock/gomock" - v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" cloudprovider "k8s.io/cloud-provider" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/interfaceclient/mockinterfaceclient" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmclient/mockvmclient" @@ -65,11 +63,11 @@ var ( testBackendPools = &[]network.BackendAddressPool{ { - ID: ptr.To(testBackendPoolID0), + ID: to.Ptr(testBackendPoolID0), BackendAddressPoolPropertiesFormat: &network.BackendAddressPoolPropertiesFormat{ BackendIPConfigurations: &[]network.InterfaceIPConfiguration{ { - ID: ptr.To(testIPConfigurationID), + ID: to.Ptr(testIPConfigurationID), }, }, }, @@ -83,17 +81,17 @@ var ( func generateTestNic(nicName string, isIPConfigurationsNil bool, provisioningState network.ProvisioningState, vmID string) network.Interface { result := network.Interface{ - ID: ptr.To("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/" + nicName), - Name: ptr.To(nicName), + ID: to.Ptr("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/" + nicName), + Name: to.Ptr(nicName), InterfacePropertiesFormat: &network.InterfacePropertiesFormat{ IPConfigurations: &[]network.InterfaceIPConfiguration{ { InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{ - Primary: ptr.To(true), - PrivateIPAddress: ptr.To(nicName + "testPrivateIP"), + Primary: to.Ptr(true), + PrivateIPAddress: to.Ptr(nicName + "testPrivateIP"), LoadBalancerBackendAddressPools: &[]network.BackendAddressPool{ { - ID: ptr.To(testBackendPoolID0), + ID: to.Ptr(testBackendPoolID0), }, }, }, @@ -101,7 +99,7 @@ func generateTestNic(nicName string, isIPConfigurationsNil bool, provisioningSta }, ProvisioningState: provisioningState, VirtualMachine: &network.SubResource{ - ID: ptr.To(vmID), + ID: to.Ptr(vmID), }, }, } @@ -889,7 +887,7 @@ func TestGetNodeCIDRMasksByProviderIDVmssFlex(t *testing.T) { testVMListWithOnlyInstanceView: testVMListWithOnlyInstanceView, vmListErr: nil, tags: map[string]*string{ - consts.VMSetCIDRIPV4TagKey: ptr.To("24"), + consts.VMSetCIDRIPV4TagKey: to.Ptr("24"), }, expectedNodeMaskCIDRIPv4: 24, expectedNodeMaskCIDRIPv6: 0, @@ -902,8 +900,8 @@ func TestGetNodeCIDRMasksByProviderIDVmssFlex(t *testing.T) { testVMListWithOnlyInstanceView: testVMListWithOnlyInstanceView, vmListErr: nil, tags: map[string]*string{ - consts.VMSetCIDRIPV4TagKey: ptr.To("abc"), - consts.VMSetCIDRIPV6TagKey: ptr.To("64"), + consts.VMSetCIDRIPV4TagKey: to.Ptr("abc"), + consts.VMSetCIDRIPV6TagKey: to.Ptr("64"), }, expectedNodeMaskCIDRIPv4: 0, expectedNodeMaskCIDRIPv6: 64, @@ -1252,7 +1250,7 @@ func TestEnsureVMSSFlexInPool(t *testing.T) { testVmssFlex := genreteTestVmssFlex("vmssflex1", testVmssFlex1ID) if tc.isVMSSDeallocating { - testVmssFlex.ProvisioningState = ptr.To(consts.ProvisionStateDeleting) + testVmssFlex.ProvisioningState = to.Ptr(consts.ProvisionStateDeleting) } if !tc.hasDefaultVMProfile { testVmssFlex.VirtualMachineProfile = nil @@ -1502,7 +1500,7 @@ func TestEnsureBackendPoolDeletedFromVMSetsVmssFlex(t *testing.T) { testVmssFlex := genreteTestVmssFlex("vmssflex1", testVmssFlex1ID) if tc.isVMSSDeallocating { - testVmssFlex.ProvisioningState = ptr.To(consts.ProvisionStateDeleting) + testVmssFlex.ProvisioningState = to.Ptr(consts.ProvisionStateDeleting) } if !tc.hasDefaultVMProfile { testVmssFlex.VirtualMachineProfile = nil diff --git a/pkg/provider/azure_zones_test.go b/pkg/provider/azure_zones_test.go index 7c160c0a00..19070abbf7 100644 --- a/pkg/provider/azure_zones_test.go +++ b/pkg/provider/azure_zones_test.go @@ -24,13 +24,11 @@ import ( "testing" "time" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" "github.com/stretchr/testify/assert" - "go.uber.org/mock/gomock" - cloudprovider "k8s.io/cloud-provider" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/vmclient/mockvmclient" "sigs.k8s.io/cloud-provider-azure/pkg/provider/config" @@ -214,7 +212,7 @@ func TestGetZoneByProviderID(t *testing.T) { mockVMClient := az.VirtualMachinesClient.(*mockvmclient.MockInterface) mockVMClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, "vm-0", gomock.Any()).Return(compute.VirtualMachine{ Zones: &[]string{"1"}, - Location: ptr.To("eastus"), + Location: to.Ptr("eastus"), }, nil) zone, err = az.GetZoneByProviderID(context.Background(), testAvailabilitySetNodeProviderID) assert.NoError(t, err) diff --git a/pkg/provider/loadbalancer/accesscontrol.go b/pkg/provider/loadbalancer/accesscontrol.go index 71c1ad72f9..99f4b48f3f 100644 --- a/pkg/provider/loadbalancer/accesscontrol.go +++ b/pkg/provider/loadbalancer/accesscontrol.go @@ -23,12 +23,11 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" "github.com/go-logr/logr" + "github.com/samber/lo" v1 "k8s.io/api/core/v1" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/consts" "sigs.k8s.io/cloud-provider-azure/pkg/provider/securitygroup" - fnutil "sigs.k8s.io/cloud-provider-azure/pkg/util/collectionutil" "sigs.k8s.io/cloud-provider-azure/pkg/util/iputil" ) @@ -68,7 +67,7 @@ func WithEventEmitter(emitter K8sEventEmitter) AccessControlOption { } func NewAccessControl(logger logr.Logger, svc *v1.Service, sg *armnetwork.SecurityGroup, opts ...AccessControlOption) (*AccessControl, error) { - logger = logger.WithName("AccessControl").WithValues("security-group", ptr.To(sg.Name)) + logger = logger.WithName("AccessControl").WithValues("security-group", lo.ToPtr(sg.Name)) options := defaultAccessControlOptions for _, opt := range opts { @@ -294,8 +293,8 @@ func (ac *AccessControl) CleanSecurityGroup( logger.V(10).Info("Start cleaning") var ( - ipv4Prefixes = fnutil.Map(func(addr netip.Addr) string { return addr.String() }, dstIPv4Addresses) - ipv6Prefixes = fnutil.Map(func(addr netip.Addr) string { return addr.String() }, dstIPv6Addresses) + ipv4Prefixes = lo.Map(dstIPv4Addresses, func(addr netip.Addr, _ int) string { return addr.String() }) + ipv6Prefixes = lo.Map(dstIPv6Addresses, func(addr netip.Addr, _ int) string { return addr.String() }) ) protocols := []armnetwork.SecurityRuleProtocol{ diff --git a/pkg/provider/loadbalancer/accesscontrol_test.go b/pkg/provider/loadbalancer/accesscontrol_test.go index e1eb2eb426..5e799542f0 100644 --- a/pkg/provider/loadbalancer/accesscontrol_test.go +++ b/pkg/provider/loadbalancer/accesscontrol_test.go @@ -22,16 +22,15 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" + "github.com/samber/lo" "github.com/stretchr/testify/assert" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/internal/testutil" "sigs.k8s.io/cloud-provider-azure/internal/testutil/fixture" "sigs.k8s.io/cloud-provider-azure/pkg/log" "sigs.k8s.io/cloud-provider-azure/pkg/provider/securitygroup" - fnutil "sigs.k8s.io/cloud-provider-azure/pkg/util/collectionutil" "sigs.k8s.io/cloud-provider-azure/pkg/util/iputil" ) @@ -461,12 +460,12 @@ func TestAccessControl_AllowedRanges(t *testing.T) { var ( ipv4 = ac.AllowedIPv4Ranges() ipv6 = ac.AllowedIPv6Ranges() - expectedIPv4 = fnutil.Map(func(s string) netip.Prefix { + expectedIPv4 = lo.Map(tt.expectedIPv4, func(s string, _ int) netip.Prefix { return netip.MustParsePrefix(s) - }, tt.expectedIPv4) - expectedIPv6 = fnutil.Map(func(s string) netip.Prefix { + }) + expectedIPv6 = lo.Map(tt.expectedIPv6, func(s string, _ int) netip.Prefix { return netip.MustParsePrefix(s) - }, tt.expectedIPv6) + }) ) if ipv4 == nil { ipv4 = []netip.Prefix{} @@ -502,8 +501,8 @@ func TestAccessControl_PatchSecurityGroup(t *testing.T) { assert.NoError(t, err) err = ac.PatchSecurityGroup( - fnutil.Map(func(s string) netip.Addr { return netip.MustParseAddr(s) }, dstIPv4Addresses), - fnutil.Map(func(s string) netip.Addr { return netip.MustParseAddr(s) }, dstIPv6Addresses), + lo.Map(dstIPv4Addresses, func(s string, _ int) netip.Addr { return netip.MustParseAddr(s) }), + lo.Map(dstIPv6Addresses, func(s string, _ int) netip.Addr { return netip.MustParseAddr(s) }), ) assert.NoError(t, err) @@ -1161,29 +1160,29 @@ func TestAccessControl_CleanSecurityGroup(t *testing.T) { var ( rules = []*armnetwork.SecurityRule{ { - Name: ptr.To("test-rule-0"), + Name: to.Ptr("test-rule-0"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolTCP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), SourceAddressPrefixes: to.SliceOfPtrs("src_foo", "src_bar"), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("10.0.0.1", "10.0.0.2"), DestinationPortRanges: to.SliceOfPtrs("80", "443"), - Priority: ptr.To(int32(500)), + Priority: to.Ptr(int32(500)), }, }, { - Name: ptr.To("test-rule-1"), + Name: to.Ptr("test-rule-1"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolUDP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), SourceAddressPrefixes: to.SliceOfPtrs("src_baz", "src_quo"), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("20.0.0.1", "20.0.0.2"), DestinationPortRanges: to.SliceOfPtrs("53"), - Priority: ptr.To(int32(501)), + Priority: to.Ptr(int32(501)), }, }, } @@ -1208,42 +1207,42 @@ func TestAccessControl_CleanSecurityGroup(t *testing.T) { var ( rules = []*armnetwork.SecurityRule{ { - Name: ptr.To("test-rule-0"), + Name: to.Ptr("test-rule-0"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolTCP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), SourceAddressPrefixes: to.SliceOfPtrs("src_foo", "src_bar"), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("10.0.0.1", "10.0.0.2", "192.168.0.1"), DestinationPortRanges: to.SliceOfPtrs("80", "443"), - Priority: ptr.To(int32(500)), + Priority: to.Ptr(int32(500)), }, }, { - Name: ptr.To("test-rule-1"), + Name: to.Ptr("test-rule-1"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolUDP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), SourceAddressPrefixes: to.SliceOfPtrs("src_baz", "src_quo"), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("20.0.0.1", "192.168.0.1", "192.168.0.2", "20.0.0.2"), DestinationPortRanges: to.SliceOfPtrs("53"), - Priority: ptr.To(int32(501)), + Priority: to.Ptr(int32(501)), }, }, { - Name: ptr.To("test-rule-2"), + Name: to.Ptr("test-rule-2"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolAsterisk), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), SourceAddressPrefixes: to.SliceOfPtrs("*"), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("8.8.8.8"), DestinationPortRanges: to.SliceOfPtrs("5000"), - Priority: ptr.To(int32(502)), + Priority: to.Ptr(int32(502)), }, }, } @@ -1265,42 +1264,42 @@ func TestAccessControl_CleanSecurityGroup(t *testing.T) { testutil.ExpectEqualInJSON(t, []*armnetwork.SecurityRule{ { - Name: ptr.To("test-rule-0"), + Name: to.Ptr("test-rule-0"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolTCP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), SourceAddressPrefixes: to.SliceOfPtrs("src_foo", "src_bar"), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("10.0.0.1", "10.0.0.2"), DestinationPortRanges: to.SliceOfPtrs("80", "443"), - Priority: ptr.To(int32(500)), + Priority: to.Ptr(int32(500)), }, }, { - Name: ptr.To("test-rule-1"), + Name: to.Ptr("test-rule-1"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolUDP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), SourceAddressPrefixes: to.SliceOfPtrs("src_baz", "src_quo"), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("20.0.0.1", "20.0.0.2"), DestinationPortRanges: to.SliceOfPtrs("53"), - Priority: ptr.To(int32(501)), + Priority: to.Ptr(int32(501)), }, }, { - Name: ptr.To("test-rule-2"), + Name: to.Ptr("test-rule-2"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolAsterisk), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), SourceAddressPrefixes: to.SliceOfPtrs("*"), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("8.8.8.8"), DestinationPortRanges: to.SliceOfPtrs("5000"), - Priority: ptr.To(int32(502)), + Priority: to.Ptr(int32(502)), }, }, }, outputSG.Properties.SecurityRules) @@ -1310,55 +1309,55 @@ func TestAccessControl_CleanSecurityGroup(t *testing.T) { var ( rules = []*armnetwork.SecurityRule{ { - Name: ptr.To("test-rule-0"), + Name: to.Ptr("test-rule-0"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolTCP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), SourceAddressPrefixes: to.SliceOfPtrs("src_foo", "src_bar"), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("10.0.0.1", "10.0.0.2", "192.168.0.1"), DestinationPortRanges: to.SliceOfPtrs("80", "443"), - Priority: ptr.To(int32(500)), + Priority: to.Ptr(int32(500)), }, }, { - Name: ptr.To("test-rule-1"), + Name: to.Ptr("test-rule-1"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolUDP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), SourceAddressPrefixes: to.SliceOfPtrs("src_baz", "src_quo"), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("192.168.0.1", "192.168.0.2"), DestinationPortRanges: to.SliceOfPtrs("53"), - Priority: ptr.To(int32(501)), + Priority: to.Ptr(int32(501)), }, }, { - Name: ptr.To("test-rule-2"), + Name: to.Ptr("test-rule-2"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolAsterisk), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), SourceAddressPrefixes: to.SliceOfPtrs("*"), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("8.8.8.8"), DestinationPortRanges: to.SliceOfPtrs("5000"), - Priority: ptr.To(int32(502)), + Priority: to.Ptr(int32(502)), }, }, { - Name: ptr.To("test-rule-3"), + Name: to.Ptr("test-rule-3"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolAsterisk), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), SourceAddressPrefixes: to.SliceOfPtrs("*"), - SourcePortRange: ptr.To("*"), - DestinationAddressPrefix: ptr.To("192.168.0.1"), + SourcePortRange: to.Ptr("*"), + DestinationAddressPrefix: to.Ptr("192.168.0.1"), DestinationPortRanges: to.SliceOfPtrs("8000"), - Priority: ptr.To(int32(2000)), + Priority: to.Ptr(int32(2000)), }, }, } @@ -1380,29 +1379,29 @@ func TestAccessControl_CleanSecurityGroup(t *testing.T) { assert.True(t, updated) testutil.ExpectEqualInJSON(t, []*armnetwork.SecurityRule{ { - Name: ptr.To("test-rule-0"), + Name: to.Ptr("test-rule-0"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolTCP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), SourceAddressPrefixes: to.SliceOfPtrs("src_foo", "src_bar"), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("10.0.0.1", "10.0.0.2"), DestinationPortRanges: to.SliceOfPtrs("80", "443"), - Priority: ptr.To(int32(500)), + Priority: to.Ptr(int32(500)), }, }, { - Name: ptr.To("test-rule-2"), + Name: to.Ptr("test-rule-2"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolAsterisk), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), SourceAddressPrefixes: to.SliceOfPtrs("*"), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("8.8.8.8"), DestinationPortRanges: to.SliceOfPtrs("5000"), - Priority: ptr.To(int32(502)), + Priority: to.Ptr(int32(502)), }, }, }, outputSG.Properties.SecurityRules) @@ -1412,42 +1411,42 @@ func TestAccessControl_CleanSecurityGroup(t *testing.T) { var ( rules = []*armnetwork.SecurityRule{ { - Name: ptr.To("test-rule-0"), + Name: to.Ptr("test-rule-0"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolTCP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), SourceAddressPrefixes: to.SliceOfPtrs("src_foo", "src_bar"), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("10.0.0.1", "10.0.0.2", "192.168.0.1"), DestinationPortRanges: to.SliceOfPtrs("80", "443"), - Priority: ptr.To(int32(500)), + Priority: to.Ptr(int32(500)), }, }, { - Name: ptr.To("test-rule-1"), + Name: to.Ptr("test-rule-1"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolUDP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), SourceAddressPrefixes: to.SliceOfPtrs("src_baz", "src_quo"), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("20.0.0.1", "192.168.0.1", "192.168.0.2", "20.0.0.2"), DestinationPortRanges: to.SliceOfPtrs("53", "54", "55", "56"), - Priority: ptr.To(int32(501)), + Priority: to.Ptr(int32(501)), }, }, { - Name: ptr.To("test-rule-2"), + Name: to.Ptr("test-rule-2"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolAsterisk), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), SourceAddressPrefixes: to.SliceOfPtrs("*"), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("8.8.8.8"), DestinationPortRanges: to.SliceOfPtrs("5000"), - Priority: ptr.To(int32(502)), + Priority: to.Ptr(int32(502)), }, }, } @@ -1471,55 +1470,55 @@ func TestAccessControl_CleanSecurityGroup(t *testing.T) { testutil.ExpectEqualInJSON(t, []*armnetwork.SecurityRule{ { - Name: ptr.To("test-rule-0"), + Name: to.Ptr("test-rule-0"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolTCP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), SourceAddressPrefixes: to.SliceOfPtrs("src_foo", "src_bar"), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("10.0.0.1", "10.0.0.2"), DestinationPortRanges: to.SliceOfPtrs("80", "443"), - Priority: ptr.To(int32(500)), + Priority: to.Ptr(int32(500)), }, }, { - Name: ptr.To("test-rule-1"), + Name: to.Ptr("test-rule-1"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolUDP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), SourceAddressPrefixes: to.SliceOfPtrs("src_baz", "src_quo"), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("20.0.0.1", "20.0.0.2"), DestinationPortRanges: to.SliceOfPtrs("53", "54", "55", "56"), - Priority: ptr.To(int32(501)), + Priority: to.Ptr(int32(501)), }, }, { - Name: ptr.To("test-rule-2"), + Name: to.Ptr("test-rule-2"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolAsterisk), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), SourceAddressPrefixes: to.SliceOfPtrs("*"), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("8.8.8.8"), DestinationPortRanges: to.SliceOfPtrs("5000"), - Priority: ptr.To(int32(502)), + Priority: to.Ptr(int32(502)), }, }, { - Name: ptr.To("k8s-azure-lb_allow_IPv4_648b18e18a92d1a4b415033da37c79a5"), + Name: to.Ptr("k8s-azure-lb_allow_IPv4_648b18e18a92d1a4b415033da37c79a5"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolUDP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), SourceAddressPrefixes: to.SliceOfPtrs("src_baz", "src_quo"), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("192.168.0.1", "192.168.0.2"), DestinationPortRanges: to.SliceOfPtrs("53", "56"), // 53 and 56 are retained - Priority: ptr.To(int32(503)), + Priority: to.Ptr(int32(503)), }, }, }, outputSG.Properties.SecurityRules) diff --git a/pkg/provider/routetable/repo_test.go b/pkg/provider/routetable/repo_test.go index ac6fe1648c..d7a22fc213 100644 --- a/pkg/provider/routetable/repo_test.go +++ b/pkg/provider/routetable/repo_test.go @@ -26,7 +26,6 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" "github.com/stretchr/testify/assert" "go.uber.org/mock/gomock" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/routetableclient/mock_routetableclient" "sigs.k8s.io/cloud-provider-azure/pkg/cache" @@ -51,7 +50,7 @@ func TestRepo_Get(t *testing.T) { ) cli.EXPECT().Get(gomock.Any(), ResourceGroup, gomock.Any()).Return(&armnetwork.RouteTable{ - Name: ptr.To(RouteTableName), + Name: to.Ptr(RouteTableName), }, nil) v, err := repo.Get(ctx, RouteTableName, cache.CacheReadTypeDefault) diff --git a/pkg/provider/securitygroup/azure_securitygroup_repo.go b/pkg/provider/securitygroup/azure_securitygroup_repo.go index 0c602b8ee2..1fff1ed705 100644 --- a/pkg/provider/securitygroup/azure_securitygroup_repo.go +++ b/pkg/provider/securitygroup/azure_securitygroup_repo.go @@ -27,9 +27,8 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" - + "github.com/samber/lo" "k8s.io/klog/v2" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/securitygroupclient" azcache "sigs.k8s.io/cloud-provider-azure/pkg/cache" @@ -100,7 +99,7 @@ func (az *securityGroupRepo) CreateOrUpdateSecurityGroup(ctx context.Context, sg var respError *azcore.ResponseError if errors.As(rerr, &respError) && respError != nil { nsgJSON, _ := json.Marshal(sg) - klog.Warningf("CreateOrUpdateSecurityGroup(%s) failed: %v, NSG request: %s", ptr.Deref(sg.Name, ""), rerr.Error(), string(nsgJSON)) + klog.Warningf("CreateOrUpdateSecurityGroup(%s) failed: %v, NSG request: %s", lo.FromPtrOr(sg.Name, ""), rerr.Error(), string(nsgJSON)) // Invalidate the cache because ETAG precondition mismatch. if respError.StatusCode == http.StatusPreconditionFailed { diff --git a/pkg/provider/securitygroup/azure_securitygroup_repo_test.go b/pkg/provider/securitygroup/azure_securitygroup_repo_test.go index 7bfd7ae117..a396c91a3e 100644 --- a/pkg/provider/securitygroup/azure_securitygroup_repo_test.go +++ b/pkg/provider/securitygroup/azure_securitygroup_repo_test.go @@ -24,13 +24,11 @@ import ( "testing" "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" "github.com/stretchr/testify/assert" - "go.uber.org/mock/gomock" - "k8s.io/utils/ptr" - "sigs.k8s.io/cloud-provider-azure/pkg/azclient/securitygroupclient/mock_securitygroupclient" "sigs.k8s.io/cloud-provider-azure/pkg/cache" "sigs.k8s.io/cloud-provider-azure/pkg/consts" @@ -51,7 +49,7 @@ func TestCreateOrUpdateSecurityGroupCanceled(t *testing.T) { }) mockSGClient.EXPECT().Get(gomock.Any(), "rg", "sg").Return(&armnetwork.SecurityGroup{}, nil) - err = az.CreateOrUpdateSecurityGroup(context.TODO(), &armnetwork.SecurityGroup{Name: ptr.To("sg")}) + err = az.CreateOrUpdateSecurityGroup(context.TODO(), &armnetwork.SecurityGroup{Name: to.Ptr("sg")}) assert.Contains(t, err.Error(), "canceledandsupersededduetoanotheroperation") // security group should be removed from cache if the operation is canceled diff --git a/pkg/provider/securitygroup/securitygroup.go b/pkg/provider/securitygroup/securitygroup.go index 7ed4be70ff..2e673fccfd 100644 --- a/pkg/provider/securitygroup/securitygroup.go +++ b/pkg/provider/securitygroup/securitygroup.go @@ -27,10 +27,9 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" "github.com/go-logr/logr" - "k8s.io/utils/ptr" + "github.com/samber/lo" "sigs.k8s.io/cloud-provider-azure/pkg/consts" - fnutil "sigs.k8s.io/cloud-provider-azure/pkg/util/collectionutil" "sigs.k8s.io/cloud-provider-azure/pkg/util/iputil" ) @@ -148,9 +147,9 @@ func (helper *RuleHelper) getOrCreateRule(name string, priorityPrefer rulePriori return nil, err } rule := &armnetwork.SecurityRule{ - Name: ptr.To(name), + Name: to.Ptr(name), Properties: &armnetwork.SecurityRulePropertiesFormat{ - Priority: ptr.To(priority), + Priority: to.Ptr(priority), }, } @@ -175,7 +174,7 @@ func (helper *RuleHelper) addAllowRule( if err != nil { return err } - dstPortRanges := fnutil.Map(func(p int32) string { return strconv.FormatInt(int64(p), 10) }, dstPorts) + dstPortRanges := lo.Map(dstPorts, func(p int32, _ int) string { return strconv.FormatInt(int64(p), 10) }) sort.Strings(dstPortRanges) rule.Properties.Protocol = to.Ptr(protocol) @@ -188,7 +187,7 @@ func (helper *RuleHelper) addAllowRule( } else { rule.Properties.SourceAddressPrefixes = to.SliceOfPtrs(srcPrefixes...) } - rule.Properties.SourcePortRange = ptr.To("*") + rule.Properties.SourcePortRange = to.Ptr("*") } { // Destination @@ -216,7 +215,7 @@ func (helper *RuleHelper) AddRuleForAllowedServiceTag( var ( ipFamily = iputil.FamilyOfAddr(dstAddresses[0]) srcPrefixes = []string{serviceTag} - dstPrefixes = fnutil.Map(func(ip netip.Addr) string { return ip.String() }, dstAddresses) + dstPrefixes = lo.Map(dstAddresses, func(ip netip.Addr, _ int) string { return ip.String() }) ) helper.logger.V(4).Info("Patching a rule for allowed service tag", "ip-family", ipFamily) @@ -243,8 +242,8 @@ func (helper *RuleHelper) AddRuleForAllowedIPRanges( var ( ipFamily = iputil.FamilyOfAddr(ipRanges[0].Addr()) - srcPrefixes = fnutil.Map(func(ip netip.Prefix) string { return ip.String() }, ipRanges) - dstPrefixes = fnutil.Map(func(ip netip.Addr) string { return ip.String() }, dstAddresses) + srcPrefixes = lo.Map(ipRanges, func(ip netip.Prefix, _ int) string { return ip.String() }) + dstPrefixes = lo.Map(dstAddresses, func(ip netip.Addr, _ int) string { return ip.String() }) ) helper.logger.V(4).Info("Patching a rule for allowed IP ranges", "ip-family", ipFamily) @@ -277,18 +276,18 @@ func (helper *RuleHelper) AddRuleForDenyAll(dstAddresses []netip.Addr) error { rule.Properties.Direction = to.Ptr(armnetwork.SecurityRuleDirectionInbound) { // Source - rule.Properties.SourceAddressPrefix = ptr.To("*") - rule.Properties.SourcePortRange = ptr.To("*") + rule.Properties.SourceAddressPrefix = to.Ptr("*") + rule.Properties.SourcePortRange = to.Ptr("*") } { // Destination - addresses := fnutil.Map(func(ip netip.Addr) string { return ip.String() }, dstAddresses) + addresses := lo.Map(dstAddresses, func(ip netip.Addr, _ int) string { return ip.String() }) addresses = append(addresses, ListDestinationPrefixes(rule)...) SetDestinationPrefixes(rule, addresses) - rule.Properties.DestinationPortRange = ptr.To("*") + rule.Properties.DestinationPortRange = to.Ptr("*") } - helper.logger.V(4).Info("Patched a rule for deny all", "rule-name", ptr.To(rule.Name)) + helper.logger.V(4).Info("Patched a rule for deny all", "rule-name", to.Ptr(rule.Name)) return nil } @@ -330,11 +329,9 @@ func (helper *RuleHelper) removeDestinationFromRule(rule *armnetwork.SecurityRul WithValues("security-rule-name", rule.Name) var ( - prefixIndex = fnutil.IndexSet(prefixes) // Used to check whether the prefix should be removed. - currentPrefixes = ListDestinationPrefixes(rule) - - expectedPrefixes = prefixIndex.SubtractedBy(currentPrefixes) // The prefixes to keep. - targetPrefixes = fnutil.Intersection(currentPrefixes, prefixes) // The prefixes to remove. + currentPrefixes = ListDestinationPrefixes(rule) + _, expectedPrefixes = lo.Difference(prefixes, currentPrefixes) + targetPrefixes = lo.Intersect(currentPrefixes, prefixes) // The prefixes to remove. ) // Clean DenyAll rule @@ -354,7 +351,7 @@ func (helper *RuleHelper) removeDestinationFromRule(rule *armnetwork.SecurityRul return nil } var ( - expectedPorts = fnutil.Intersection(currentPorts, retainDstPorts) // The ports to keep. + expectedPorts = lo.Intersect(currentPorts, retainDstPorts) // The ports to keep. ) if len(targetPrefixes) == 0 || len(currentPorts) == len(expectedPorts) { diff --git a/pkg/provider/securitygroup/securitygroup_test.go b/pkg/provider/securitygroup/securitygroup_test.go index 90b5dfbc47..b08df071c9 100644 --- a/pkg/provider/securitygroup/securitygroup_test.go +++ b/pkg/provider/securitygroup/securitygroup_test.go @@ -23,14 +23,13 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" + "github.com/samber/lo" "github.com/stretchr/testify/assert" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/internal/testutil" "sigs.k8s.io/cloud-provider-azure/internal/testutil/fixture" "sigs.k8s.io/cloud-provider-azure/pkg/log" . "sigs.k8s.io/cloud-provider-azure/pkg/provider/securitygroup" //nolint:revive - fnutil "sigs.k8s.io/cloud-provider-azure/pkg/util/collectionutil" "sigs.k8s.io/cloud-provider-azure/pkg/util/iputil" ) @@ -54,20 +53,20 @@ func TestNewSecurityGroupHelper(t *testing.T) { } { _, err := NewSecurityGroupHelper(log.Noop(), &armnetwork.SecurityGroup{ - Name: ptr.To("nsg"), + Name: to.Ptr("nsg"), }) assert.ErrorIs(t, err, ErrInvalidSecurityGroup) } { _, err := NewSecurityGroupHelper(log.Noop(), &armnetwork.SecurityGroup{ - Name: ptr.To("nsg"), + Name: to.Ptr("nsg"), Properties: &armnetwork.SecurityGroupPropertiesFormat{}, }) assert.ErrorIs(t, err, ErrInvalidSecurityGroup) } { helper, err := NewSecurityGroupHelper(log.Noop(), &armnetwork.SecurityGroup{ - Name: ptr.To("nsg"), + Name: to.Ptr("nsg"), Properties: &armnetwork.SecurityGroupPropertiesFormat{ SecurityRules: []*armnetwork.SecurityRule{}, }, @@ -78,7 +77,7 @@ func TestNewSecurityGroupHelper(t *testing.T) { assert.NoError(t, err) assert.False(t, updated) testutil.ExpectEqualInJSON(t, &armnetwork.SecurityGroup{ - Name: ptr.To("nsg"), + Name: to.Ptr("nsg"), Properties: &armnetwork.SecurityGroupPropertiesFormat{ SecurityRules: []*armnetwork.SecurityRule{}, }, @@ -216,16 +215,16 @@ func TestSecurityGroupHelper_AddRuleForAllowedIPRanges(t *testing.T) { testutil.ExpectHasSecurityRules(t, outputSG, rules, "[`%s`] the original irrelevant rules should remain unchanged", c.TestName) testutil.ExpectHasSecurityRules(t, outputSG, []*armnetwork.SecurityRule{ { - Name: ptr.To(GenerateAllowSecurityRuleName(protocol, ipFamily, fnutil.Map(func(v netip.Prefix) string { return v.String() }, srcIPRanges), dstPorts)), + Name: to.Ptr(GenerateAllowSecurityRuleName(protocol, ipFamily, lo.Map(srcIPRanges, func(v netip.Prefix, _ int) string { return v.String() }), dstPorts)), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(protocol), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), - SourceAddressPrefixes: fnutil.Map(func(v netip.Prefix) *string { return to.Ptr(v.String()) }, srcIPRanges), - SourcePortRange: ptr.To("*"), - DestinationAddressPrefixes: fnutil.Map(func(v netip.Addr) *string { return to.Ptr(v.String()) }, dstAddresses), + SourceAddressPrefixes: lo.Map(srcIPRanges, func(v netip.Prefix, _ int) *string { return to.Ptr(v.String()) }), + SourcePortRange: to.Ptr("*"), + DestinationAddressPrefixes: lo.Map(dstAddresses, func(v netip.Addr, _ int) *string { return to.Ptr(v.String()) }), DestinationPortRanges: to.SliceOfPtrs(NormalizeDestinationPortRanges(dstPorts)...), - Priority: ptr.To(int32(500)), + Priority: to.Ptr(int32(500)), }, }, }, "[`%s`] 1 allow rule should be created", c.TestName) @@ -300,16 +299,16 @@ func TestSecurityGroupHelper_AddRuleForAllowedIPRanges(t *testing.T) { dstPorts = c.DstPorts targetRule = &armnetwork.SecurityRule{ - Name: ptr.To(GenerateAllowSecurityRuleName(protocol, ipFamily, fnutil.Map(func(v netip.Prefix) string { return v.String() }, srcIPRanges), dstPorts)), + Name: to.Ptr(GenerateAllowSecurityRuleName(protocol, ipFamily, lo.Map(srcIPRanges, func(v netip.Prefix, _ int) string { return v.String() }), dstPorts)), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(protocol), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), - SourceAddressPrefixes: fnutil.Map(func(v netip.Prefix) *string { return to.Ptr(v.String()) }, srcIPRanges), - SourcePortRange: ptr.To("*"), + SourceAddressPrefixes: lo.Map(srcIPRanges, func(v netip.Prefix, _ int) *string { return to.Ptr(v.String()) }), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("foo", "bar"), // Should append the dstAddresses. DestinationPortRanges: to.SliceOfPtrs(NormalizeDestinationPortRanges(dstPorts)...), - Priority: ptr.To(int32(950)), // A random priority, should remain unchanged. + Priority: to.Ptr(int32(950)), // A random priority, should remain unchanged. }, } irrelevantRules = fx.Azure().NoiseSecurityRules() @@ -332,9 +331,9 @@ func TestSecurityGroupHelper_AddRuleForAllowedIPRanges(t *testing.T) { // It should append the new destination addresses. expectedTargetRule.Properties.DestinationAddressPrefixes = append( expectedTargetRule.Properties.DestinationAddressPrefixes, - fnutil.Map(func(v netip.Addr) *string { return to.Ptr(v.String()) }, dstAddresses)..., + lo.Map(dstAddresses, func(v netip.Addr, _ int) *string { return to.Ptr(v.String()) })..., ) - result := fnutil.Map(func(v *string) string { return *v }, expectedTargetRule.Properties.DestinationAddressPrefixes) + result := lo.Map(expectedTargetRule.Properties.DestinationAddressPrefixes, func(v *string, _ int) string { return *v }) sort.Strings(result) expectedTargetRule.Properties.DestinationAddressPrefixes = to.SliceOfPtrs(result...) } @@ -412,19 +411,19 @@ func TestSecurityGroupHelper_AddRuleForAllowedIPRanges(t *testing.T) { dstPorts = c.DstPorts targetRule = &armnetwork.SecurityRule{ - Name: ptr.To(GenerateAllowSecurityRuleName(protocol, ipFamily, fnutil.Map(func(v netip.Prefix) string { return v.String() }, srcIPRanges), dstPorts)), + Name: to.Ptr(GenerateAllowSecurityRuleName(protocol, ipFamily, lo.Map(srcIPRanges, func(v netip.Prefix, _ int) string { return v.String() }), dstPorts)), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(protocol), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), - SourceAddressPrefixes: fnutil.Map(func(v netip.Prefix) *string { return to.Ptr(v.String()) }, srcIPRanges), - SourcePortRange: ptr.To("*"), + SourceAddressPrefixes: lo.Map(srcIPRanges, func(v netip.Prefix, _ int) *string { return to.Ptr(v.String()) }), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs( NormalizeSecurityRuleAddressPrefixes( - append([]string{"foo", "bar"}, fnutil.Map(func(v netip.Addr) string { return v.String() }, dstAddresses)...), + append([]string{"foo", "bar"}, lo.Map(dstAddresses, func(v netip.Addr, _ int) string { return v.String() })...), )...), DestinationPortRanges: to.SliceOfPtrs(NormalizeDestinationPortRanges(dstPorts)...), - Priority: ptr.To(int32(950)), // A random priority, should remain unchanged. + Priority: to.Ptr(int32(950)), // A random priority, should remain unchanged. }, } irrelevantRules = fx.Azure().NoiseSecurityRules() @@ -548,16 +547,16 @@ func TestSecurityGroupHelper_AddRuleForAllowedServiceTag(t *testing.T) { testutil.ExpectHasSecurityRules(t, outputSG, rules, "[`%s`] the original irrelevant rules should remain unchanged", c.TestName) testutil.ExpectHasSecurityRules(t, outputSG, []*armnetwork.SecurityRule{ { - Name: ptr.To(GenerateAllowSecurityRuleName(protocol, ipFamily, []string{srcServiceTag}, dstPorts)), + Name: to.Ptr(GenerateAllowSecurityRuleName(protocol, ipFamily, []string{srcServiceTag}, dstPorts)), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(protocol), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), - SourceAddressPrefix: ptr.To(srcServiceTag), - SourcePortRange: ptr.To("*"), - DestinationAddressPrefixes: fnutil.Map(func(v netip.Addr) *string { return to.Ptr(v.String()) }, dstAddresses), + SourceAddressPrefix: to.Ptr(srcServiceTag), + SourcePortRange: to.Ptr("*"), + DestinationAddressPrefixes: lo.Map(dstAddresses, func(v netip.Addr, _ int) *string { return to.Ptr(v.String()) }), DestinationPortRanges: to.SliceOfPtrs(NormalizeDestinationPortRanges(dstPorts)...), - Priority: ptr.To(int32(500)), + Priority: to.Ptr(int32(500)), }, }, }, "[`%s`] 1 allow rule should be created", c.TestName) @@ -632,16 +631,16 @@ func TestSecurityGroupHelper_AddRuleForAllowedServiceTag(t *testing.T) { dstPorts = c.DstPorts targetRule = &armnetwork.SecurityRule{ - Name: ptr.To(GenerateAllowSecurityRuleName(protocol, ipFamily, []string{srcServiceTag}, dstPorts)), + Name: to.Ptr(GenerateAllowSecurityRuleName(protocol, ipFamily, []string{srcServiceTag}, dstPorts)), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(protocol), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), - SourceAddressPrefix: ptr.To(srcServiceTag), - SourcePortRange: ptr.To("*"), + SourceAddressPrefix: to.Ptr(srcServiceTag), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("foo", "bar"), // Should append the dstAddresses. DestinationPortRanges: to.SliceOfPtrs(NormalizeDestinationPortRanges(dstPorts)...), - Priority: ptr.To(int32(950)), // A random priority, should remain unchanged. + Priority: to.Ptr(int32(950)), // A random priority, should remain unchanged. }, } irrelevantRules = fx.Azure().NoiseSecurityRules() @@ -664,9 +663,9 @@ func TestSecurityGroupHelper_AddRuleForAllowedServiceTag(t *testing.T) { // It should append the new destination addresses. expectedTargetRule.Properties.DestinationAddressPrefixes = append( expectedTargetRule.Properties.DestinationAddressPrefixes, - fnutil.Map(func(v netip.Addr) *string { return to.Ptr(v.String()) }, dstAddresses)..., + lo.Map(dstAddresses, func(v netip.Addr, _ int) *string { return to.Ptr(v.String()) })..., ) - result := fnutil.Map(func(v *string) string { return *v }, expectedTargetRule.Properties.DestinationAddressPrefixes) + result := lo.Map(expectedTargetRule.Properties.DestinationAddressPrefixes, func(v *string, _ int) string { return *v }) sort.Strings(result) expectedTargetRule.Properties.DestinationAddressPrefixes = to.SliceOfPtrs(result...) } @@ -744,19 +743,19 @@ func TestSecurityGroupHelper_AddRuleForAllowedServiceTag(t *testing.T) { dstPorts = c.DstPorts targetRule = &armnetwork.SecurityRule{ - Name: ptr.To(GenerateAllowSecurityRuleName(protocol, ipFamily, []string{srcServiceTag}, dstPorts)), + Name: to.Ptr(GenerateAllowSecurityRuleName(protocol, ipFamily, []string{srcServiceTag}, dstPorts)), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(protocol), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), - SourceAddressPrefix: ptr.To(srcServiceTag), - SourcePortRange: ptr.To("*"), + SourceAddressPrefix: to.Ptr(srcServiceTag), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs( NormalizeSecurityRuleAddressPrefixes( - append([]string{"foo", "bar"}, fnutil.Map(func(v netip.Addr) string { return v.String() }, dstAddresses)...), + append([]string{"foo", "bar"}, lo.Map(dstAddresses, func(v netip.Addr, _ int) string { return v.String() })...), )...), DestinationPortRanges: to.SliceOfPtrs(NormalizeDestinationPortRanges(dstPorts)...), - Priority: ptr.To(int32(950)), // A random priority, should remain unchanged. + Priority: to.Ptr(int32(950)), // A random priority, should remain unchanged. }, } irrelevantRules = fx.Azure().NoiseSecurityRules() @@ -854,16 +853,16 @@ func TestSecurityGroupHelper_AddRuleForDenyAll(t *testing.T) { testutil.ExpectHasSecurityRules(t, outputSG, rules, "[`%s`] the original irrelevant rules should remain unchanged", c.TestName) testutil.ExpectHasSecurityRules(t, outputSG, []*armnetwork.SecurityRule{ { - Name: ptr.To(GenerateDenyAllSecurityRuleName(ipFamily)), + Name: to.Ptr(GenerateDenyAllSecurityRuleName(ipFamily)), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolAsterisk), Access: to.Ptr(armnetwork.SecurityRuleAccessDeny), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), - SourceAddressPrefix: ptr.To("*"), - SourcePortRange: ptr.To("*"), - DestinationAddressPrefixes: fnutil.Map(func(v netip.Addr) *string { return to.Ptr(v.String()) }, dstAddresses), - DestinationPortRange: ptr.To("*"), - Priority: ptr.To(int32(4095)), + SourceAddressPrefix: to.Ptr("*"), + SourcePortRange: to.Ptr("*"), + DestinationAddressPrefixes: lo.Map(dstAddresses, func(v netip.Addr, _ int) *string { return to.Ptr(v.String()) }), + DestinationPortRange: to.Ptr("*"), + Priority: to.Ptr(int32(4095)), }, }, }, "[`%s`] 1 allow rule should be created", c.TestName) @@ -914,16 +913,16 @@ func TestSecurityGroupHelper_AddRuleForDenyAll(t *testing.T) { dstAddresses = c.DstAddresses targetRule = &armnetwork.SecurityRule{ - Name: ptr.To(GenerateDenyAllSecurityRuleName(ipFamily)), + Name: to.Ptr(GenerateDenyAllSecurityRuleName(ipFamily)), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolAsterisk), Access: to.Ptr(armnetwork.SecurityRuleAccessDeny), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), - SourceAddressPrefix: ptr.To("*"), - SourcePortRange: ptr.To("*"), + SourceAddressPrefix: to.Ptr("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("foo", "bar"), // Should append the dstAddresses. - DestinationPortRange: ptr.To("*"), - Priority: ptr.To(int32(950)), // A random priority, should remain unchanged. + DestinationPortRange: to.Ptr("*"), + Priority: to.Ptr(int32(950)), // A random priority, should remain unchanged. }, } irrelevantRules = fx.Azure().NoiseSecurityRules() @@ -946,8 +945,8 @@ func TestSecurityGroupHelper_AddRuleForDenyAll(t *testing.T) { // It should append the new destination addresses. expectedTargetRule.Properties.DestinationAddressPrefixes = append( expectedTargetRule.Properties.DestinationAddressPrefixes, - fnutil.Map(func(v netip.Addr) *string { return to.Ptr(v.String()) }, dstAddresses)...) - result := fnutil.Map(func(v *string) string { return *v }, expectedTargetRule.Properties.DestinationAddressPrefixes) + lo.Map(dstAddresses, func(v netip.Addr, _ int) *string { return to.Ptr(v.String()) })...) + result := lo.Map(expectedTargetRule.Properties.DestinationAddressPrefixes, func(v *string, _ int) string { return *v }) sort.Strings(result) expectedTargetRule.Properties.DestinationAddressPrefixes = to.SliceOfPtrs(result...) } @@ -1001,16 +1000,16 @@ func TestSecurityGroupHelper_AddRuleForDenyAll(t *testing.T) { dstAddresses = c.DstAddresses targetRule = &armnetwork.SecurityRule{ - Name: ptr.To(GenerateDenyAllSecurityRuleName(ipFamily)), + Name: to.Ptr(GenerateDenyAllSecurityRuleName(ipFamily)), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolAsterisk), Access: to.Ptr(armnetwork.SecurityRuleAccessDeny), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), - SourceAddressPrefix: ptr.To("*"), - SourcePortRange: ptr.To("*"), - DestinationAddressPrefix: ptr.To("foo"), // Should append the dstAddresses. - DestinationPortRange: ptr.To("*"), - Priority: ptr.To(int32(950)), // A random priority, should remain unchanged. + SourceAddressPrefix: to.Ptr("*"), + SourcePortRange: to.Ptr("*"), + DestinationAddressPrefix: to.Ptr("foo"), // Should append the dstAddresses. + DestinationPortRange: to.Ptr("*"), + Priority: to.Ptr(int32(950)), // A random priority, should remain unchanged. }, } irrelevantRules = fx.Azure().NoiseSecurityRules() @@ -1032,7 +1031,7 @@ func TestSecurityGroupHelper_AddRuleForDenyAll(t *testing.T) { { // It should append the new destination addresses. ps := append( - fnutil.Map(func(v netip.Addr) *string { return to.Ptr(v.String()) }, dstAddresses), + lo.Map(dstAddresses, func(v netip.Addr, _ int) *string { return to.Ptr(v.String()) }), expectedTargetRule.Properties.DestinationAddressPrefix, ) expectedTargetRule.Properties.DestinationAddressPrefixes = ps @@ -1088,20 +1087,20 @@ func TestSecurityGroupHelper_AddRuleForDenyAll(t *testing.T) { dstAddresses = c.DstAddresses targetRule = &armnetwork.SecurityRule{ - Name: ptr.To(GenerateDenyAllSecurityRuleName(ipFamily)), + Name: to.Ptr(GenerateDenyAllSecurityRuleName(ipFamily)), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolAsterisk), Access: to.Ptr(armnetwork.SecurityRuleAccessDeny), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), - SourceAddressPrefix: ptr.To("*"), - SourcePortRange: ptr.To("*"), + SourceAddressPrefix: to.Ptr("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs( NormalizeSecurityRuleAddressPrefixes( - append([]string{"foo", "bar"}, fnutil.Map(func(v netip.Addr) string { return v.String() }, dstAddresses)...), + append([]string{"foo", "bar"}, lo.Map(dstAddresses, func(v netip.Addr, _ int) string { return v.String() })...), )..., ), - DestinationPortRange: ptr.To("*"), - Priority: ptr.To(int32(950)), // A random priority, should remain unchanged. + DestinationPortRange: to.Ptr("*"), + Priority: to.Ptr(int32(950)), // A random priority, should remain unchanged. }, } irrelevantRules = fx.Azure().NoiseSecurityRules() @@ -1130,9 +1129,9 @@ func TestRuleHelper_RemoveDestinationFromRules(t *testing.T) { var ( sg = fx.Azure().SecurityGroup().Build() helper = ExpectNewSecurityGroupHelper(t, sg) - dstAddresses = fnutil.Map(func(p netip.Addr) string { + dstAddresses = lo.Map(fx.RandomIPv4Addresses(2), func(p netip.Addr, _ int) string { return p.String() - }, fx.RandomIPv4Addresses(2)) + }) ) err := helper.RemoveDestinationFromRules(armnetwork.SecurityRuleProtocolTCP, dstAddresses, []int32{}) assert.NoError(t, err) @@ -1146,29 +1145,29 @@ func TestRuleHelper_RemoveDestinationFromRules(t *testing.T) { var ( rules = []*armnetwork.SecurityRule{ { - Name: ptr.To("test-rule-0"), + Name: to.Ptr("test-rule-0"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolTCP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), SourceAddressPrefixes: to.SliceOfPtrs("src_foo", "src_bar"), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("10.0.0.1", "10.0.0.2"), DestinationPortRanges: to.SliceOfPtrs("443", "80"), - Priority: ptr.To(int32(500)), + Priority: to.Ptr(int32(500)), }, }, { - Name: ptr.To("test-rule-1"), + Name: to.Ptr("test-rule-1"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolUDP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), SourceAddressPrefixes: to.SliceOfPtrs("src_baz", "src_quo"), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("20.0.0.1", "20.0.0.2"), DestinationPortRanges: to.SliceOfPtrs("53"), - Priority: ptr.To(int32(501)), + Priority: to.Ptr(int32(501)), }, }, } @@ -1192,42 +1191,42 @@ func TestRuleHelper_RemoveDestinationFromRules(t *testing.T) { var ( rules = []*armnetwork.SecurityRule{ { - Name: ptr.To("test-rule-0"), + Name: to.Ptr("test-rule-0"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolTCP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), SourceAddressPrefixes: to.SliceOfPtrs("src_foo", "src_bar"), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("10.0.0.1", "10.0.0.2", "192.168.0.1"), DestinationPortRanges: to.SliceOfPtrs("443", "80"), - Priority: ptr.To(int32(500)), + Priority: to.Ptr(int32(500)), }, }, { - Name: ptr.To("test-rule-1"), + Name: to.Ptr("test-rule-1"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolUDP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), SourceAddressPrefixes: to.SliceOfPtrs("src_baz", "src_quo"), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("20.0.0.1", "192.168.0.1", "192.168.0.2", "20.0.0.2"), DestinationPortRanges: to.SliceOfPtrs("53"), - Priority: ptr.To(int32(501)), + Priority: to.Ptr(int32(501)), }, }, { - Name: ptr.To("test-rule-2"), + Name: to.Ptr("test-rule-2"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolAsterisk), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), - SourceAddressPrefix: ptr.To("*"), - SourcePortRange: ptr.To("*"), + SourceAddressPrefix: to.Ptr("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("8.8.8.8"), DestinationPortRanges: to.SliceOfPtrs("5000"), - Priority: ptr.To(int32(502)), + Priority: to.Ptr(int32(502)), }, }, } @@ -1248,42 +1247,42 @@ func TestRuleHelper_RemoveDestinationFromRules(t *testing.T) { assert.True(t, updated) testutil.ExpectEqualInJSON(t, []*armnetwork.SecurityRule{ { - Name: ptr.To("test-rule-0"), + Name: to.Ptr("test-rule-0"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolTCP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), SourceAddressPrefixes: to.SliceOfPtrs("src_foo", "src_bar"), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("10.0.0.1", "10.0.0.2"), DestinationPortRanges: to.SliceOfPtrs("443", "80"), - Priority: ptr.To(int32(500)), + Priority: to.Ptr(int32(500)), }, }, { - Name: ptr.To("test-rule-1"), + Name: to.Ptr("test-rule-1"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolUDP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), SourceAddressPrefixes: to.SliceOfPtrs("src_baz", "src_quo"), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("20.0.0.1", "20.0.0.2"), DestinationPortRanges: to.SliceOfPtrs("53"), - Priority: ptr.To(int32(501)), + Priority: to.Ptr(int32(501)), }, }, { - Name: ptr.To("test-rule-2"), + Name: to.Ptr("test-rule-2"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolAsterisk), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), - SourceAddressPrefix: ptr.To("*"), - SourcePortRange: ptr.To("*"), + SourceAddressPrefix: to.Ptr("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("8.8.8.8"), DestinationPortRanges: to.SliceOfPtrs("5000"), - Priority: ptr.To(int32(502)), + Priority: to.Ptr(int32(502)), }, }, }, outputSG.Properties.SecurityRules) @@ -1293,83 +1292,83 @@ func TestRuleHelper_RemoveDestinationFromRules(t *testing.T) { var ( rules = []*armnetwork.SecurityRule{ { - Name: ptr.To("test-rule-0"), + Name: to.Ptr("test-rule-0"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolTCP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), SourceAddressPrefixes: to.SliceOfPtrs("src_foo", "src_bar"), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("10.0.0.1", "10.0.0.2", "192.168.0.1"), DestinationPortRanges: to.SliceOfPtrs("443", "80"), - Priority: ptr.To(int32(500)), + Priority: to.Ptr(int32(500)), }, }, { - Name: ptr.To("test-rule-1"), + Name: to.Ptr("test-rule-1"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolUDP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), SourceAddressPrefixes: to.SliceOfPtrs("src_baz", "src_quo"), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("192.168.0.1", "192.168.0.2"), DestinationPortRanges: to.SliceOfPtrs("53"), - Priority: ptr.To(int32(501)), + Priority: to.Ptr(int32(501)), }, }, { - Name: ptr.To("test-rule-2"), + Name: to.Ptr("test-rule-2"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolTCP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), - SourceAddressPrefix: ptr.To("*"), - SourcePortRange: ptr.To("*"), + SourceAddressPrefix: to.Ptr("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("8.8.8.8"), DestinationPortRanges: to.SliceOfPtrs("5000"), - Priority: ptr.To(int32(502)), + Priority: to.Ptr(int32(502)), }, }, { - Name: ptr.To("test-rule-3"), + Name: to.Ptr("test-rule-3"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolUDP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), - SourceAddressPrefix: ptr.To("*"), - SourcePortRange: ptr.To("*"), - DestinationAddressPrefix: ptr.To("192.168.0.1"), + SourceAddressPrefix: to.Ptr("*"), + SourcePortRange: to.Ptr("*"), + DestinationAddressPrefix: to.Ptr("192.168.0.1"), DestinationPortRanges: to.SliceOfPtrs("8000"), - Priority: ptr.To(int32(2000)), + Priority: to.Ptr(int32(2000)), }, }, { - Name: ptr.To("test-rule-4"), + Name: to.Ptr("test-rule-4"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolTCP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), - SourceAddressPrefix: ptr.To("*"), - SourcePortRange: ptr.To("*"), + SourceAddressPrefix: to.Ptr("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: []*string{}, - DestinationAddressPrefix: ptr.To("192.168.0.1"), + DestinationAddressPrefix: to.Ptr("192.168.0.1"), DestinationPortRanges: to.SliceOfPtrs("8000"), - Priority: ptr.To(int32(2001)), + Priority: to.Ptr(int32(2001)), }, }, { - Name: ptr.To("test-rule-5"), + Name: to.Ptr("test-rule-5"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolAsterisk), Access: to.Ptr(armnetwork.SecurityRuleAccessDeny), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), - SourceAddressPrefix: ptr.To("*"), - SourcePortRange: ptr.To("*"), + SourceAddressPrefix: to.Ptr("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: []*string{}, - DestinationAddressPrefix: ptr.To("*"), // Should not overwrite the DestinationAddressPrefixes. + DestinationAddressPrefix: to.Ptr("*"), // Should not overwrite the DestinationAddressPrefixes. DestinationPortRanges: to.SliceOfPtrs("8000"), - Priority: ptr.To(int32(2002)), + Priority: to.Ptr(int32(2002)), }, }, } @@ -1389,43 +1388,43 @@ func TestRuleHelper_RemoveDestinationFromRules(t *testing.T) { assert.True(t, updated) testutil.ExpectEqualInJSON(t, []*armnetwork.SecurityRule{ { - Name: ptr.To("test-rule-0"), + Name: to.Ptr("test-rule-0"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolTCP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), SourceAddressPrefixes: to.SliceOfPtrs("src_foo", "src_bar"), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("10.0.0.1", "10.0.0.2"), DestinationPortRanges: to.SliceOfPtrs("443", "80"), - Priority: ptr.To(int32(500)), + Priority: to.Ptr(int32(500)), }, }, { - Name: ptr.To("test-rule-2"), + Name: to.Ptr("test-rule-2"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolTCP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), - SourceAddressPrefix: ptr.To("*"), - SourcePortRange: ptr.To("*"), + SourceAddressPrefix: to.Ptr("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("8.8.8.8"), DestinationPortRanges: to.SliceOfPtrs("5000"), - Priority: ptr.To(int32(502)), + Priority: to.Ptr(int32(502)), }, }, { - Name: ptr.To("test-rule-5"), + Name: to.Ptr("test-rule-5"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolAsterisk), Access: to.Ptr(armnetwork.SecurityRuleAccessDeny), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), - SourceAddressPrefix: ptr.To("*"), - SourcePortRange: ptr.To("*"), + SourceAddressPrefix: to.Ptr("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: []*string{}, - DestinationAddressPrefix: ptr.To("*"), + DestinationAddressPrefix: to.Ptr("*"), DestinationPortRanges: to.SliceOfPtrs("8000"), - Priority: ptr.To(int32(2002)), + Priority: to.Ptr(int32(2002)), }, }, }, outputSG.Properties.SecurityRules) @@ -1435,16 +1434,16 @@ func TestRuleHelper_RemoveDestinationFromRules(t *testing.T) { var ( rules = []*armnetwork.SecurityRule{ { - Name: ptr.To("test-rule-0"), + Name: to.Ptr("test-rule-0"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolTCP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), SourceAddressPrefixes: to.SliceOfPtrs("src_foo", "src_bar"), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("10.0.0.1", "10.0.0.2", "192.168.0.1"), DestinationPortRanges: to.SliceOfPtrs("443", "80"), - Priority: ptr.To(int32(500)), + Priority: to.Ptr(int32(500)), }, }, } @@ -1468,29 +1467,29 @@ func TestRuleHelper_RemoveDestinationFromRules(t *testing.T) { var ( rules = []*armnetwork.SecurityRule{ { - Name: ptr.To("test-rule-0"), + Name: to.Ptr("test-rule-0"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolTCP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), SourceAddressPrefixes: to.SliceOfPtrs("bar", "foo"), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("10.0.0.1", "10.0.0.2", "192.168.0.1"), DestinationPortRanges: to.SliceOfPtrs("443", "80"), - Priority: ptr.To(int32(500)), + Priority: to.Ptr(int32(500)), }, }, { - Name: ptr.To("test-rule-1"), + Name: to.Ptr("test-rule-1"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolUDP), // Different protocol, should not be touched. Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), SourceAddressPrefixes: to.SliceOfPtrs("baz"), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("10.0.0.1", "10.0.0.2", "192.168.0.1"), DestinationPortRanges: to.SliceOfPtrs("443", "80"), - Priority: ptr.To(int32(501)), + Priority: to.Ptr(int32(501)), }, }, } @@ -1510,42 +1509,42 @@ func TestRuleHelper_RemoveDestinationFromRules(t *testing.T) { assert.True(t, updated) testutil.ExpectEqualInJSON(t, []*armnetwork.SecurityRule{ { - Name: ptr.To("test-rule-0"), + Name: to.Ptr("test-rule-0"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolTCP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), SourceAddressPrefixes: to.SliceOfPtrs("bar", "foo"), - SourcePortRange: ptr.To("*"), - DestinationAddressPrefix: ptr.To("192.168.0.1"), + SourcePortRange: to.Ptr("*"), + DestinationAddressPrefix: to.Ptr("192.168.0.1"), DestinationPortRanges: to.SliceOfPtrs("443", "80"), - Priority: ptr.To(int32(500)), + Priority: to.Ptr(int32(500)), }, }, { - Name: ptr.To("test-rule-1"), + Name: to.Ptr("test-rule-1"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolUDP), // Different protocol, should not be touched. Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), SourceAddressPrefixes: to.SliceOfPtrs("baz"), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("10.0.0.1", "10.0.0.2", "192.168.0.1"), DestinationPortRanges: to.SliceOfPtrs("443", "80"), - Priority: ptr.To(int32(501)), + Priority: to.Ptr(int32(501)), }, }, { - Name: ptr.To("k8s-azure-lb_allow_IPv4_b5ae07e8a4177ea2d37162cdf2badf8b"), + Name: to.Ptr("k8s-azure-lb_allow_IPv4_b5ae07e8a4177ea2d37162cdf2badf8b"), Properties: &armnetwork.SecurityRulePropertiesFormat{ Protocol: to.Ptr(armnetwork.SecurityRuleProtocolTCP), Access: to.Ptr(armnetwork.SecurityRuleAccessAllow), Direction: to.Ptr(armnetwork.SecurityRuleDirectionInbound), SourceAddressPrefixes: to.SliceOfPtrs("bar", "foo"), - SourcePortRange: ptr.To("*"), + SourcePortRange: to.Ptr("*"), DestinationAddressPrefixes: to.SliceOfPtrs("10.0.0.1", "10.0.0.2"), DestinationPortRanges: to.SliceOfPtrs("443"), - Priority: ptr.To(int32(502)), + Priority: to.Ptr(int32(502)), }, }, }, outputSG.Properties.SecurityRules) diff --git a/pkg/provider/securitygroup/securityrule.go b/pkg/provider/securitygroup/securityrule.go index 481c26f134..0c7d1cd257 100644 --- a/pkg/provider/securitygroup/securityrule.go +++ b/pkg/provider/securitygroup/securityrule.go @@ -25,9 +25,9 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" + "github.com/samber/lo" v1 "k8s.io/api/core/v1" - fnutil "sigs.k8s.io/cloud-provider-azure/pkg/util/collectionutil" "sigs.k8s.io/cloud-provider-azure/pkg/util/iputil" ) @@ -40,7 +40,7 @@ func GenerateAllowSecurityRuleName( ) string { var ruleID string { - dstPortRanges := fnutil.Map(func(p int32) string { return strconv.FormatInt(int64(p), 10) }, dstPorts) + dstPortRanges := lo.Map(dstPorts, func(p int32, _ int) string { return strconv.FormatInt(int64(p), 10) }) // Generate rule ID from protocol, source prefixes and destination port ranges. sort.Strings(srcPrefixes) sort.Strings(dstPortRanges) @@ -82,7 +82,7 @@ func NormalizeSecurityRuleAddressPrefixes(vs []string) []string { // NormalizeDestinationPortRanges normalizes the given destination port ranges. func NormalizeDestinationPortRanges(dstPorts []int32) []string { - rv := fnutil.Map(func(p int32) string { return strconv.FormatInt(int64(p), 10) }, dstPorts) + rv := lo.Map(dstPorts, func(p int32, _ int) string { return strconv.FormatInt(int64(p), 10) }) sort.Strings(rv) return rv } @@ -93,7 +93,7 @@ func ListSourcePrefixes(r *armnetwork.SecurityRule) []string { rv = append(rv, *r.Properties.SourceAddressPrefix) } if r.Properties.SourceAddressPrefixes != nil { - rv = append(rv, fnutil.Map(func(data *string) string { return *data }, r.Properties.SourceAddressPrefixes)...) + rv = append(rv, lo.Map(r.Properties.SourceAddressPrefixes, func(data *string, _ int) string { return *data })...) } return rv } @@ -104,7 +104,7 @@ func ListDestinationPrefixes(r *armnetwork.SecurityRule) []string { rv = append(rv, *r.Properties.DestinationAddressPrefix) } if r.Properties.DestinationAddressPrefixes != nil { - rv = append(rv, fnutil.Map(func(key *string) string { return *key }, r.Properties.DestinationAddressPrefixes)...) + rv = append(rv, lo.Map(r.Properties.DestinationAddressPrefixes, func(key *string, _ int) string { return *key })...) } return rv } diff --git a/pkg/provider/virtualmachine/virtualmachine.go b/pkg/provider/virtualmachine/virtualmachine.go index f9b482298f..1022e5193a 100644 --- a/pkg/provider/virtualmachine/virtualmachine.go +++ b/pkg/provider/virtualmachine/virtualmachine.go @@ -18,8 +18,7 @@ package virtualmachine import ( "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - - "k8s.io/utils/ptr" + "github.com/samber/lo" "sigs.k8s.io/cloud-provider-azure/pkg/consts" ) @@ -82,10 +81,10 @@ func FromVirtualMachine(vm *compute.VirtualMachine, opt ...ManageOption) *Virtua vm: vm, Variant: VariantVirtualMachine, - ID: ptr.Deref(vm.ID, ""), - Name: ptr.Deref(vm.Name, ""), - Type: ptr.Deref(vm.Type, ""), - Location: ptr.Deref(vm.Location, ""), + ID: lo.FromPtrOr(vm.ID, ""), + Name: lo.FromPtrOr(vm.Name, ""), + Type: lo.FromPtrOr(vm.Type, ""), + Location: lo.FromPtrOr(vm.Location, ""), Tags: stringMap(vm.Tags), Zones: stringSlice(vm.Zones), Plan: vm.Plan, @@ -107,17 +106,17 @@ func FromVirtualMachineScaleSetVM(vm *compute.VirtualMachineScaleSetVM, opt Mana Variant: VariantVirtualMachineScaleSetVM, vmssVM: vm, - ID: ptr.Deref(vm.ID, ""), - Name: ptr.Deref(vm.Name, ""), - Type: ptr.Deref(vm.Type, ""), - Location: ptr.Deref(vm.Location, ""), + ID: lo.FromPtrOr(vm.ID, ""), + Name: lo.FromPtrOr(vm.Name, ""), + Type: lo.FromPtrOr(vm.Type, ""), + Location: lo.FromPtrOr(vm.Location, ""), Tags: stringMap(vm.Tags), Zones: stringSlice(vm.Zones), Plan: vm.Plan, Resources: vm.Resources, SKU: vm.Sku, - InstanceID: ptr.Deref(vm.InstanceID, ""), + InstanceID: lo.FromPtrOr(vm.InstanceID, ""), VirtualMachineScaleSetVMProperties: vm.VirtualMachineScaleSetVMProperties, } diff --git a/pkg/provider/zone/repo.go b/pkg/provider/zone/repo.go index ad3284b3ab..58e32adb9a 100644 --- a/pkg/provider/zone/repo.go +++ b/pkg/provider/zone/repo.go @@ -22,8 +22,9 @@ package zone import ( "context" + "github.com/samber/lo" + "sigs.k8s.io/cloud-provider-azure/pkg/azclient/providerclient" - fnutil "sigs.k8s.io/cloud-provider-azure/pkg/util/collectionutil" ) type Repository interface { @@ -46,7 +47,7 @@ func (r *repo) ListZones(ctx context.Context) (map[string][]string, error) { var rv = make(map[string][]string, len(zones)) for region, z := range zones { - rv[region] = fnutil.Map(func(s *string) string { return *s }, z) + rv[region] = lo.Map(z, func(s *string, _ int) string { return *s }) } return rv, nil diff --git a/pkg/util/collectionutil/map.go b/pkg/util/collectionutil/map.go deleted file mode 100644 index d214844920..0000000000 --- a/pkg/util/collectionutil/map.go +++ /dev/null @@ -1,33 +0,0 @@ -/* -Copyright 2023 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package fnutil - -func Keys[K comparable, V any](m map[K]V) []K { - rv := make([]K, 0, len(m)) - for k := range m { - rv = append(rv, k) - } - return rv -} - -func Values[K comparable, V any](m map[K]V) []V { - rv := make([]V, 0, len(m)) - for _, v := range m { - rv = append(rv, v) - } - return rv -} diff --git a/pkg/util/collectionutil/slice.go b/pkg/util/collectionutil/slice.go deleted file mode 100644 index fb1b39e7a3..0000000000 --- a/pkg/util/collectionutil/slice.go +++ /dev/null @@ -1,107 +0,0 @@ -/* -Copyright 2023 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package fnutil - -func Map[T any, R any](f func(T) R, xs []T) []R { - rv := make([]R, len(xs)) - for i, x := range xs { - rv[i] = f(x) - } - return rv -} - -func Filter[T any](f func(T) bool, xs []T) []T { - var rv []T - for _, x := range xs { - if f(x) { - rv = append(rv, x) - } - } - return rv -} - -func RemoveIf[T any](f func(T) bool, xs []T) []T { - var rv []T - for _, x := range xs { - if !f(x) { - rv = append(rv, x) - } - } - return rv -} - -func IsAll[T any](f func(T) bool, xs []T) bool { - for _, x := range xs { - if !f(x) { - return false - } - } - return true -} - -func PlanHashCode[D comparable](data D) D { return data } - -func IndexSet[D comparable](xs []D) *IndexSetWithComparableIndex[D, D] { - return NewIndexSetWithComparableIndex(PlanHashCode, xs) -} - -type IndexSetWithComparableIndex[I comparable, D any] struct { - hashCode func(data D) I - data map[I]D -} - -func NewIndexSetWithComparableIndex[I comparable, D any](hashCode func(data D) I, xs []D) *IndexSetWithComparableIndex[I, D] { - if hashCode == nil { - panic("hashCode must not be nil") - } - rv := make(map[I]D, len(xs)) - for _, x := range xs { - rv[hashCode(x)] = x - } - return &IndexSetWithComparableIndex[I, D]{ - data: rv, - hashCode: hashCode, - } -} -func (xs *IndexSetWithComparableIndex[I, D]) Contains(data D) bool { - _, ok := xs.data[xs.hashCode(data)] - return ok -} - -func (xs *IndexSetWithComparableIndex[I, D]) Intersection(ys []D) []D { - var rv []D - for _, y := range ys { - if xs.Contains(y) { - rv = append(rv, y) - } - } - return rv -} - -func (xs *IndexSetWithComparableIndex[I, D]) SubtractedBy(ys []D) []D { - var rv []D - for _, y := range ys { - if !xs.Contains(y) { - rv = append(rv, y) - } - } - return rv -} - -func Intersection[D comparable](xs, ys []D) []D { - return IndexSet(xs).Intersection(ys) -} diff --git a/pkg/util/deepcopy/deepcopy_test.go b/pkg/util/deepcopy/deepcopy_test.go index 6723ccef54..e682f0da40 100644 --- a/pkg/util/deepcopy/deepcopy_test.go +++ b/pkg/util/deepcopy/deepcopy_test.go @@ -21,9 +21,8 @@ import ( "testing" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" + "github.com/samber/lo" "github.com/stretchr/testify/assert" - - "k8s.io/utils/ptr" ) type fakeStruct struct { @@ -43,12 +42,12 @@ func TestCopyBasic(t *testing.T) { zones := []string{"zone0", "zone1"} var vmOriginal *compute.VirtualMachine = &compute.VirtualMachine{ VirtualMachineProperties: &compute.VirtualMachineProperties{ - ProvisioningState: ptr.To("Failed"), + ProvisioningState: lo.ToPtr("Failed"), }, - Name: ptr.To("vmOriginal"), + Name: lo.ToPtr("vmOriginal"), Zones: &zones, Tags: map[string]*string{ - "tag0": ptr.To("tagVal0"), + "tag0": lo.ToPtr("tagVal0"), }, } vmCopied := Copy(vmOriginal).(*compute.VirtualMachine) @@ -69,9 +68,9 @@ func TestCopyBasic(t *testing.T) { func TestCopyVMInSyncMap(t *testing.T) { var vmOriginal *compute.VirtualMachine = &compute.VirtualMachine{ VirtualMachineProperties: &compute.VirtualMachineProperties{ - ProvisioningState: ptr.To("Failed"), + ProvisioningState: lo.ToPtr("Failed"), }, - Name: ptr.To("vmOriginal"), + Name: lo.ToPtr("vmOriginal"), } vmCacheOriginal := &sync.Map{} vmCacheOriginal.Store("vmOriginal", vmOriginal) @@ -94,9 +93,9 @@ type vmssEntry struct { // TestCopyVMSSEntryInSyncMap tests object like vmssEntry in sync.Map. func TestCopyVMSSEntryInSyncMap(t *testing.T) { vmssEntryOriginal := &vmssEntry{ - Name: ptr.To("vmssEntryName"), + Name: lo.ToPtr("vmssEntryName"), VirtualMachineScaleSet: &compute.VirtualMachineScaleSet{ - Name: ptr.To("vmssOriginal"), + Name: lo.ToPtr("vmssOriginal"), }, } vmssCacheOriginal := &sync.Map{} diff --git a/pkg/util/iputil/family.go b/pkg/util/iputil/family.go index 65a8ce2203..d1d0777af5 100644 --- a/pkg/util/iputil/family.go +++ b/pkg/util/iputil/family.go @@ -19,7 +19,7 @@ package iputil import ( "net/netip" - fnutil "sigs.k8s.io/cloud-provider-azure/pkg/util/collectionutil" + "github.com/samber/lo" ) type Family string @@ -40,16 +40,16 @@ func ArePrefixesFromSameFamily(prefixes []netip.Prefix) bool { if len(prefixes) <= 1 { return true } - return fnutil.IsAll(func(p netip.Prefix) bool { + return len(lo.Filter(prefixes, func(p netip.Prefix, _ int) bool { return p.Addr().Is4() == prefixes[0].Addr().Is4() - }, prefixes) + })) == len(prefixes) } func AreAddressesFromSameFamily(addresses []netip.Addr) bool { if len(addresses) <= 1 { return true } - return fnutil.IsAll(func(p netip.Addr) bool { + return len(lo.Filter(addresses, func(p netip.Addr, _ int) bool { return p.Is4() == addresses[0].Is4() - }, addresses) + })) == len(addresses) } diff --git a/pkg/util/iputil/prefix_test.go b/pkg/util/iputil/prefix_test.go index 0875e5eb0a..2586863494 100644 --- a/pkg/util/iputil/prefix_test.go +++ b/pkg/util/iputil/prefix_test.go @@ -22,9 +22,8 @@ import ( "sort" "testing" + "github.com/samber/lo" "github.com/stretchr/testify/assert" - - fnutil "sigs.k8s.io/cloud-provider-azure/pkg/util/collectionutil" ) func TestIsPrefixesAllowAll(t *testing.T) { @@ -476,7 +475,7 @@ func FuzzAggregatePrefixesIPv4(f *testing.F) { rv[addr.String()] = struct{}{} } } - return fnutil.Keys(rv) + return lo.Keys(rv) } f.Fuzz(func( @@ -502,9 +501,9 @@ func FuzzAggregatePrefixesIPv4(f *testing.F) { input := []netip.Prefix{p1, p2, p3} output := AggregatePrefixes(input) - prefixAsString := func(p netip.Prefix) string { return p.String() } - t.Logf("input: %s", fnutil.Map(prefixAsString, input)) - t.Logf("output: %s", fnutil.Map(prefixAsString, output)) + prefixAsString := func(p netip.Prefix, _ int) string { return p.String() } + t.Logf("input: %s", lo.Map(input, prefixAsString)) + t.Logf("output: %s", lo.Map(output, prefixAsString)) expectedAddresses := listAddressesAsString(input...) actualAddresses := listAddressesAsString(output...) diff --git a/pkg/util/vm/vm.go b/pkg/util/vm/vm.go index a5084f30b9..b48fe8be30 100644 --- a/pkg/util/vm/vm.go +++ b/pkg/util/vm/vm.go @@ -20,9 +20,8 @@ import ( "strings" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" - + "github.com/samber/lo" "k8s.io/klog/v2" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/consts" stringutils "sigs.k8s.io/cloud-provider-azure/pkg/util/string" @@ -33,7 +32,7 @@ func GetVMPowerState(vmName string, vmStatuses *[]compute.InstanceViewStatus) st logger := klog.Background().WithName("getVMSSVMPowerState").WithValues("vmName", vmName) if vmStatuses != nil { for _, status := range *vmStatuses { - state := ptr.Deref(status.Code, "") + state := lo.FromPtrOr(status.Code, "") if stringutils.HasPrefixCaseInsensitive(state, consts.VMPowerStatePrefix) { return strings.TrimPrefix(state, consts.VMPowerStatePrefix) } diff --git a/pkg/util/vm/vm_test.go b/pkg/util/vm/vm_test.go index ec1cd97083..dd108c4591 100644 --- a/pkg/util/vm/vm_test.go +++ b/pkg/util/vm/vm_test.go @@ -19,8 +19,7 @@ package vm import ( "testing" - "k8s.io/utils/ptr" - + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" "github.com/stretchr/testify/assert" ) @@ -36,15 +35,15 @@ func TestGetVMPowerState(t *testing.T) { { name: "should return power state when there is power state status", vmStatuses: &[]compute.InstanceViewStatus{ - {Code: ptr.To("foo")}, - {Code: ptr.To("PowerState/Running")}, + {Code: to.Ptr("foo")}, + {Code: to.Ptr("PowerState/Running")}, }, expected: "Running", }, { name: "should return unknown when there is no power state status", vmStatuses: &[]compute.InstanceViewStatus{ - {Code: ptr.To("foo")}, + {Code: to.Ptr("foo")}, }, expected: "unknown", }, diff --git a/tests/e2e/network/ensureloadbalancer.go b/tests/e2e/network/ensureloadbalancer.go index 9968d374aa..e6fff14a7b 100644 --- a/tests/e2e/network/ensureloadbalancer.go +++ b/tests/e2e/network/ensureloadbalancer.go @@ -28,7 +28,9 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" aznetwork "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" - + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + "github.com/samber/lo" appsv1 "k8s.io/api/apps/v1" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -37,13 +39,9 @@ import ( "k8s.io/apimachinery/pkg/util/wait" clientset "k8s.io/client-go/kubernetes" cloudprovider "k8s.io/cloud-provider" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/consts" "sigs.k8s.io/cloud-provider-azure/tests/e2e/utils" - - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" ) const ( @@ -148,11 +146,11 @@ var _ = Describe("Ensure LoadBalancer", Label(utils.TestSuiteLabelLB), func() { for _, rule := range lb.Properties.LoadBalancingRules { switch { case strings.EqualFold(string(*rule.Properties.Protocol), string(v1.ProtocolTCP)): - if ptr.Deref(rule.Properties.FrontendPort, 0) == serverPort { + if lo.FromPtrOr(rule.Properties.FrontendPort, 0) == serverPort { foundTCP = true } case strings.EqualFold(string(*rule.Properties.Protocol), string(v1.ProtocolUDP)): - if ptr.Deref(rule.Properties.FrontendPort, 0) == testingPort { + if lo.FromPtrOr(rule.Properties.FrontendPort, 0) == testingPort { foundUDP = true } } @@ -166,7 +164,7 @@ var _ = Describe("Ensure LoadBalancer", Label(utils.TestSuiteLabelLB), func() { ipNameBase := basename + "-public-IP" + string(uuid.NewUUID())[0:4] v4Enabled, v6Enabled := utils.IfIPFamiliesEnabled(tc.IPFamily) expectedTags := map[string]*string{ - "foo": ptr.To("bar"), + "foo": to.Ptr("bar"), } pips := []*aznetwork.PublicIPAddress{} targetIPs := []*string{} @@ -557,7 +555,7 @@ var _ = Describe("Ensure LoadBalancer", Label(utils.TestSuiteLabelLB), func() { for _, sharedIP := range sharedIPs { pip, err := tc.GetPublicIPFromAddress(tc.GetResourceGroup(), sharedIP) Expect(err).NotTo(HaveOccurred()) - pipNames = append(pipNames, ptr.Deref(pip.Name, "")) + pipNames = append(pipNames, lo.FromPtrOr(pip.Name, "")) } utils.Logf("update pip names %s", strings.Join(pipNames, ",")) service = updateServicePIPNames(tc.IPFamily, service, pipNames) @@ -611,8 +609,8 @@ var _ = Describe("Ensure LoadBalancer", Label(utils.TestSuiteLabelLB), func() { } for _, pip := range pips { - if _, ok := sharedIPsMap[ptr.Deref(pip.Properties.IPAddress, "")]; ok { - utils.Logf("the public IP with address %s still exists", ptr.Deref(pip.Properties.IPAddress, "")) + if _, ok := sharedIPsMap[lo.FromPtrOr(pip.Properties.IPAddress, "")]; ok { + utils.Logf("the public IP with address %s still exists", lo.FromPtrOr(pip.Properties.IPAddress, "")) return false, nil } } @@ -722,7 +720,7 @@ var _ = Describe("Ensure LoadBalancer", Label(utils.TestSuiteLabelLB), func() { for _, ip := range lbBackendPoolIPs { Expect(ip.Properties).NotTo(BeNil()) Expect(ip.Properties.NetworkInterfaceIPConfiguration).NotTo(BeNil()) - ipConfigID := ptr.Deref(ip.Properties.NetworkInterfaceIPConfiguration.ID, "") + ipConfigID := lo.FromPtrOr(ip.Properties.NetworkInterfaceIPConfiguration.ID, "") if !strings.Contains(ipConfigID, utils.SystemPool) { lbBackendPoolIPCount++ } @@ -823,7 +821,7 @@ var _ = Describe("Ensure LoadBalancer", Label(utils.TestSuiteLabelLB), func() { continue } utils.Logf("%q is the corresponding rule of the Service", *lbRule.Name) - Expect(ptr.Deref(lbRule.Properties.EnableFloatingIP, false)).To(BeFalse()) + Expect(lo.FromPtrOr(lbRule.Properties.EnableFloatingIP, false)).To(BeFalse()) found = true break } @@ -998,9 +996,9 @@ var _ = Describe("EnsureLoadBalancer should not update any resources when servic Expect(err).NotTo(HaveOccurred()) if tc.IPFamily == utils.DualStack { - annotation[consts.ServiceAnnotationPIPPrefixIDDualStack[isIPv6]] = ptr.Deref(prefix.ID, "") + annotation[consts.ServiceAnnotationPIPPrefixIDDualStack[isIPv6]] = lo.FromPtrOr(prefix.ID, "") } else { - annotation[consts.ServiceAnnotationPIPPrefixIDDualStack[false]] = ptr.Deref(prefix.ID, "") + annotation[consts.ServiceAnnotationPIPPrefixIDDualStack[false]] = lo.FromPtrOr(prefix.ID, "") } return deleteFunc } @@ -1043,13 +1041,13 @@ var _ = Describe("EnsureLoadBalancer should not update any resources when servic By("Creating a subnet for ilb frontend ip") subnetName := "testSubnet" subnet, isNew := createNewSubnet(tc, subnetName) - Expect(ptr.Deref(subnet.Name, "")).To(Equal(subnetName)) + Expect(lo.FromPtrOr(subnet.Name, "")).To(Equal(subnetName)) if isNew { defer func() { utils.Logf("cleaning up test subnet %s", subnetName) vNet, err := tc.GetClusterVirtualNetwork() Expect(err).NotTo(HaveOccurred()) - err = tc.DeleteSubnet(ptr.Deref(vNet.Name, ""), subnetName) + err = tc.DeleteSubnet(lo.FromPtrOr(vNet.Name, ""), subnetName) Expect(err).NotTo(HaveOccurred()) }() } @@ -1153,9 +1151,9 @@ func createNewSubnet(tc *utils.AzureTestClient, subnetName string) (*aznetwork.S func getResourceEtags(tc *utils.AzureTestClient, ip *string, nsgRulePrefix string, internal bool) (lbEtag, nsgEtag, pipEtag string) { if internal { - lbEtag = ptr.Deref(getAzureInternalLoadBalancerFromPrivateIP(tc, ip, "").Etag, "") + lbEtag = lo.FromPtrOr(getAzureInternalLoadBalancerFromPrivateIP(tc, ip, "").Etag, "") } else { - lbEtag = ptr.Deref(getAzureLoadBalancerFromPIP(tc, ip, tc.GetResourceGroup(), "").Etag, "") + lbEtag = lo.FromPtrOr(getAzureLoadBalancerFromPIP(tc, ip, tc.GetResourceGroup(), "").Etag, "") } nsgs, err := tc.GetClusterSecurityGroups() @@ -1165,9 +1163,9 @@ func getResourceEtags(tc *utils.AzureTestClient, ip *string, nsgRulePrefix strin continue } for _, securityRule := range nsg.Properties.SecurityRules { - utils.Logf("Checking security rule %q", ptr.Deref(securityRule.Name, "")) - if strings.HasPrefix(ptr.Deref(securityRule.Name, ""), nsgRulePrefix) { - nsgEtag = ptr.Deref(nsg.Etag, "") + utils.Logf("Checking security rule %q", lo.FromPtrOr(securityRule.Name, "")) + if strings.HasPrefix(lo.FromPtrOr(securityRule.Name, ""), nsgRulePrefix) { + nsgEtag = lo.FromPtrOr(nsg.Etag, "") break } } @@ -1176,7 +1174,7 @@ func getResourceEtags(tc *utils.AzureTestClient, ip *string, nsgRulePrefix strin if !internal { pip, err := tc.GetPublicIPFromAddress(tc.GetResourceGroup(), ip) Expect(err).NotTo(HaveOccurred()) - pipEtag = ptr.Deref(pip.Etag, "") + pipEtag = lo.FromPtrOr(pip.Etag, "") } utils.Logf("Got resource etags: lbEtag: %s; nsgEtag: %s, pipEtag: %s", lbEtag, nsgEtag, pipEtag) return @@ -1224,7 +1222,7 @@ func waitForNodesInLBBackendPool(tc *utils.AzureTestClient, ip *string, expected if lbBackendPoolIPConfigs != nil { ipConfigNum = len(lbBackendPoolIPConfigs) for _, ipConfig := range lbBackendPoolIPConfigs { - ipConfigIDs = append(ipConfigIDs, ptr.Deref(ipConfig.ID, "")) + ipConfigIDs = append(ipConfigIDs, lo.FromPtrOr(ipConfig.ID, "")) } } if expectedNum == ipConfigNum { @@ -1255,7 +1253,7 @@ func waitForNodesInLBBackendPool(tc *utils.AzureTestClient, ip *string, expected ip.Properties.NetworkInterfaceIPConfiguration == nil { return false, fmt.Errorf("LB backendPool address's NIC IP config ID is nil") } - ipConfigID := ptr.Deref(ip.Properties.NetworkInterfaceIPConfiguration.ID, "") + ipConfigID := lo.FromPtrOr(ip.Properties.NetworkInterfaceIPConfiguration.ID, "") if !strings.Contains(ipConfigID, utils.SystemPool) { ipNum++ ipConfigIDs = append(ipConfigIDs, ipConfigID) @@ -1340,8 +1338,8 @@ func defaultPublicIPAddress(ipName string, isIPv6 bool) *aznetwork.PublicIPAddre } } pip := &aznetwork.PublicIPAddress{ - Name: ptr.To(ipName), - Location: ptr.To(os.Getenv(utils.ClusterLocationEnv)), + Name: to.Ptr(ipName), + Location: to.Ptr(os.Getenv(utils.ClusterLocationEnv)), SKU: &aznetwork.PublicIPAddressSKU{ Name: to.Ptr(skuName), }, @@ -1363,13 +1361,13 @@ func defaultPublicIPPrefix(name string, isIPv6 bool) aznetwork.PublicIPPrefix { prefixLen = 124 } return aznetwork.PublicIPPrefix{ - Name: ptr.To(name), - Location: ptr.To(os.Getenv(utils.ClusterLocationEnv)), + Name: to.Ptr(name), + Location: to.Ptr(os.Getenv(utils.ClusterLocationEnv)), SKU: &aznetwork.PublicIPPrefixSKU{ Name: to.Ptr(aznetwork.PublicIPPrefixSKUNameStandard), }, Properties: &aznetwork.PublicIPPrefixPropertiesFormat{ - PrefixLength: ptr.To(prefixLen), + PrefixLength: to.Ptr(prefixLen), PublicIPAddressVersion: to.Ptr(pipAddrVersion), }, } @@ -1379,7 +1377,7 @@ func createPIP(tc *utils.AzureTestClient, ipNameBase string, isIPv6 bool) (strin ipName := utils.GetNameWithSuffix(ipNameBase, utils.Suffixes[isIPv6]) pip, err := utils.WaitCreatePIP(tc, ipName, tc.GetResourceGroup(), defaultPublicIPAddress(ipName, isIPv6)) Expect(err).NotTo(HaveOccurred()) - targetIP := ptr.Deref(pip.Properties.IPAddress, "") + targetIP := lo.FromPtrOr(pip.Properties.IPAddress, "") utils.Logf("Created PIP to %s", targetIP) return targetIP, func() { By("Cleaning up PIP") diff --git a/tests/e2e/network/multiple_standard_lb.go b/tests/e2e/network/multiple_standard_lb.go index 219dd09de0..5c1b384904 100644 --- a/tests/e2e/network/multiple_standard_lb.go +++ b/tests/e2e/network/multiple_standard_lb.go @@ -23,6 +23,10 @@ import ( "strings" "time" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + "github.com/samber/lo" appsv1 "k8s.io/api/apps/v1" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -30,12 +34,8 @@ import ( "k8s.io/apimachinery/pkg/util/sets" "k8s.io/apimachinery/pkg/util/wait" clientset "k8s.io/client-go/kubernetes" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/tests/e2e/utils" - - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" ) var _ = Describe("Ensure LoadBalancer", Label(utils.TestSuiteLabelMultiSLB), func() { @@ -112,10 +112,10 @@ var _ = Describe("Ensure LoadBalancer", Label(utils.TestSuiteLabelMultiSLB), fun for _, svcIP := range svcIPs { lb := getAzureLoadBalancerFromPIP(tc, svcIP, tc.GetResourceGroup(), tc.GetResourceGroup()) - lbName := ptr.Deref(lb.Name, "") + lbName := lo.FromPtrOr(lb.Name, "") for _, bp := range lb.Properties.BackendAddressPools { for _, a := range bp.Properties.LoadBalancerBackendAddresses { - nodeName := ptr.Deref(a.Name, "") + nodeName := lo.FromPtrOr(a.Name, "") expectedVMSSName := lbNameToExpectedVMSetNameMap[lbName] if nodeName == "" || !strings.HasPrefix(nodeName, expectedVMSSName) { Fail(fmt.Sprintf("Node %s is not in the expected VMSS %s on LB %s", nodeName, expectedVMSSName, lbName)) @@ -140,7 +140,7 @@ var _ = Describe("Ensure LoadBalancer", Label(utils.TestSuiteLabelMultiSLB), fun svcIP := svsWithLabel.Status.LoadBalancer.Ingress[0].IP svcIPs = append(svcIPs, &svcIP) lb := getAzureLoadBalancerFromPIP(tc, &svcIP, tc.GetResourceGroup(), tc.GetResourceGroup()) - Expect(ptr.Deref(lb.Name, "")).To(Equal("lb-2")) + Expect(lo.FromPtrOr(lb.Name, "")).To(Equal("lb-2")) svcCount := 2 var svc *v1.Service @@ -195,10 +195,10 @@ var _ = Describe("Ensure LoadBalancer", Label(utils.TestSuiteLabelMultiSLB), fun Expect(err).NotTo(HaveOccurred()) By("Scaling the deployment to 3 replicas and then to 1") - deployment.Spec.Replicas = ptr.To(int32(3)) + deployment.Spec.Replicas = to.Ptr(int32(3)) _, err = cs.AppsV1().Deployments(ns.Name).Update(context.Background(), deployment, metav1.UpdateOptions{}) Expect(err).NotTo(HaveOccurred()) - deployment.Spec.Replicas = ptr.To(int32(1)) + deployment.Spec.Replicas = to.Ptr(int32(1)) _, err = cs.AppsV1().Deployments(ns.Name).Update(context.Background(), deployment, metav1.UpdateOptions{}) Expect(err).NotTo(HaveOccurred()) @@ -215,7 +215,7 @@ var _ = Describe("Ensure LoadBalancer", Label(utils.TestSuiteLabelMultiSLB), fun Expect(err).NotTo(HaveOccurred()) By("Scaling the deployment to 5") - deployment.Spec.Replicas = ptr.To(int32(5)) + deployment.Spec.Replicas = to.Ptr(int32(5)) _, err = cs.AppsV1().Deployments(ns.Name).Update(context.Background(), deployment, metav1.UpdateOptions{}) Expect(err).NotTo(HaveOccurred()) nodeNames, err = getDeploymentPodsNodeNames(cs, ns.Name, testDeploymentName) @@ -268,14 +268,14 @@ func getDeploymentPodsNodeNames(kubeClient clientset.Interface, namespace, deplo func checkNodeCountInBackendPoolByServiceIPs(tc *utils.AzureTestClient, expectedLBName, bpName string, svcIPs []*string, expectedCount int) error { for _, svcIP := range svcIPs { lb := getAzureLoadBalancerFromPIP(tc, svcIP, tc.GetResourceGroup(), tc.GetResourceGroup()) - lbName := ptr.Deref(lb.Name, "") + lbName := lo.FromPtrOr(lb.Name, "") if !strings.EqualFold(lbName, expectedLBName) { return fmt.Errorf("expected load balancer name %s, actual %s", expectedLBName, lbName) } var found bool for _, bp := range lb.Properties.BackendAddressPools { - if strings.HasPrefix(strings.ToLower(ptr.Deref(bp.Name, "")), strings.ToLower(bpName)) { + if strings.HasPrefix(strings.ToLower(lo.FromPtrOr(bp.Name, "")), strings.ToLower(bpName)) { found = true } if len(bp.Properties.LoadBalancerBackendAddresses) != expectedCount { @@ -293,7 +293,7 @@ func getLBsFromPublicIPs(tc *utils.AzureTestClient, pips []*string) sets.Set[str lbNames := sets.New[string]() for _, svcIP := range pips { lb := getAzureLoadBalancerFromPIP(tc, svcIP, tc.GetResourceGroup(), tc.GetResourceGroup()) - lbName := ptr.Deref(lb.Name, "") + lbName := lo.FromPtrOr(lb.Name, "") lbNames.Insert(lbName) } return lbNames diff --git a/tests/e2e/network/network_security_group.go b/tests/e2e/network/network_security_group.go index 491afd025d..c93613fe5a 100644 --- a/tests/e2e/network/network_security_group.go +++ b/tests/e2e/network/network_security_group.go @@ -23,17 +23,15 @@ import ( "strconv" "strings" + aznetwork "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - - aznetwork "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" - + "github.com/samber/lo" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/apimachinery/pkg/util/sets" clientset "k8s.io/client-go/kubernetes" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/consts" "sigs.k8s.io/cloud-provider-azure/tests/e2e/utils" @@ -54,13 +52,6 @@ var _ = Describe("Network security group", Label(utils.TestSuiteLabelNSG), func( // Helpers var ( - derefSliceOfStringPtr = func(vs []*string) []string { - rv := make([]string, 0, len(vs)) - for _, v := range vs { - rv = append(rv, *v) - } - return rv - } mustParseIPs = func(ips []string) []netip.Addr { rv := make([]netip.Addr, 0, len(ips)) for _, ip := range ips { @@ -145,7 +136,7 @@ var _ = Describe("Network security group", Label(utils.TestSuiteLabelNSG), func( }} ) rv := createAndExposeDefaultServiceWithAnnotation(k8sClient, azureClient.IPFamily, ServiceName, namespace.Name, labels, annotations, ports) - serviceIPv4s, serviceIPv6s = groupIPsByFamily(mustParseIPs(derefSliceOfStringPtr(rv))) + serviceIPv4s, serviceIPv6s = groupIPsByFamily(mustParseIPs(lo.FromSlicePtr(rv))) }) logger.Info("Created a LoadBalancer service", "v4-IPs", serviceIPv4s, "v6-IPs", serviceIPv6s) @@ -201,7 +192,7 @@ var _ = Describe("Network security group", Label(utils.TestSuiteLabelNSG), func( }} ) rv := createAndExposeDefaultServiceWithAnnotation(k8sClient, azureClient.IPFamily, ServiceName, namespace.Name, labels, annotations, ports) - serviceIPv4s, serviceIPv6s = groupIPsByFamily(mustParseIPs(derefSliceOfStringPtr(rv))) + serviceIPv4s, serviceIPv6s = groupIPsByFamily(mustParseIPs(lo.FromSlicePtr(rv))) }) var validator *SecurityGroupValidator @@ -275,7 +266,7 @@ var _ = Describe("Network security group", Label(utils.TestSuiteLabelNSG), func( }} ) rv := createAndExposeDefaultServiceWithAnnotation(k8sClient, azureClient.IPFamily, ServiceName, namespace.Name, labels, annotations, ports) - serviceIPv4s, serviceIPv6s = groupIPsByFamily(mustParseIPs(derefSliceOfStringPtr(rv))) + serviceIPv4s, serviceIPv6s = groupIPsByFamily(mustParseIPs(lo.FromSlicePtr(rv))) }) logger.Info("Created a LoadBalancer service", "v4-IPs", serviceIPv4s, "v6-IPs", serviceIPv6s) @@ -347,7 +338,7 @@ var _ = Describe("Network security group", Label(utils.TestSuiteLabelNSG), func( }} ) rv := createAndExposeDefaultServiceWithAnnotation(k8sClient, azureClient.IPFamily, ServiceName, namespace.Name, labels, annotations, ports) - serviceIPv4s, serviceIPv6s = groupIPsByFamily(mustParseIPs(derefSliceOfStringPtr(rv))) + serviceIPv4s, serviceIPv6s = groupIPsByFamily(mustParseIPs(lo.FromSlicePtr(rv))) }) logger.Info("Created a LoadBalancer service", "v4-IPs", serviceIPv4s, "v6-IPs", serviceIPv6s) @@ -414,7 +405,7 @@ var _ = Describe("Network security group", Label(utils.TestSuiteLabelNSG), func( }} ) rv := createAndExposeDefaultServiceWithAnnotation(k8sClient, azureClient.IPFamily, ServiceName, namespace.Name, labels, annotations, ports) - serviceIPv4s, serviceIPv6s = groupIPsByFamily(mustParseIPs(derefSliceOfStringPtr(rv))) + serviceIPv4s, serviceIPv6s = groupIPsByFamily(mustParseIPs(lo.FromSlicePtr(rv))) }) var validator *SecurityGroupValidator @@ -496,7 +487,7 @@ var _ = Describe("Network security group", Label(utils.TestSuiteLabelNSG), func( }} ) rv := createAndExposeDefaultServiceWithAnnotation(k8sClient, azureClient.IPFamily, Service1Name, namespace.Name, labels, annotations, ports) - svc1IPv4s, svc1IPv6s = groupIPsByFamily(mustParseIPs(derefSliceOfStringPtr(rv))) + svc1IPv4s, svc1IPv6s = groupIPsByFamily(mustParseIPs(lo.FromSlicePtr(rv))) logger.Info("Created the first LoadBalancer service", "svc-name", Service1Name, "v4-IPs", svc1IPv4s, "v6-IPs", svc1IPv6s) }) @@ -516,7 +507,7 @@ var _ = Describe("Network security group", Label(utils.TestSuiteLabelNSG), func( ) rv := createAndExposeDefaultServiceWithAnnotation(k8sClient, azureClient.IPFamily, Service2Name, namespace.Name, labels, annotations, ports) - svc2IPv4s, svc2IPv6s = groupIPsByFamily(mustParseIPs(derefSliceOfStringPtr(rv))) + svc2IPv4s, svc2IPv6s = groupIPsByFamily(mustParseIPs(lo.FromSlicePtr(rv))) logger.Info("Created the second LoadBalancer service", "svc-name", Service2Name, "v4-IPs", svc2IPv4s, "v6-IPs", svc2IPv6s) }) @@ -592,7 +583,7 @@ var _ = Describe("Network security group", Label(utils.TestSuiteLabelNSG), func( }} ) rv := createAndExposeDefaultServiceWithAnnotation(k8sClient, azureClient.IPFamily, ServiceName, namespace.Name, labels, annotations, ports) - serviceIPv4s, serviceIPv6s = groupIPsByFamily(mustParseIPs(derefSliceOfStringPtr(rv))) + serviceIPv4s, serviceIPv6s = groupIPsByFamily(mustParseIPs(lo.FromSlicePtr(rv))) }) logger.Info("Created a LoadBalancer service", "v4-IPs", serviceIPv4s, "v6-IPs", serviceIPv6s) @@ -677,7 +668,7 @@ var _ = Describe("Network security group", Label(utils.TestSuiteLabelNSG), func( }} ) rv := createAndExposeDefaultServiceWithAnnotation(k8sClient, azureClient.IPFamily, ServiceName, namespace.Name, labels, annotations, ports) - serviceIPv4s, serviceIPv6s = groupIPsByFamily(mustParseIPs(derefSliceOfStringPtr(rv))) + serviceIPv4s, serviceIPv6s = groupIPsByFamily(mustParseIPs(lo.FromSlicePtr(rv))) }) logger.Info("Created a LoadBalancer service", "v4-IPs", serviceIPv4s, "v6-IPs", serviceIPv6s) @@ -746,7 +737,7 @@ var _ = Describe("Network security group", Label(utils.TestSuiteLabelNSG), func( }} ) rv := createAndExposeDefaultServiceWithAnnotation(k8sClient, azureClient.IPFamily, ServiceName, namespace.Name, labels, annotations, ports) - serviceIPv4s, serviceIPv6s = groupIPsByFamily(mustParseIPs(derefSliceOfStringPtr(rv))) + serviceIPv4s, serviceIPv6s = groupIPsByFamily(mustParseIPs(lo.FromSlicePtr(rv))) }) logger.Info("Created a LoadBalancer service", "v4-IPs", serviceIPv4s, "v6-IPs", serviceIPv6s) @@ -830,7 +821,7 @@ var _ = Describe("Network security group", Label(utils.TestSuiteLabelNSG), func( }} ) rv := createAndExposeDefaultServiceWithAnnotation(k8sClient, azureClient.IPFamily, ServiceName, namespace.Name, labels, annotations, ports) - serviceIPv4s, serviceIPv6s = groupIPsByFamily(mustParseIPs(derefSliceOfStringPtr(rv))) + serviceIPv4s, serviceIPv6s = groupIPsByFamily(mustParseIPs(lo.FromSlicePtr(rv))) }) logger.Info("Created a LoadBalancer service", "v4-IPs", serviceIPv4s, "v6-IPs", serviceIPv6s) @@ -938,7 +929,7 @@ var _ = Describe("Network security group", Label(utils.TestSuiteLabelNSG), func( }} ) rv := createAndExposeDefaultServiceWithAnnotation(k8sClient, azureClient.IPFamily, Service1Name, namespace.Name, labels, annotations, ports) - svc1IPv4s, svc1IPv6s = groupIPsByFamily(mustParseIPs(derefSliceOfStringPtr(rv))) + svc1IPv4s, svc1IPv6s = groupIPsByFamily(mustParseIPs(lo.FromSlicePtr(rv))) logger.Info("Created the first LoadBalancer service", "svc-name", Service1Name, "v4-IPs", svc1IPv4s, "v6-IPs", svc1IPv6s) }) @@ -967,7 +958,7 @@ var _ = Describe("Network security group", Label(utils.TestSuiteLabelNSG), func( ) rv := createAndExposeDefaultServiceWithAnnotation(k8sClient, azureClient.IPFamily, Service2Name, namespace.Name, labels, annotations, ports) - svc2IPv4s, svc2IPv6s := groupIPsByFamily(mustParseIPs(derefSliceOfStringPtr(rv))) + svc2IPv4s, svc2IPv6s := groupIPsByFamily(mustParseIPs(lo.FromSlicePtr(rv))) logger.Info("Created the second LoadBalancer service", "svc-name", Service2Name, "v4-IPs", svc2IPv4s, "v6-IPs", svc2IPv6s) Expect(svc2IPv4s).To(Equal(svc1IPv4s)) Expect(svc2IPv6s).To(Equal(svc1IPv6s)) @@ -1038,15 +1029,15 @@ var _ = Describe("Network security group", Label(utils.TestSuiteLabelNSG), func( switch ipFamily { case utils.IPv4: svc.Spec.IPFamilies = []v1.IPFamily{v1.IPv4Protocol} - svc.Spec.IPFamilyPolicy = ptr.To(v1.IPFamilyPolicySingleStack) + svc.Spec.IPFamilyPolicy = lo.ToPtr(v1.IPFamilyPolicySingleStack) svc.Annotations[consts.ServiceAnnotationPIPNameDualStack[false]] = ipv4PIPName case utils.IPv6: svc.Spec.IPFamilies = []v1.IPFamily{v1.IPv6Protocol} - svc.Spec.IPFamilyPolicy = ptr.To(v1.IPFamilyPolicySingleStack) + svc.Spec.IPFamilyPolicy = lo.ToPtr(v1.IPFamilyPolicySingleStack) svc.Annotations[consts.ServiceAnnotationPIPNameDualStack[false]] = ipv6PIPName case utils.DualStack: svc.Spec.IPFamilies = []v1.IPFamily{v1.IPv4Protocol, v1.IPv6Protocol} - svc.Spec.IPFamilyPolicy = ptr.To(v1.IPFamilyPolicyPreferDualStack) + svc.Spec.IPFamilyPolicy = lo.ToPtr(v1.IPFamilyPolicyPreferDualStack) svc.Annotations[consts.ServiceAnnotationPIPNameDualStack[false]] = ipv4PIPName svc.Annotations[consts.ServiceAnnotationPIPNameDualStack[true]] = ipv6PIPName default: @@ -1105,7 +1096,7 @@ var _ = Describe("Network security group", Label(utils.TestSuiteLabelNSG), func( rv := createAndExposeDefaultServiceWithAnnotation(k8sClient, azureClient.IPFamily, Service1Name, namespace.Name, labels, annotations, ports, func(svc *v1.Service) error { return applyIPFamilyForService(svc, azureClient.IPFamily, ipv4PIPName, ipv6PIPName) }) - ipv4s, ipv6s := groupIPsByFamily(mustParseIPs(derefSliceOfStringPtr(rv))) + ipv4s, ipv6s := groupIPsByFamily(mustParseIPs(lo.FromSlicePtr(rv))) logger.Info("Created the first LoadBalancer service", "svc-name", Service1Name, "v4-IPs", ipv4s, "v6-IPs", ipv6s) Expect(ipv4s).To(Equal(ipv4PIPs)) Expect(ipv6s).To(Equal(ipv6PIPs)) @@ -1126,7 +1117,7 @@ var _ = Describe("Network security group", Label(utils.TestSuiteLabelNSG), func( rv := createAndExposeDefaultServiceWithAnnotation(k8sClient, azureClient.IPFamily, Service2Name, namespace.Name, labels, annotations, ports, func(svc *v1.Service) error { return applyIPFamilyForService(svc, azureClient.IPFamily, ipv4PIPName, ipv6PIPName) }) - ipv4s, ipv6s := groupIPsByFamily(mustParseIPs(derefSliceOfStringPtr(rv))) + ipv4s, ipv6s := groupIPsByFamily(mustParseIPs(lo.FromSlicePtr(rv))) logger.Info("Created the second LoadBalancer service", "svc-name", Service2Name, "v4-IPs", ipv4s, "v6-IPs", ipv6s) Expect(ipv4s).To(Equal(ipv4PIPs)) Expect(ipv6s).To(Equal(ipv6PIPs)) @@ -1294,7 +1285,7 @@ func SecurityGroupHasAllowRuleForDestination( if *rule.Properties.Access != aznetwork.SecurityRuleAccessAllow || *rule.Properties.Direction != aznetwork.SecurityRuleDirectionInbound || *rule.Properties.Protocol != protocol || - ptr.Deref(rule.Properties.SourcePortRange, "") != "*" || + lo.FromPtrOr(rule.Properties.SourcePortRange, "") != "*" || len(rule.Properties.DestinationPortRanges) != len(dstPorts) { logger.Info("skip rule", "rule", rule) continue @@ -1369,9 +1360,9 @@ func SecurityGroupHasDenyAllRuleForDestination(nsg *aznetwork.SecurityGroup, dst for _, rule := range nsg.Properties.SecurityRules { if *rule.Properties.Access != aznetwork.SecurityRuleAccessDeny || - ptr.Deref(rule.Properties.SourceAddressPrefix, "") != "*" || - ptr.Deref(rule.Properties.SourcePortRange, "") != "*" || - ptr.Deref(rule.Properties.DestinationPortRange, "") != "*" { + lo.FromPtrOr(rule.Properties.SourceAddressPrefix, "") != "*" || + lo.FromPtrOr(rule.Properties.SourcePortRange, "") != "*" || + lo.FromPtrOr(rule.Properties.DestinationPortRange, "") != "*" { logger.Info("skip rule", "rule-name", rule.Name) continue } diff --git a/tests/e2e/network/node.go b/tests/e2e/network/node.go index 17ff7a95a7..273c7604dc 100644 --- a/tests/e2e/network/node.go +++ b/tests/e2e/network/node.go @@ -29,13 +29,12 @@ import ( network "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - + "github.com/samber/lo" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/apimachinery/pkg/util/wait" clientset "k8s.io/client-go/kubernetes" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/consts" "sigs.k8s.io/cloud-provider-azure/tests/e2e/utils" @@ -201,7 +200,7 @@ var _ = Describe("Azure node resources", Label(utils.TestSuiteLabelNode), func() utils.Logf("getting all NICs of VMSS VMs") for _, vmssVM := range vmssVMs { - utils.Logf("Checking VMSS VM %q", ptr.Deref(vmssVM.Name, "")) + utils.Logf("Checking VMSS VM %q", lo.FromPtrOr(vmssVM.Name, "")) nodeName, err := utils.GetVMSSVMComputerName(vmssVM) Expect(err).NotTo(HaveOccurred()) diff --git a/tests/e2e/network/private_link_service.go b/tests/e2e/network/private_link_service.go index 43c973723d..9c49720393 100644 --- a/tests/e2e/network/private_link_service.go +++ b/tests/e2e/network/private_link_service.go @@ -27,13 +27,12 @@ import ( network "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - + "github.com/samber/lo" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/apimachinery/pkg/util/wait" clientset "k8s.io/client-go/kubernetes" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/consts" "sigs.k8s.io/cloud-provider-azure/tests/e2e/utils" @@ -153,7 +152,7 @@ var _ = Describe("Private link service", Label(utils.TestSuiteLabelPrivateLinkSe It("should support service annotation 'service.beta.kubernetes.io/azure-pls-resource-group'", func() { By("creating a test resource group") rg, cleanup := utils.CreateTestResourceGroup(tc) - defer cleanup(ptr.Deref(rg.Name, "")) + defer cleanup(lo.FromPtrOr(rg.Name, "")) By("creating a test pls specifying the test resource group") plsName := "testpls" @@ -161,7 +160,7 @@ var _ = Describe("Private link service", Label(utils.TestSuiteLabelPrivateLinkSe consts.ServiceAnnotationLoadBalancerInternal: "true", consts.ServiceAnnotationPLSCreation: "true", consts.ServiceAnnotationPLSName: plsName, - consts.ServiceAnnotationPLSResourceGroup: ptr.Deref(rg.Name, ""), + consts.ServiceAnnotationPLSResourceGroup: lo.FromPtrOr(rg.Name, ""), } ips := createAndExposeDefaultServiceWithAnnotation(cs, tc.IPFamily, serviceName, ns.Name, labels, annotation, ports) @@ -175,20 +174,20 @@ var _ = Describe("Private link service", Label(utils.TestSuiteLabelPrivateLinkSe utils.Logf("Get Internal IP: %s", ip) // get pls from azure client - pls := getPrivateLinkServiceFromIP(tc, ip, ptr.Deref(rg.Name, ""), "", plsName) + pls := getPrivateLinkServiceFromIP(tc, ip, lo.FromPtrOr(rg.Name, ""), "", plsName) Expect(*pls.Name).To(Equal(plsName)) }) It("should support service annotation 'service.beta.kubernetes.io/azure-pls-ip-configuration-subnet'", func() { subnetName := "pls-subnet" subnet, isNew := createNewSubnet(tc, subnetName) - Expect(ptr.Deref(subnet.Name, "")).To(Equal(subnetName)) + Expect(lo.FromPtrOr(subnet.Name, "")).To(Equal(subnetName)) if isNew { defer func() { utils.Logf("cleaning up test subnet %s", subnetName) vNet, err := tc.GetClusterVirtualNetwork() Expect(err).NotTo(HaveOccurred()) - err = tc.DeleteSubnet(ptr.Deref(vNet.Name, ""), subnetName) + err = tc.DeleteSubnet(lo.FromPtrOr(vNet.Name, ""), subnetName) Expect(err).NotTo(HaveOccurred()) }() } diff --git a/tests/e2e/network/service_annotations.go b/tests/e2e/network/service_annotations.go index 10f437c4b2..8db5876dc5 100644 --- a/tests/e2e/network/service_annotations.go +++ b/tests/e2e/network/service_annotations.go @@ -29,7 +29,9 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" network "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" - + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + "github.com/samber/lo" appsv1 "k8s.io/api/apps/v1" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -39,13 +41,9 @@ import ( "k8s.io/apimachinery/pkg/util/wait" clientset "k8s.io/client-go/kubernetes" "k8s.io/client-go/util/retry" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/consts" "sigs.k8s.io/cloud-provider-azure/tests/e2e/utils" - - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" ) var ( @@ -406,7 +404,7 @@ var _ = Describe("Service with annotation", Label(utils.TestSuiteLabelServiceAnn It("should support service annotation 'service.beta.kubernetes.io/azure-load-balancer-resource-group'", func() { By("creating a test resource group") rg, cleanup := utils.CreateTestResourceGroup(tc) - defer cleanup(ptr.Deref(rg.Name, "")) + defer cleanup(lo.FromPtrOr(rg.Name, "")) By("creating test PIP in the test resource group") pips := []*string{} @@ -437,7 +435,7 @@ var _ = Describe("Service with annotation", Label(utils.TestSuiteLabelServiceAnn }() annotation := map[string]string{ - consts.ServiceAnnotationLoadBalancerResourceGroup: ptr.Deref(rg.Name, ""), + consts.ServiceAnnotationLoadBalancerResourceGroup: lo.FromPtrOr(rg.Name, ""), } By("Creating service " + serviceName + " in namespace " + ns.Name) service := utils.CreateLoadBalancerServiceManifest(serviceName, annotation, labels, ns.Name, ports) @@ -462,10 +460,10 @@ var _ = Describe("Service with annotation", Label(utils.TestSuiteLabelServiceAnn } expectedTags := map[string]*string{ - "a": ptr.To("c"), - "c": ptr.To("d"), - "e": ptr.To(""), - "x": ptr.To("y"), + "a": lo.ToPtr("c"), + "c": lo.ToPtr("d"), + "e": lo.ToPtr(""), + "x": lo.ToPtr("y"), } testPIPTagAnnotationWithTags(cs, tc, ns, serviceName, labels, ports, expectedTags) @@ -477,8 +475,8 @@ var _ = Describe("Service with annotation", Label(utils.TestSuiteLabelServiceAnn } expectedTags := map[string]*string{ - "a": ptr.To("c"), - "x": ptr.To("y"), + "a": lo.ToPtr("c"), + "x": lo.ToPtr("y"), } testPIPTagAnnotationWithTags(cs, tc, ns, serviceName, labels, ports, expectedTags) @@ -582,7 +580,7 @@ var _ = Describe("Service with annotation", Label(utils.TestSuiteLabelServiceAnn Expect(utils.DeletePIPPrefixWithRetry(tc, prefixName)).NotTo(HaveOccurred()) }) Expect(err).NotTo(HaveOccurred()) - prefixIDs1[isIPv6] = ptr.Deref(prefix.ID, "") + prefixIDs1[isIPv6] = lo.FromPtrOr(prefix.ID, "") prefixName = utils.GetNameWithSuffix(prefix2NameBase, utils.Suffixes[isIPv6]) prefixNames2[isIPv6] = prefixName @@ -591,7 +589,7 @@ var _ = Describe("Service with annotation", Label(utils.TestSuiteLabelServiceAnn Expect(utils.DeletePIPPrefixWithRetry(tc, prefixName)).NotTo(HaveOccurred()) }) Expect(err).NotTo(HaveOccurred()) - prefixIDs2[isIPv6] = ptr.Deref(prefix.ID, "") + prefixIDs2[isIPv6] = lo.FromPtrOr(prefix.ID, "") } if v4Enabled { createPIPPrefix(false) @@ -635,8 +633,8 @@ var _ = Describe("Service with annotation", Label(utils.TestSuiteLabelServiceAnn Expect(err).NotTo(HaveOccurred()) Expect(pip.Properties.IPAddress).NotTo(BeNil()) - Expect(ptr.Deref(pip.Properties.PublicIPPrefix.ID, "")).To(Equal(prefixIDs1[isIPv6])) - Expect(*ip).To(Equal(ptr.Deref(pip.Properties.IPAddress, ""))) + Expect(lo.FromPtrOr(pip.Properties.PublicIPPrefix.ID, "")).To(Equal(prefixIDs1[isIPv6])) + Expect(*ip).To(Equal(lo.FromPtrOr(pip.Properties.IPAddress, ""))) } } @@ -665,8 +663,8 @@ var _ = Describe("Service with annotation", Label(utils.TestSuiteLabelServiceAnn Expect(err).NotTo(HaveOccurred()) Expect(pip.Properties.IPAddress).NotTo(BeNil()) - Expect(ptr.Deref(pip.Properties.PublicIPPrefix.ID, "")).To(Equal(prefixIDs2[isIPv6])) - pipAddrs = append(pipAddrs, ptr.Deref(pip.Properties.IPAddress, "")) + Expect(lo.FromPtrOr(pip.Properties.PublicIPPrefix.ID, "")).To(Equal(prefixIDs2[isIPv6])) + pipAddrs = append(pipAddrs, lo.FromPtrOr(pip.Properties.IPAddress, "")) } if v4Enabled { doPIPByPrefix(false) @@ -1029,7 +1027,7 @@ var _ = Describe("Service with annotation", Label(utils.TestSuiteLabelServiceAnn Expect(err).NotTo(HaveOccurred()) } - pipAddr := ptr.Deref(pip.Properties.IPAddress, "") + pipAddr := lo.FromPtrOr(pip.Properties.IPAddress, "") utils.Logf("Created pip with address %s", pipAddr) annotation[consts.ServiceAnnotationLoadBalancerIPDualStack[isIPv6]] = pipAddr return pipAddr, cleanup @@ -1184,7 +1182,7 @@ var _ = Describe("Multi-ports service", Label(utils.TestSuiteLabelMultiPorts), f "app": serviceName, } ports := []v1.ServicePort{{ - AppProtocol: ptr.To("Tcp"), + AppProtocol: lo.ToPtr("Tcp"), Port: serverPort, Name: "port1", TargetPort: intstr.FromInt(serverPort), @@ -1192,7 +1190,7 @@ var _ = Describe("Multi-ports service", Label(utils.TestSuiteLabelMultiPorts), f Port: serverPort + 1, Name: "port2", TargetPort: intstr.FromInt(serverPort), - AppProtocol: ptr.To("Tcp"), + AppProtocol: lo.ToPtr("Tcp"), }, } @@ -1277,7 +1275,7 @@ var _ = Describe("Multi-ports service", Label(utils.TestSuiteLabelMultiPorts), f pip, err := tc.GetPublicIPFromAddress(tc.GetResourceGroup(), ip) Expect(err).NotTo(HaveOccurred()) if pip != nil { - err = utils.DeletePIPWithRetry(tc, ptr.Deref(pip.Name, ""), tc.GetResourceGroup()) + err = utils.DeletePIPWithRetry(tc, lo.FromPtrOr(pip.Name, ""), tc.GetResourceGroup()) Expect(err).NotTo(HaveOccurred()) } } @@ -1480,7 +1478,7 @@ func getFrontendConfigurationIDFromPIP(tc *utils.AzureTestClient, pip, pipResour ip.Properties.IPConfiguration != nil && ip.Properties.IPConfiguration.ID != nil && *ip.Properties.IPAddress == pip { - ipConfig := ptr.Deref(ip.Properties.IPConfiguration.ID, "") + ipConfig := lo.FromPtrOr(ip.Properties.IPConfiguration.ID, "") utils.Logf("Found pip %q with ipConfig %q", pip, ipConfig) pipFrontendConfigurationID = ipConfig break @@ -1705,18 +1703,18 @@ func testPIPTagAnnotationWithTags( By("Checking tags on the corresponding public IP") expectedTags := map[string]*string{ - "a": ptr.To("b"), - "c": ptr.To("d"), - "e": ptr.To(""), + "a": lo.ToPtr("b"), + "c": lo.ToPtr("d"), + "e": lo.ToPtr(""), } pips, err := tc.ListPublicIPs(tc.GetResourceGroup()) Expect(err).NotTo(HaveOccurred()) var targetPIPs []network.PublicIPAddress for _, pip := range pips { for _, ip := range ips { - if strings.EqualFold(ptr.Deref(pip.Properties.IPAddress, ""), *ip) { + if strings.EqualFold(lo.FromPtrOr(pip.Properties.IPAddress, ""), *ip) { targetPIPs = append(targetPIPs, *pip) - err := waitComparePIPTags(tc, expectedTags, ptr.Deref(pip.Name, "")) + err := waitComparePIPTags(tc, expectedTags, lo.FromPtrOr(pip.Name, "")) Expect(err).NotTo(HaveOccurred()) break } @@ -1732,7 +1730,7 @@ func testPIPTagAnnotationWithTags( _, err = cs.CoreV1().Services(ns.Name).Update(context.TODO(), service, metav1.UpdateOptions{}) Expect(err).NotTo(HaveOccurred()) for _, targetPIP := range targetPIPs { - err = waitComparePIPTags(tc, expectedTagsAfterUpdate, ptr.Deref(targetPIP.Name, "")) + err = waitComparePIPTags(tc, expectedTagsAfterUpdate, lo.FromPtrOr(targetPIP.Name, "")) Expect(err).NotTo(HaveOccurred()) } } diff --git a/tests/e2e/network/sharedhealthprobe.go b/tests/e2e/network/sharedhealthprobe.go index 0a94db7ae7..3eb77d2d05 100644 --- a/tests/e2e/network/sharedhealthprobe.go +++ b/tests/e2e/network/sharedhealthprobe.go @@ -21,18 +21,17 @@ import ( "strings" "time" + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + "github.com/samber/lo" appsv1 "k8s.io/api/apps/v1" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/apimachinery/pkg/util/wait" clientset "k8s.io/client-go/kubernetes" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/tests/e2e/utils" - - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" ) var _ = Describe("Shared Health Probe", Label(utils.TestSuiteLabelSharedHealthProbe), func() { @@ -97,7 +96,7 @@ var _ = Describe("Shared Health Probe", Label(utils.TestSuiteLabelSharedHealthPr err = wait.PollUntilContextCancel(ctxWithTimeout, 5*time.Second, false, func(ctx context.Context) (bool, error) { lb := getAzureInternalLoadBalancerFromPrivateIP(tc, ips[0], "") probes := lb.Properties.Probes - if len(probes) != 1 || !strings.EqualFold(ptr.Deref(probes[0].Name, ""), "cluster-service-shared-health-probe") { + if len(probes) != 1 || !strings.EqualFold(lo.FromPtrOr(probes[0].Name, ""), "cluster-service-shared-health-probe") { return false, nil } return true, nil @@ -118,7 +117,7 @@ var _ = Describe("Shared Health Probe", Label(utils.TestSuiteLabelSharedHealthPr err = wait.PollUntilContextCancel(ctxWithTimeout, 5*time.Second, false, func(ctx context.Context) (bool, error) { lb := getAzureInternalLoadBalancerFromPrivateIP(tc, ips[0], "") probes := lb.Properties.Probes - if len(probes) != 1 || !strings.EqualFold(ptr.Deref(probes[0].Name, ""), "cluster-service-shared-health-probe") { + if len(probes) != 1 || !strings.EqualFold(lo.FromPtrOr(probes[0].Name, ""), "cluster-service-shared-health-probe") { return false, nil } return true, nil @@ -198,7 +197,7 @@ var _ = Describe("Shared Health Probe", Label(utils.TestSuiteLabelSharedHealthPr err = wait.PollUntilContextCancel(ctxWithTimeout, 5*time.Second, false, func(ctx context.Context) (bool, error) { lb := getAzureInternalLoadBalancerFromPrivateIP(tc, ips[0], "") probes := lb.Properties.Probes - if len(probes) != 1 || strings.EqualFold(ptr.Deref(probes[0].Name, ""), "cluster-service-shared-health-probe") { + if len(probes) != 1 || strings.EqualFold(lo.FromPtrOr(probes[0].Name, ""), "cluster-service-shared-health-probe") { return false, nil } return true, nil diff --git a/tests/e2e/utils/container_registry_utils.go b/tests/e2e/utils/container_registry_utils.go index 3a73e56b54..fbc4e0ec41 100644 --- a/tests/e2e/utils/container_registry_utils.go +++ b/tests/e2e/utils/container_registry_utils.go @@ -30,7 +30,6 @@ import ( "k8s.io/apimachinery/pkg/util/uuid" "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/utils/ptr" ) // CreateContainerRegistry creates a test acr @@ -43,8 +42,8 @@ func (tc *AzureTestClient) CreateContainerRegistry() (acr.Registry, error) { Name: to.Ptr(acr.SKUNameStandard), Tier: to.Ptr(acr.SKUTierStandard), }, - Name: ptr.To(acrName), - Location: ptr.To(location), + Name: to.Ptr(acrName), + Location: to.Ptr(location), } Logf("Creating ACR %s in resource group %s.", acrName, rgName) @@ -137,8 +136,8 @@ func (tc *AzureTestClient) PushImageToACR(registryName, image string) (string, e tag := "1.25" err := acrClient.ImportImage(context.Background(), rgName, registryName, acr.ImportImageParameters{ Source: &acr.ImportSource{ - RegistryURI: ptr.To("mcr.microsoft.com"), - SourceImage: ptr.To("mirror/docker/library/" + image + ":" + tag), + RegistryURI: to.Ptr("mcr.microsoft.com"), + SourceImage: to.Ptr("mirror/docker/library/" + image + ":" + tag), }, TargetTags: []*string{ to.Ptr(image + ":" + tag), diff --git a/tests/e2e/utils/network_utils.go b/tests/e2e/utils/network_utils.go index 747056003d..843955c2d5 100644 --- a/tests/e2e/utils/network_utils.go +++ b/tests/e2e/utils/network_utils.go @@ -27,11 +27,10 @@ import ( "time" aznetwork "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" - + "github.com/samber/lo" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/utils/ptr" "sigs.k8s.io/cloud-provider-azure/pkg/azclient/virtualnetworkclient" ) @@ -139,7 +138,7 @@ func (azureTestClient *AzureTestClient) DeleteSubnet(vnetName string, subnetName ipConfigIDs := []string{} if subnet.Properties.IPConfigurations != nil { for _, ipConfig := range subnet.Properties.IPConfigurations { - ipConfigIDs = append(ipConfigIDs, ptr.Deref(ipConfig.ID, "")) + ipConfigIDs = append(ipConfigIDs, lo.FromPtrOr(ipConfig.ID, "")) } } @@ -366,7 +365,7 @@ func WaitGetPIPByPrefix( return false, nil } - pipID := ptr.Deref((prefix.Properties.PublicIPAddresses)[0].ID, "") + pipID := lo.FromPtrOr((prefix.Properties.PublicIPAddresses)[0].ID, "") parts := strings.Split(pipID, "/") pipName := parts[len(parts)-1] pip, err = WaitGetPIP(cli, pipName) @@ -500,7 +499,7 @@ func SelectAvailablePrivateIPs(tc *AzureTestClient) ([]*string, error) { return []*string{}, err } if len(vNet.Properties.Subnets) == 0 { - return []*string{}, fmt.Errorf("failed to find a subnet in vNet %s", ptr.Deref(vNet.Name, "")) + return []*string{}, fmt.Errorf("failed to find a subnet in vNet %s", lo.FromPtrOr(vNet.Name, "")) } subnets, err := selectSubnets(tc.IPFamily, vNet.Properties.Subnets) if err != nil { @@ -513,7 +512,7 @@ func SelectAvailablePrivateIPs(tc *AzureTestClient) ([]*string, error) { } privateIPs := []*string{} for _, subnet := range subnets { - ip, err := findIPInSubnet(vNetClient, tc.resourceGroup, *subnet, ptr.Deref(vNet.Name, "")) + ip, err := findIPInSubnet(vNetClient, tc.resourceGroup, *subnet, lo.FromPtrOr(vNet.Name, "")) if err != nil { return privateIPs, err } @@ -537,7 +536,7 @@ func (azureTestClient *AzureTestClient) GetPublicIPFromAddress(resourceGroupName return pip, err } for _, pip := range pipList { - if strings.EqualFold(ptr.Deref(pip.Properties.IPAddress, ""), *ipAddr) { + if strings.EqualFold(lo.FromPtrOr(pip.Properties.IPAddress, ""), *ipAddr) { return pip, err } } diff --git a/tests/e2e/utils/network_utils_test.go b/tests/e2e/utils/network_utils_test.go index f943f08386..5502f17429 100644 --- a/tests/e2e/utils/network_utils_test.go +++ b/tests/e2e/utils/network_utils_test.go @@ -22,8 +22,6 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" aznetwork "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" "github.com/stretchr/testify/assert" - - "k8s.io/utils/ptr" ) func TestSelectSubnets(t *testing.T) { @@ -37,7 +35,7 @@ func TestSelectSubnets(t *testing.T) { "only control-plane subnet", IPv4, []*aznetwork.Subnet{ - {Name: ptr.To("control-plane")}, + {Name: to.Ptr("control-plane")}, }, []*string{}, }, @@ -45,7 +43,7 @@ func TestSelectSubnets(t *testing.T) { "IPv4", IPv4, []*aznetwork.Subnet{ - {Name: ptr.To("subnet0"), Properties: &aznetwork.SubnetPropertiesFormat{AddressPrefix: ptr.To("10.0.0.0/24")}}, + {Name: to.Ptr("subnet0"), Properties: &aznetwork.SubnetPropertiesFormat{AddressPrefix: to.Ptr("10.0.0.0/24")}}, }, []*string{to.Ptr("10.0.0.0/24")}, }, @@ -54,9 +52,9 @@ func TestSelectSubnets(t *testing.T) { IPv6, []*aznetwork.Subnet{ { - Name: ptr.To("subnet0"), + Name: to.Ptr("subnet0"), Properties: &aznetwork.SubnetPropertiesFormat{ - AddressPrefix: ptr.To("10.0.0.0/24"), + AddressPrefix: to.Ptr("10.0.0.0/24"), AddressPrefixes: []*string{to.Ptr("10.0.0.0/24"), to.Ptr("2001::1/96")}, }, }, @@ -68,9 +66,9 @@ func TestSelectSubnets(t *testing.T) { DualStack, []*aznetwork.Subnet{ { - Name: ptr.To("subnet0"), + Name: to.Ptr("subnet0"), Properties: &aznetwork.SubnetPropertiesFormat{ - AddressPrefix: ptr.To("10.0.0.0/24"), + AddressPrefix: to.Ptr("10.0.0.0/24"), AddressPrefixes: []*string{to.Ptr("10.0.0.0/24"), to.Ptr("2001::1/96")}, }, }, diff --git a/tests/e2e/utils/resource_group_utils.go b/tests/e2e/utils/resource_group_utils.go index de27cf5937..bd209aac34 100644 --- a/tests/e2e/utils/resource_group_utils.go +++ b/tests/e2e/utils/resource_group_utils.go @@ -20,18 +20,18 @@ import ( "context" "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" resources "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "k8s.io/apimachinery/pkg/util/uuid" - "k8s.io/utils/ptr" ) // CreateTestResourceGroup create a test rg func CreateTestResourceGroup(tc *AzureTestClient) (*resources.ResourceGroup, func(string)) { gc := tc.createResourceGroupClient() - rgName := ptr.To("e2e-" + string(uuid.NewUUID())[0:4]) + rgName := to.Ptr("e2e-" + string(uuid.NewUUID())[0:4]) rg, err := gc.CreateOrUpdate(context.Background(), *rgName, createTestTemplate(tc, rgName)) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf("resource group %s created", *rgName)) @@ -47,6 +47,6 @@ func CreateTestResourceGroup(tc *AzureTestClient) (*resources.ResourceGroup, fun func createTestTemplate(tc *AzureTestClient, name *string) resources.ResourceGroup { return resources.ResourceGroup{ Name: name, - Location: ptr.To(tc.location), + Location: to.Ptr(tc.location), } } diff --git a/tests/e2e/utils/route_table_utils.go b/tests/e2e/utils/route_table_utils.go index da98d35682..6561bf0a7b 100644 --- a/tests/e2e/utils/route_table_utils.go +++ b/tests/e2e/utils/route_table_utils.go @@ -21,8 +21,7 @@ import ( "fmt" aznetwork "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork/v6" - - "k8s.io/utils/ptr" + "github.com/samber/lo" providerazure "sigs.k8s.io/cloud-provider-azure/pkg/provider" ) @@ -46,7 +45,7 @@ func GetNodesInRouteTable(routeTable aznetwork.RouteTable) (map[string]interface routeSet := make(map[string]interface{}) for _, route := range routeTable.Properties.Routes { - routeSet[string(providerazure.MapRouteNameToNodeName(true, ptr.Deref(route.Name, "")))] = true + routeSet[string(providerazure.MapRouteNameToNodeName(true, lo.FromPtrOr(route.Name, "")))] = true } return routeSet, nil diff --git a/tests/e2e/utils/vmss_utils.go b/tests/e2e/utils/vmss_utils.go index bcfda99946..53707e924e 100644 --- a/tests/e2e/utils/vmss_utils.go +++ b/tests/e2e/utils/vmss_utils.go @@ -29,7 +29,6 @@ import ( v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/utils/ptr" ) var ( @@ -80,7 +79,7 @@ func ScaleVMSS(tc *AzureTestClient, vmssName string, instanceCount int64) (err e Location: vmss.Location, SKU: &azcompute.SKU{ Name: vmss.SKU.Name, - Capacity: ptr.To(instanceCount), + Capacity: to.Ptr(instanceCount), }, } diff --git a/vendor/github.com/samber/lo/CHANGELOG.md b/vendor/github.com/samber/lo/CHANGELOG.md index 25815f76aa..8b9e4e11f5 100644 --- a/vendor/github.com/samber/lo/CHANGELOG.md +++ b/vendor/github.com/samber/lo/CHANGELOG.md @@ -2,6 +2,11 @@ @samber: I sometimes forget to update this file. Ping me on [Twitter](https://twitter.com/samuelberthe) or open an issue in case of error. We need to keep a clear changelog for easier lib upgrade. +## 1.39.0 (2023-12-01) + +Improvement: +- Adding IsNil + ## 1.38.1 (2023-03-20) Improvement: @@ -15,7 +20,7 @@ Adding: - lo.EmptyableToPtr Improvement: -- Substring: add support for non-english chars +- Substring: add support for non-English chars Fix: - Async: Fix goroutine leak diff --git a/vendor/github.com/samber/lo/Dockerfile b/vendor/github.com/samber/lo/Dockerfile index bd01bbbb45..5eab431ac0 100644 --- a/vendor/github.com/samber/lo/Dockerfile +++ b/vendor/github.com/samber/lo/Dockerfile @@ -1,5 +1,5 @@ -FROM golang:1.18 +FROM golang:1.21.12 WORKDIR /go/src/github.com/samber/lo diff --git a/vendor/github.com/samber/lo/Makefile b/vendor/github.com/samber/lo/Makefile index 57bb49159f..f97ded85e7 100644 --- a/vendor/github.com/samber/lo/Makefile +++ b/vendor/github.com/samber/lo/Makefile @@ -1,8 +1,6 @@ -BIN=go - build: - ${BIN} build -v ./... + go build -v ./... test: go test -race -v ./... @@ -15,18 +13,18 @@ watch-bench: reflex -t 50ms -s -- sh -c 'go test -benchmem -count 3 -bench ./...' coverage: - ${BIN} test -v -coverprofile=cover.out -covermode=atomic . - ${BIN} tool cover -html=cover.out -o cover.html + go test -v -coverprofile=cover.out -covermode=atomic ./... + go tool cover -html=cover.out -o cover.html # tools tools: - ${BIN} install github.com/cespare/reflex@latest - ${BIN} install github.com/rakyll/gotest@latest - ${BIN} install github.com/psampaz/go-mod-outdated@latest - ${BIN} install github.com/jondot/goweight@latest - ${BIN} install github.com/golangci/golangci-lint/cmd/golangci-lint@latest - ${BIN} get -t -u golang.org/x/tools/cmd/cover - ${BIN} install github.com/sonatype-nexus-community/nancy@latest + go install github.com/cespare/reflex@latest + go install github.com/rakyll/gotest@latest + go install github.com/psampaz/go-mod-outdated@latest + go install github.com/jondot/goweight@latest + go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest + go get -t -u golang.org/x/tools/cmd/cover + go install github.com/sonatype-nexus-community/nancy@latest go mod tidy lint: @@ -35,10 +33,10 @@ lint-fix: golangci-lint run --timeout 60s --max-same-issues 50 --fix ./... audit: tools - ${BIN} list -json -m all | nancy sleuth + go list -json -m all | nancy sleuth outdated: tools - ${BIN} list -u -m -json all | go-mod-outdated -update -direct + go list -u -m -json all | go-mod-outdated -update -direct weight: tools goweight diff --git a/vendor/github.com/samber/lo/README.md b/vendor/github.com/samber/lo/README.md index 77ab2d007d..3f73cc8e6d 100644 --- a/vendor/github.com/samber/lo/README.md +++ b/vendor/github.com/samber/lo/README.md @@ -24,7 +24,7 @@ In the future, 5 to 10 helpers will overlap with those coming into the Go standa **Why this name?** -I wanted a **short name**, similar to "Lodash" and no Go package currently uses this name. +I wanted a **short name**, similar to "Lodash" and no Go package uses this name. ![lo](img/logo-full.png) @@ -54,7 +54,7 @@ import ( Then use one of the helpers below: ```go -names := lo.Uniq[string]([]string{"Samuel", "John", "Samuel"}) +names := lo.Uniq([]string{"Samuel", "John", "Samuel"}) // []string{"Samuel", "John"} ``` @@ -85,6 +85,7 @@ Supported helpers for slices: - [Reduce](#reduce) - [ReduceRight](#reduceright) - [ForEach](#foreach) +- [ForEachWhile](#foreachwhile) - [Times](#times) - [Uniq](#uniq) - [UniqBy](#uniqby) @@ -104,7 +105,10 @@ Supported helpers for slices: - [DropRight](#dropright) - [DropWhile](#dropwhile) - [DropRightWhile](#droprightwhile) +- [DropByIndex](#DropByIndex) - [Reject](#reject) +- [RejectMap](#rejectmap) +- [FilterReject](#filterreject) - [Count](#count) - [CountBy](#countby) - [CountValues](#countvalues) @@ -116,12 +120,16 @@ Supported helpers for slices: - [Compact](#compact) - [IsSorted](#issorted) - [IsSortedByKey](#issortedbykey) +- [Splice](#Splice) Supported helpers for maps: - [Keys](#keys) +- [UniqKeys](#uniqkeys) +- [HasKey](#haskey) - [ValueOr](#valueor) - [Values](#values) +- [UniqValues](#uniqvalues) - [PickBy](#pickby) - [PickByKeys](#pickbykeys) - [PickByValues](#pickbyvalues) @@ -143,6 +151,8 @@ Supported math helpers: - [Clamp](#clamp) - [Sum](#sum) - [SumBy](#sumby) +- [Mean](#mean) +- [MeanBy](#meanby) Supported helpers for strings: @@ -150,13 +160,27 @@ Supported helpers for strings: - [Substring](#substring) - [ChunkString](#chunkstring) - [RuneLength](#runelength) +- [PascalCase](#pascalcase) +- [CamelCase](#camelcase) +- [KebabCase](#kebabcase) +- [SnakeCase](#snakecase) +- [Words](#words) +- [Capitalize](#capitalize) +- [Elipse](#elipse) Supported helpers for tuples: - [T2 -> T9](#t2---t9) - [Unpack2 -> Unpack9](#unpack2---unpack9) - [Zip2 -> Zip9](#zip2---zip9) +- [ZipBy2 -> ZipBy9](#zipby2---zipby9) - [Unzip2 -> Unzip9](#unzip2---unzip9) +- [UnzipBy2 -> UnzipBy9](#unzipby2---unzipby9) + +Supported helpers for time and duration: + +- [Duration](#duration) +- [Duration0 -> Duration10](#duration0-duration10) Supported helpers for channels: @@ -200,9 +224,18 @@ Supported search helpers: - [FindDuplicatesBy](#findduplicatesby) - [Min](#min) - [MinBy](#minby) +- [Earliest](#earliest) +- [EarliestBy](#earliestby) - [Max](#max) - [MaxBy](#maxby) +- [Latest](#latest) +- [LatestBy](#latestby) +- [First](#first) +- [FirstOrEmpty](#FirstOrEmpty) +- [FirstOr](#FirstOr) - [Last](#last) +- [LastOrEmpty](#LastOrEmpty) +- [LastOr](#LastOr) - [Nth](#nth) - [Sample](#sample) - [Samples](#samples) @@ -216,17 +249,22 @@ Conditional helpers: Type manipulation helpers: +- [IsNil](#isnil) - [ToPtr](#toptr) +- [Nil](#nil) - [EmptyableToPtr](#emptyabletoptr) - [FromPtr](#fromptr) - [FromPtrOr](#fromptror) - [ToSlicePtr](#tosliceptr) +- [FromSlicePtr](#fromsliceptr) +- [FromSlicePtrOr](#fromsliceptror) - [ToAnySlice](#toanyslice) - [FromAnySlice](#fromanyslice) - [Empty](#empty) - [IsEmpty](#isempty) - [IsNotEmpty](#isnotempty) - [Coalesce](#coalesce) +- [CoalesceOrEmpty](#coalesceorempty) Function helpers: @@ -244,6 +282,8 @@ Concurrency helpers: - [Synchronize](#synchronize) - [Async](#async) - [Transaction](#transaction) +- [WaitFor](#waitfor) +- [WaitForWithContext](#waitforwithcontext) Error handling: @@ -324,11 +364,11 @@ matching := lo.FilterMap([]string{"cpu", "gpu", "mouse", "keyboard"}, func(x str Manipulates a slice and transforms and flattens it to a slice of another type. The transform function can either return a slice or a `nil`, and in the `nil` case no value is added to the final slice. ```go -lo.FlatMap([]int{0, 1, 2}, func(x int, _ int) []string { - return []string{ - strconv.FormatInt(x, 10), - strconv.FormatInt(x, 10), - } +lo.FlatMap([]int64{0, 1, 2}, func(x int64, _ int) []string { + return []string{ + strconv.FormatInt(x, 10), + strconv.FormatInt(x, 10), + } }) // []string{"0", "0", "1", "1", "2", "2"} ``` @@ -387,6 +427,26 @@ lop.ForEach([]string{"hello", "world"}, func(x string, _ int) { // prints "hello\nworld\n" or "world\nhello\n" ``` +### ForEachWhile + +Iterates over collection elements and invokes iteratee for each element collection return value decide to continue or break, like do while(). + +```go +list := []int64{1, 2, -42, 4} + +lo.ForEachWhile(list, func(x int64, _ int) bool { + if x < 0 { + return false + } + fmt.Println(x) + return true +}) +// 1 +// 2 +``` + +[[play](https://go.dev/play/p/QnLGt35tnow)] + ### Times Times invokes the iteratee n times, returning an array of the results of each invocation. The iteratee is invoked with index as argument. @@ -542,7 +602,7 @@ interleaved := lo.Interleave([]int{1}, []int{2, 5, 8}, []int{3, 6}, []int{4, 7, // []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} ``` -[[play](https://go.dev/play/p/DDhlwrShbwe)] +[[play](https://go.dev/play/p/-RJkTLQEDVt)] ### Shuffle @@ -716,6 +776,18 @@ l := lo.DropRightWhile([]string{"a", "aa", "aaa", "aa", "aa"}, func(val string) [[play](https://go.dev/play/p/3-n71oEC0Hz)] +### DropByIndex + +Drops elements from a slice or array by the index. A negative index will drop elements from the end of the slice. + +```go +l := lo.DropByIndex([]int{0, 1, 2, 3, 4, 5}, 2, 4, -1) +// []int{0, 1, 3} +``` + +[[play](https://go.dev/play/p/JswS7vXRJP2)] + + ### Reject The opposite of Filter, this method returns the elements of collection that predicate does not return truthy for. @@ -729,6 +801,33 @@ odd := lo.Reject([]int{1, 2, 3, 4}, func(x int, _ int) bool { [[play](https://go.dev/play/p/YkLMODy1WEL)] +### RejectMap + +The opposite of FilterMap, this method returns a slice which obtained after both filtering and mapping using the given callback function. + +The callback function should return two values: +- the result of the mapping operation and +- whether the result element should be included or not. + +```go +items := lo.RejectMap([]int{1, 2, 3, 4}, func(x int, _ int) (int, bool) { + return x*10, x%2 == 0 +}) +// []int{10, 30} +``` + +### FilterReject + +Mixes Filter and Reject, this method returns two slices, one for the elements of collection that predicate returns truthy for and one for the elements that predicate does not return truthy for. + +```go +kept, rejected := lo.FilterReject([]int{1, 2, 3, 4}, func(x int, _ int) bool { + return x%2 == 0 +}) +// []int{2, 4} +// []int{1, 3} +``` + ### Count Counts the number of elements in the collection that compare equal to value. @@ -893,7 +992,7 @@ Returns a slice of all non-zero elements. ```go in := []string{"", "foo", "", "bar", ""} -slice := lo.Compact[string](in) +slice := lo.Compact(in) // []string{"foo", "bar"} ``` @@ -923,37 +1022,117 @@ slice := lo.IsSortedByKey([]string{"a", "bb", "ccc"}, func(s string) int { [[play](https://go.dev/play/p/wiG6XyBBu49)] +### Splice + +Splice inserts multiple elements at index i. A negative index counts back from the end of the slice. The helper is protected against overflow errors. + +```go +result := lo.Splice([]string{"a", "b"}, 1, "1", "2") +// []string{"a", "1", "2", "b"} + +// negative +result = lo.Splice([]string{"a", "b"}, -1, "1", "2") +// []string{"a", "1", "2", "b"} + +// overflow +result = lo.Splice([]string{"a", "b"}, 42, "1", "2") +// []string{"a", "b", "1", "2"} +``` + +[[play](https://go.dev/play/p/G5_GhkeSUBA)] + ### Keys -Creates an array of the map keys. +Creates a slice of the map keys. + +Use the UniqKeys variant to deduplicate common keys. ```go -keys := lo.Keys[string, int](map[string]int{"foo": 1, "bar": 2}) +keys := lo.Keys(map[string]int{"foo": 1, "bar": 2}) // []string{"foo", "bar"} + +keys := lo.Keys(map[string]int{"foo": 1, "bar": 2}, map[string]int{"baz": 3}) +// []string{"foo", "bar", "baz"} + +keys := lo.Keys(map[string]int{"foo": 1, "bar": 2}, map[string]int{"bar": 3}) +// []string{"foo", "bar", "bar"} ``` [[play](https://go.dev/play/p/Uu11fHASqrU)] +### UniqKeys + +Creates an array of unique map keys. + +```go +keys := lo.Keys(map[string]int{"foo": 1, "bar": 2}, map[string]int{"baz": 3}) +// []string{"foo", "bar", "baz"} + +keys := lo.Keys(map[string]int{"foo": 1, "bar": 2}, map[string]int{"bar": 3}) +// []string{"foo", "bar"} +``` + +[[play](https://go.dev/play/p/TPKAb6ILdHk)] + +### HasKey + +Returns whether the given key exists. + +```go +exists := lo.HasKey(map[string]int{"foo": 1, "bar": 2}, "foo") +// true + +exists := lo.HasKey(map[string]int{"foo": 1, "bar": 2}, "baz") +// false +``` + +[[play](https://go.dev/play/p/aVwubIvECqS)] + ### Values Creates an array of the map values. +Use the UniqValues variant to deduplicate common values. + ```go -values := lo.Values[string, int](map[string]int{"foo": 1, "bar": 2}) +values := lo.Values(map[string]int{"foo": 1, "bar": 2}) // []int{1, 2} + +values := lo.Values(map[string]int{"foo": 1, "bar": 2}, map[string]int{"baz": 3}) +// []int{1, 2, 3} + +values := lo.Values(map[string]int{"foo": 1, "bar": 2}, map[string]int{"bar": 2}) +// []int{1, 2, 2} ``` [[play](https://go.dev/play/p/nnRTQkzQfF6)] +### UniqValues + +Creates an array of unique map values. + +```go +values := lo.UniqValues(map[string]int{"foo": 1, "bar": 2}) +// []int{1, 2} + +values := lo.UniqValues(map[string]int{"foo": 1, "bar": 2}, map[string]int{"baz": 3}) +// []int{1, 2, 3} + +values := lo.UniqValues(map[string]int{"foo": 1, "bar": 2}, map[string]int{"bar": 2}) +// []int{1, 2} +``` + +[[play](https://go.dev/play/p/nf6bXMh7rM3)] + ### ValueOr -Creates an array of the map values. +Returns the value of the given key or the fallback value if the key is not present. ```go -value := lo.ValueOr[string, int](map[string]int{"foo": 1, "bar": 2}, "foo", 42) +value := lo.ValueOr(map[string]int{"foo": 1, "bar": 2}, "foo", 42) // 1 -value := lo.ValueOr[string, int](map[string]int{"foo": 1, "bar": 2}, "baz", 42) +value := lo.ValueOr(map[string]int{"foo": 1, "bar": 2}, "baz", 42) // 42 ``` @@ -1088,7 +1267,7 @@ m2 := lo.Invert(map[string]int{"a": 1, "b": 2, "c": 1}) Merges multiple maps from left to right. ```go -mergedMaps := lo.Assign[string, int]( +mergedMaps := lo.Assign( map[string]int{"a": 1, "b": 2}, map[string]int{"b": 3, "c": 4}, ) @@ -1234,6 +1413,42 @@ sum := lo.SumBy(strings, func(item string) int { [[play](https://go.dev/play/p/Dz_a_7jN_ca)] +### Mean + +Calculates the mean of a collection of numbers. + +If collection is empty 0 is returned. + +```go +mean := lo.Mean([]int{2, 3, 4, 5}) +// 3 + +mean := lo.Mean([]float64{2, 3, 4, 5}) +// 3.5 + +mean := lo.Mean([]float64{}) +// 0 +``` + +### MeanBy + +Calculates the mean of a collection of numbers using the given return value from the iteration function. + +If collection is empty 0 is returned. + +```go +list := []string{"aa", "bbb", "cccc", "ddddd"} +mapper := func(item string) float64 { + return float64(len(item)) +} + +mean := lo.MeanBy(list, mapper) +// 3.5 + +mean := lo.MeanBy([]float64{}, mapper) +// 0 +``` + ### RandomString Returns a random string of the specified length and made of the specified charset. @@ -1296,6 +1511,85 @@ sub := len("hellô") [[play](https://go.dev/play/p/tuhgW_lWY8l)] +### PascalCase + +Converts string to pascal case. + +```go +str := lo.PascalCase("hello_world") +// HelloWorld +``` + +[[play](https://go.dev/play/p/iZkdeLP9oiB)] + +### CamelCase + +Converts string to camel case. + +```go +str := lo.CamelCase("hello_world") +// helloWorld +``` + +[[play](https://go.dev/play/p/dtyFB58MBRp)] + +### KebabCase + +Converts string to kebab case. + +```go +str := lo.KebabCase("helloWorld") +// hello-world +``` + +[[play](https://go.dev/play/p/2YTuPafwECA)] + +### SnakeCase + +Converts string to snake case. + +```go +str := lo.SnakeCase("HelloWorld") +// hello_world +``` + +[[play](https://go.dev/play/p/QVKJG9nOnDg)] + +### Words + +Splits string into an array of its words. + +```go +str := lo.Words("helloWorld") +// []string{"hello", "world"} +``` + +[[play](https://go.dev/play/p/2P4zhqqq61g)] + +### Capitalize + +Converts the first character of string to upper case and the remaining to lower case. + +```go +str := lo.Capitalize("heLLO") +// Hello +``` + +### Elipse + +Truncates a string to a specified length and appends an ellipsis if truncated. + +```go +str := lo.Elipse("Lorem Ipsum", 5) +// Lo... + +str := lo.Elipse("Lorem Ipsum", 100) +// Lorem Ipsum + +str := lo.Elipse("Lorem Ipsum", 3) +// ... +``` + ### T2 -> T9 Creates a tuple from a list of values. @@ -1325,7 +1619,7 @@ Unpack is also available as a method of TupleX. ```go tuple2 := lo.T2("a", 1) a, b := tuple2.Unpack() -// "a" 1 +// "a", 1 ``` [[play](https://go.dev/play/p/xVP_k0kJ96W)] @@ -1343,6 +1637,19 @@ tuples := lo.Zip2([]string{"a", "b"}, []int{1, 2}) [[play](https://go.dev/play/p/jujaA6GaJTp)] +### ZipBy2 -> ZipBy9 + +ZipBy creates a slice of transformed elements, the first of which contains the first elements of the given arrays, the second of which contains the second elements of the given arrays, and so on. + +When collections have different size, the Tuple attributes are filled with zero value. + +```go +items := lo.ZipBy2([]string{"a", "b"}, []int{1, 2}, func(a string, b int) string { + return fmt.Sprintf("%s-%d", a, b) +}) +// []string{"a-1", "b-2"} +``` + ### Unzip2 -> Unzip9 Unzip accepts an array of grouped elements and creates an array regrouping the elements to their pre-zip configuration. @@ -1355,6 +1662,56 @@ a, b := lo.Unzip2([]Tuple2[string, int]{{A: "a", B: 1}, {A: "b", B: 2}}) [[play](https://go.dev/play/p/ciHugugvaAW)] +### UnzipBy2 -> UnzipBy9 + +UnzipBy2 iterates over a collection and creates an array regrouping the elements to their pre-zip configuration. + +```go +a, b := lo.UnzipBy2([]string{"hello", "john", "doe"}, func(str string) (string, int) { + return str, len(str) +}) +// []string{"hello", "john", "doe"} +// []int{5, 4, 3} +``` + +### Duration + +Returns the time taken to execute a function. + +```go +duration := lo.Duration(func() { + // very long job +}) +// 3s +``` + +### Duration0 -> Duration10 + +Returns the time taken to execute a function. + +```go +duration := lo.Duration0(func() { + // very long job +}) +// 3s + +err, duration := lo.Duration1(func() error { + // very long job + return fmt.Errorf("an error") +}) +// an error +// 3s + +str, nbr, err, duration := lo.Duration3(func() (string, int, error) { + // very long job + return "hello", 42, nil +}) +// hello +// 42 +// nil +// 3s +``` + ### ChannelDispatcher Distributes messages from input channels into N child channels. Close events are propagated to children. @@ -1823,7 +2180,7 @@ str, index, ok := lo.FindLastIndexOf([]string{"foobar"}, func(i string) bool { ### FindOrElse -Search an element in a slice based on a predicate. It returns element and true if element was found. +Search an element in a slice based on a predicate. It returns the element if found or a given fallback value otherwise. ```go str := lo.FindOrElse([]string{"a", "b", "c", "d"}, "x", func(i string) bool { @@ -1915,7 +2272,7 @@ duplicatedValues := lo.FindDuplicatesBy([]int{3, 4, 5, 6, 7}, func(i int) int { Search the minimum value of a collection. -Returns zero value when collection is empty. +Returns zero value when the collection is empty. ```go min := lo.Min([]int{1, 2, 3}) @@ -1923,6 +2280,9 @@ min := lo.Min([]int{1, 2, 3}) min := lo.Min([]int{}) // 0 + +min := lo.Min([]time.Duration{time.Second, time.Hour}) +// 1s ``` ### MinBy @@ -1931,7 +2291,7 @@ Search the minimum value of a collection using the given comparison function. If several values of the collection are equal to the smallest value, returns the first such value. -Returns zero value when collection is empty. +Returns zero value when the collection is empty. ```go min := lo.MinBy([]string{"s1", "string2", "s3"}, func(item string, min string) bool { @@ -1945,11 +2305,39 @@ min := lo.MinBy([]string{}, func(item string, min string) bool { // "" ``` +### Earliest + +Search the minimum time.Time of a collection. + +Returns zero value when the collection is empty. + +```go +earliest := lo.Earliest(time.Now(), time.Time{}) +// 0001-01-01 00:00:00 +0000 UTC +``` + +### EarliestBy + +Search the minimum time.Time of a collection using the given iteratee function. + +Returns zero value when the collection is empty. + +```go +type foo struct { + bar time.Time +} + +earliest := lo.EarliestBy([]foo{{time.Now()}, {}}, func(i foo) time.Time { + return i.bar +}) +// {bar:{2023-04-01 01:02:03 +0000 UTC}} +``` + ### Max Search the maximum value of a collection. -Returns zero value when collection is empty. +Returns zero value when the collection is empty. ```go max := lo.Max([]int{1, 2, 3}) @@ -1957,6 +2345,9 @@ max := lo.Max([]int{1, 2, 3}) max := lo.Max([]int{}) // 0 + +max := lo.Max([]time.Duration{time.Second, time.Hour}) +// 1h ``` ### MaxBy @@ -1965,7 +2356,7 @@ Search the maximum value of a collection using the given comparison function. If several values of the collection are equal to the greatest value, returns the first such value. -Returns zero value when collection is empty. +Returns zero value when the collection is empty. ```go max := lo.MaxBy([]string{"string1", "s2", "string3"}, func(item string, max string) bool { @@ -1979,13 +2370,104 @@ max := lo.MaxBy([]string{}, func(item string, max string) bool { // "" ``` +### Latest + +Search the maximum time.Time of a collection. + +Returns zero value when the collection is empty. + +```go +latest := lo.Latest([]time.Time{time.Now(), time.Time{}}) +// 2023-04-01 01:02:03 +0000 UTC +``` + +### LatestBy + +Search the maximum time.Time of a collection using the given iteratee function. + +Returns zero value when the collection is empty. + +```go +type foo struct { + bar time.Time +} + +latest := lo.LatestBy([]foo{{time.Now()}, {}}, func(i foo) time.Time { + return i.bar +}) +// {bar:{2023-04-01 01:02:03 +0000 UTC}} +``` + +### First + +Returns the first element of a collection and check for availability of the first element. + +```go +first, ok := lo.First([]int{1, 2, 3}) +// 1, true + +first, ok := lo.First([]int{}) +// 0, false +``` + +### FirstOrEmpty + +Returns the first element of a collection or zero value if empty. + +```go +first := lo.FirstOrEmpty([]int{1, 2, 3}) +// 1 + +first := lo.FirstOrEmpty([]int{}) +// 0 +``` +### FirstOr + +Returns the first element of a collection or the fallback value if empty. + +```go +first := lo.FirstOr([]int{1, 2, 3}, 245) +// 1 + +first := lo.FirstOr([]int{}, 31) +// 31 +``` + ### Last Returns the last element of a collection or error if empty. ```go -last, err := lo.Last([]int{1, 2, 3}) +last, ok := lo.Last([]int{1, 2, 3}) // 3 +// true + +last, ok := lo.Last([]int{}) +// 0 +// false +``` + +### LastOrEmpty + +Returns the first element of a collection or zero value if empty. + +```go +last := lo.LastOrEmpty([]int{1, 2, 3}) +// 3 + +last := lo.LastOrEmpty([]int{}) +// 0 +``` +### LastOr + +Returns the first element of a collection or the fallback value if empty. + +```go +last := lo.LastOr([]int{1, 2, 3}, 245) +// 3 + +last := lo.LastOr([]int{}, 31) +// 31 ``` ### Nth @@ -2047,7 +2529,7 @@ result := lo.TernaryF(false, func() string { return "a" }, func() string { retur // "b" ``` -Useful to avoid nil-pointer dereferencing in intializations, or avoid running unnecessary code +Useful to avoid nil-pointer dereferencing in initializations, or avoid running unnecessary code ```go var s *string @@ -2155,31 +2637,64 @@ result := lo.Switch(1). [[play](https://go.dev/play/p/TGbKUMAeRUd)] +### IsNil + +Checks if a value is nil or if it's a reference type with a nil underlying value. + +```go +var x int +IsNil(x)) +// false + +var k struct{} +IsNil(k) +// false + +var i *int +IsNil(i) +// true + +var ifaceWithNilValue any = (*string)(nil) +IsNil(ifaceWithNilValue) +// true +ifaceWithNilValue == nil +// false +``` + ### ToPtr -Returns a pointer copy of value. +Returns a pointer copy of the value. ```go ptr := lo.ToPtr("hello world") // *string{"hello world"} ``` +### Nil + +Returns a nil pointer of type. + +```go +ptr := lo.Nil[float64]() +// nil +``` + ### EmptyableToPtr Returns a pointer copy of value if it's nonzero. Otherwise, returns nil pointer. ```go -ptr := lo.EmptyableToPtr[[]int](nil) +ptr := lo.EmptyableToPtr(nil) // nil -ptr := lo.EmptyableToPtr[string]("") +ptr := lo.EmptyableToPtr("") // nil -ptr := lo.EmptyableToPtr[[]int]([]int{}) +ptr := lo.EmptyableToPtr([]int{}) // *[]int{} -ptr := lo.EmptyableToPtr[string]("hello world") +ptr := lo.EmptyableToPtr("hello world") // *string{"hello world"} ``` @@ -2192,7 +2707,7 @@ str := "hello world" value := lo.FromPtr(&str) // "hello world" -value := lo.FromPtr[string](nil) +value := lo.FromPtr(nil) // "" ``` @@ -2205,7 +2720,7 @@ str := "hello world" value := lo.FromPtrOr(&str, "empty") // "hello world" -value := lo.FromPtrOr[string](nil, "empty") +value := lo.FromPtrOr(nil, "empty") // "empty" ``` @@ -2218,6 +2733,36 @@ ptr := lo.ToSlicePtr([]string{"hello", "world"}) // []*string{"hello", "world"} ``` +### FromSlicePtr + +Returns a slice with the pointer values. +Returns a zero value in case of a nil pointer element. + +```go +str1 := "hello" +str2 := "world" + +ptr := lo.FromSlicePtr[string]([]*string{&str1, &str2, nil}) +// []string{"hello", "world", ""} + +ptr := lo.Compact( + lo.FromSlicePtr[string]([]*string{&str1, &str2, nil}), +) +// []string{"hello", "world"} +``` + +### FromSlicePtrOr + +Returns a slice with the pointer values or the fallback value. + +```go +str1 := "hello" +str2 := "world" + +ptr := lo.FromSlicePtrOr[string]([]*string{&str1, &str2, "fallback value"}) +// []string{"hello", "world", "fallback value"} +``` + ### ToAnySlice Returns a slice with all elements mapped to `any` type. @@ -2315,10 +2860,27 @@ result, ok := lo.Coalesce("") var nilStr *string str := "foobar" -result, ok := lo.Coalesce[*string](nil, nilStr, &str) +result, ok := lo.Coalesce(nil, nilStr, &str) // &"foobar" true ``` +### CoalesceOrEmpty + +Returns the first non-empty arguments. Arguments must be comparable. + +```go +result := lo.CoalesceOrEmpty(0, 1, 2, 3) +// 1 + +result := lo.CoalesceOrEmpty("") +// "" + +var nilStr *string +str := "foobar" +result := lo.CoalesceOrEmpty(nil, nilStr, &str) +// &"foobar" +``` + ### Partial Returns new function that, when called, has its first argument set to the provided value. @@ -2568,7 +3130,7 @@ ch := lo.Async2(func() (int, string) { Implements a Saga pattern. ```go -transaction := NewTransaction[int](). +transaction := NewTransaction(). Then( func(state int) (int, error) { fmt.Println("step 1") @@ -2615,6 +3177,81 @@ _, _ = transaction.Process(-5) // rollback 1 ``` +### WaitFor + +Runs periodically until a condition is validated. + +```go +alwaysTrue := func(i int) bool { return true } +alwaysFalse := func(i int) bool { return false } +laterTrue := func(i int) bool { + return i > 5 +} + +iterations, duration, ok := lo.WaitFor(alwaysTrue, 10*time.Millisecond, 2 * time.Millisecond) +// 1 +// 1ms +// true + +iterations, duration, ok := lo.WaitFor(alwaysFalse, 10*time.Millisecond, time.Millisecond) +// 10 +// 10ms +// false + +iterations, duration, ok := lo.WaitFor(laterTrue, 10*time.Millisecond, time.Millisecond) +// 7 +// 7ms +// true + +iterations, duration, ok := lo.WaitFor(laterTrue, 10*time.Millisecond, 5*time.Millisecond) +// 2 +// 10ms +// false +``` + + +### WaitForWithContext + +Runs periodically until a condition is validated or context is invalid. + +The condition receives also the context, so it can invalidate the process in the condition checker + +```go +ctx := context.Background() + +alwaysTrue := func(_ context.Context, i int) bool { return true } +alwaysFalse := func(_ context.Context, i int) bool { return false } +laterTrue := func(_ context.Context, i int) bool { + return i >= 5 +} + +iterations, duration, ok := lo.WaitForWithContext(ctx, alwaysTrue, 10*time.Millisecond, 2 * time.Millisecond) +// 1 +// 1ms +// true + +iterations, duration, ok := lo.WaitForWithContext(ctx, alwaysFalse, 10*time.Millisecond, time.Millisecond) +// 10 +// 10ms +// false + +iterations, duration, ok := lo.WaitForWithContext(ctx, laterTrue, 10*time.Millisecond, time.Millisecond) +// 5 +// 5ms +// true + +iterations, duration, ok := lo.WaitForWithContext(ctx, laterTrue, 10*time.Millisecond, 5*time.Millisecond) +// 2 +// 10ms +// false + +expiringCtx, cancel := context.WithTimeout(ctx, 5*time.Millisecond) +iterations, duration, ok := lo.WaitForWithContext(expiringCtx, alwaysFalse, 100*time.Millisecond, time.Millisecond) +// 5 +// 5.1ms +// false +``` + ### Validate Helper function that creates an error when a condition is not met. @@ -2687,7 +3324,7 @@ lo.Must0(ok, "'%s' must always contain '%s'", myString, requiredChar) list := []int{0, 1, 2} item := 5 -lo.Must0(lo.Contains[int](list, item), "'%s' must always contain '%s'", list, item) +lo.Must0(lo.Contains(list, item), "'%s' must always contain '%s'", list, item) ... ``` @@ -2695,7 +3332,7 @@ lo.Must0(lo.Contains[int](list, item), "'%s' must always contain '%s'", list, it ### Try -Calls the function and return false in case of error and on panic. +Calls the function and returns false in case of error and panic. ```go ok := lo.Try(func() error { @@ -2719,7 +3356,7 @@ ok := lo.Try(func() error { ### Try{0->6} -The same behavior than `Try`, but callback returns 2 variables. +The same behavior as `Try`, but the callback returns 2 variables. ```go ok := lo.Try2(func() (string, error) { @@ -2760,7 +3397,7 @@ str, ok := lo.TryOr(func() error { ### TryOr{0->6} -The same behavior than `TryOr`, but callback returns `X` variables. +The same behavior as `TryOr`, but the callback returns `X` variables. ```go str, nbr, ok := lo.TryOr2(func() (string, int, error) { @@ -2776,7 +3413,7 @@ str, nbr, ok := lo.TryOr2(func() (string, int, error) { ### TryWithErrorValue -The same behavior than `Try`, but also returns value passed to panic. +The same behavior as `Try`, but also returns the value passed to panic. ```go err, ok := lo.TryWithErrorValue(func() error { @@ -2790,7 +3427,7 @@ err, ok := lo.TryWithErrorValue(func() error { ### TryCatch -The same behavior than `Try`, but calls the catch function in case of error. +The same behavior as `Try`, but calls the catch function in case of error. ```go caught := false @@ -2809,7 +3446,7 @@ ok := lo.TryCatch(func() error { ### TryCatchWithErrorValue -The same behavior than `TryWithErrorValue`, but calls the catch function in case of error. +The same behavior as `TryWithErrorValue`, but calls the catch function in case of error. ```go caught := false @@ -2853,7 +3490,7 @@ if rateLimitErr, ok := lo.ErrorsAs[*RateLimitError](err); ok { ## 🛩 Benchmark -We executed a simple benchmark with the a dead-simple `lo.Map` loop: +We executed a simple benchmark with a dead-simple `lo.Map` loop: See the full implementation [here](./benchmark_test.go). @@ -2890,13 +3527,13 @@ ok github.com/samber/lo 6.657s ## 🤝 Contributing -- Ping me on twitter [@samuelberthe](https://twitter.com/samuelberthe) (DMs, mentions, whatever :)) +- Ping me on Twitter [@samuelberthe](https://twitter.com/samuelberthe) (DMs, mentions, whatever :)) - Fork the [project](https://github.com/samber/lo) - Fix [open issues](https://github.com/samber/lo/issues) or request new features Don't hesitate ;) -Helper naming: helpers must be self explanatory and respect standards (other languages, libraries...). Feel free to suggest many names in your contributions. +Helper naming: helpers must be self-explanatory and respect standards (other languages, libraries...). Feel free to suggest many names in your contributions. ### With Docker @@ -2924,10 +3561,10 @@ make watch-test Give a ⭐️ if this project helped you! -[![support us](https://c5.patreon.com/external/logo/become_a_patron_button.png)](https://www.patreon.com/samber) +[![GitHub Sponsors](https://img.shields.io/github/sponsors/samber?style=for-the-badge)](https://github.com/sponsors/samber) ## 📝 License Copyright © 2022 [Samuel Berthe](https://github.com/samber). -This project is [MIT](./LICENSE) licensed. +This project is under [MIT](./LICENSE) license. diff --git a/vendor/github.com/samber/lo/channel.go b/vendor/github.com/samber/lo/channel.go index 5dcac328a8..228705ae39 100644 --- a/vendor/github.com/samber/lo/channel.go +++ b/vendor/github.com/samber/lo/channel.go @@ -1,9 +1,10 @@ package lo import ( - "math/rand" "sync" "time" + + "github.com/samber/lo/internal/rand" ) type DispatchingStrategy[T any] func(msg T, index uint64, channels []<-chan T) int @@ -86,7 +87,7 @@ func DispatchingStrategyRoundRobin[T any](msg T, index uint64, channels []<-chan // If the channel capacity is exceeded, another random channel will be selected and so on. func DispatchingStrategyRandom[T any](msg T, index uint64, channels []<-chan T) int { for { - i := rand.Intn(len(channels)) + i := rand.IntN(len(channels)) if channelIsNotFull(channels[i]) { return i } @@ -108,7 +109,7 @@ func DispatchingStrategyWeightedRandom[T any](weights []int) DispatchingStrategy return func(msg T, index uint64, channels []<-chan T) int { for { - i := seq[rand.Intn(len(seq))] + i := seq[rand.IntN(len(seq))] if channelIsNotFull(channels[i]) { return i } @@ -156,8 +157,8 @@ func SliceToChannel[T any](bufferSize int, collection []T) <-chan T { ch := make(chan T, bufferSize) go func() { - for _, item := range collection { - ch <- item + for i := range collection { + ch <- collection[i] } close(ch) @@ -261,13 +262,13 @@ func FanIn[T any](channelBufferCap int, upstreams ...<-chan T) <-chan T { // Start an output goroutine for each input channel in upstreams. wg.Add(len(upstreams)) - for _, c := range upstreams { - go func(c <-chan T) { - for n := range c { + for i := range upstreams { + go func(index int) { + for n := range upstreams[index] { out <- n } wg.Done() - }(c) + }(i) } // Start a goroutine to close out once all the output goroutines are done. diff --git a/vendor/github.com/samber/lo/concurrency.go b/vendor/github.com/samber/lo/concurrency.go index d0aca2aa28..a2ebbce20a 100644 --- a/vendor/github.com/samber/lo/concurrency.go +++ b/vendor/github.com/samber/lo/concurrency.go @@ -1,6 +1,10 @@ package lo -import "sync" +import ( + "context" + "sync" + "time" +) type synchronize struct { locker sync.Locker @@ -50,7 +54,7 @@ func Async1[A any](f func() A) <-chan A { } // Async2 has the same behavior as Async, but returns the 2 results as a tuple inside the channel. -func Async2[A any, B any](f func() (A, B)) <-chan Tuple2[A, B] { +func Async2[A, B any](f func() (A, B)) <-chan Tuple2[A, B] { ch := make(chan Tuple2[A, B], 1) go func() { ch <- T2(f()) @@ -59,7 +63,7 @@ func Async2[A any, B any](f func() (A, B)) <-chan Tuple2[A, B] { } // Async3 has the same behavior as Async, but returns the 3 results as a tuple inside the channel. -func Async3[A any, B any, C any](f func() (A, B, C)) <-chan Tuple3[A, B, C] { +func Async3[A, B, C any](f func() (A, B, C)) <-chan Tuple3[A, B, C] { ch := make(chan Tuple3[A, B, C], 1) go func() { ch <- T3(f()) @@ -68,7 +72,7 @@ func Async3[A any, B any, C any](f func() (A, B, C)) <-chan Tuple3[A, B, C] { } // Async4 has the same behavior as Async, but returns the 4 results as a tuple inside the channel. -func Async4[A any, B any, C any, D any](f func() (A, B, C, D)) <-chan Tuple4[A, B, C, D] { +func Async4[A, B, C, D any](f func() (A, B, C, D)) <-chan Tuple4[A, B, C, D] { ch := make(chan Tuple4[A, B, C, D], 1) go func() { ch <- T4(f()) @@ -77,7 +81,7 @@ func Async4[A any, B any, C any, D any](f func() (A, B, C, D)) <-chan Tuple4[A, } // Async5 has the same behavior as Async, but returns the 5 results as a tuple inside the channel. -func Async5[A any, B any, C any, D any, E any](f func() (A, B, C, D, E)) <-chan Tuple5[A, B, C, D, E] { +func Async5[A, B, C, D, E any](f func() (A, B, C, D, E)) <-chan Tuple5[A, B, C, D, E] { ch := make(chan Tuple5[A, B, C, D, E], 1) go func() { ch <- T5(f()) @@ -86,10 +90,47 @@ func Async5[A any, B any, C any, D any, E any](f func() (A, B, C, D, E)) <-chan } // Async6 has the same behavior as Async, but returns the 6 results as a tuple inside the channel. -func Async6[A any, B any, C any, D any, E any, F any](f func() (A, B, C, D, E, F)) <-chan Tuple6[A, B, C, D, E, F] { +func Async6[A, B, C, D, E, F any](f func() (A, B, C, D, E, F)) <-chan Tuple6[A, B, C, D, E, F] { ch := make(chan Tuple6[A, B, C, D, E, F], 1) go func() { ch <- T6(f()) }() return ch } + +// WaitFor runs periodically until a condition is validated. +func WaitFor(condition func(i int) bool, timeout time.Duration, heartbeatDelay time.Duration) (totalIterations int, elapsed time.Duration, conditionFound bool) { + conditionWithContext := func(_ context.Context, currentIteration int) bool { + return condition(currentIteration) + } + return WaitForWithContext(context.Background(), conditionWithContext, timeout, heartbeatDelay) +} + +// WaitForWithContext runs periodically until a condition is validated or context is canceled. +func WaitForWithContext(ctx context.Context, condition func(ctx context.Context, currentIteration int) bool, timeout time.Duration, heartbeatDelay time.Duration) (totalIterations int, elapsed time.Duration, conditionFound bool) { + start := time.Now() + + if ctx.Err() != nil { + return totalIterations, time.Since(start), false + } + + ctx, cleanCtx := context.WithTimeout(ctx, timeout) + ticker := time.NewTicker(heartbeatDelay) + + defer func() { + cleanCtx() + ticker.Stop() + }() + + for { + select { + case <-ctx.Done(): + return totalIterations, time.Since(start), false + case <-ticker.C: + totalIterations++ + if condition(ctx, totalIterations-1) { + return totalIterations, time.Since(start), true + } + } + } +} diff --git a/vendor/github.com/samber/lo/errors.go b/vendor/github.com/samber/lo/errors.go index a99013d950..e63bf5d824 100644 --- a/vendor/github.com/samber/lo/errors.go +++ b/vendor/github.com/samber/lo/errors.go @@ -15,7 +15,7 @@ func Validate(ok bool, format string, args ...any) error { return nil } -func messageFromMsgAndArgs(msgAndArgs ...interface{}) string { +func messageFromMsgAndArgs(msgAndArgs ...any) string { if len(msgAndArgs) == 1 { if msgAsStr, ok := msgAndArgs[0].(string); ok { return msgAsStr @@ -29,7 +29,7 @@ func messageFromMsgAndArgs(msgAndArgs ...interface{}) string { } // must panics if err is error or false. -func must(err any, messageArgs ...interface{}) { +func must(err any, messageArgs ...any) { if err == nil { return } @@ -61,54 +61,54 @@ func must(err any, messageArgs ...interface{}) { // Must is a helper that wraps a call to a function returning a value and an error // and panics if err is error or false. // Play: https://go.dev/play/p/TMoWrRp3DyC -func Must[T any](val T, err any, messageArgs ...interface{}) T { +func Must[T any](val T, err any, messageArgs ...any) T { must(err, messageArgs...) return val } // Must0 has the same behavior as Must, but callback returns no variable. // Play: https://go.dev/play/p/TMoWrRp3DyC -func Must0(err any, messageArgs ...interface{}) { +func Must0(err any, messageArgs ...any) { must(err, messageArgs...) } // Must1 is an alias to Must // Play: https://go.dev/play/p/TMoWrRp3DyC -func Must1[T any](val T, err any, messageArgs ...interface{}) T { +func Must1[T any](val T, err any, messageArgs ...any) T { return Must(val, err, messageArgs...) } // Must2 has the same behavior as Must, but callback returns 2 variables. // Play: https://go.dev/play/p/TMoWrRp3DyC -func Must2[T1 any, T2 any](val1 T1, val2 T2, err any, messageArgs ...interface{}) (T1, T2) { +func Must2[T1, T2 any](val1 T1, val2 T2, err any, messageArgs ...any) (T1, T2) { must(err, messageArgs...) return val1, val2 } // Must3 has the same behavior as Must, but callback returns 3 variables. // Play: https://go.dev/play/p/TMoWrRp3DyC -func Must3[T1 any, T2 any, T3 any](val1 T1, val2 T2, val3 T3, err any, messageArgs ...interface{}) (T1, T2, T3) { +func Must3[T1, T2, T3 any](val1 T1, val2 T2, val3 T3, err any, messageArgs ...any) (T1, T2, T3) { must(err, messageArgs...) return val1, val2, val3 } // Must4 has the same behavior as Must, but callback returns 4 variables. // Play: https://go.dev/play/p/TMoWrRp3DyC -func Must4[T1 any, T2 any, T3 any, T4 any](val1 T1, val2 T2, val3 T3, val4 T4, err any, messageArgs ...interface{}) (T1, T2, T3, T4) { +func Must4[T1, T2, T3, T4 any](val1 T1, val2 T2, val3 T3, val4 T4, err any, messageArgs ...any) (T1, T2, T3, T4) { must(err, messageArgs...) return val1, val2, val3, val4 } // Must5 has the same behavior as Must, but callback returns 5 variables. // Play: https://go.dev/play/p/TMoWrRp3DyC -func Must5[T1 any, T2 any, T3 any, T4 any, T5 any](val1 T1, val2 T2, val3 T3, val4 T4, val5 T5, err any, messageArgs ...interface{}) (T1, T2, T3, T4, T5) { +func Must5[T1, T2, T3, T4, T5 any](val1 T1, val2 T2, val3 T3, val4 T4, val5 T5, err any, messageArgs ...any) (T1, T2, T3, T4, T5) { must(err, messageArgs...) return val1, val2, val3, val4, val5 } // Must6 has the same behavior as Must, but callback returns 6 variables. // Play: https://go.dev/play/p/TMoWrRp3DyC -func Must6[T1 any, T2 any, T3 any, T4 any, T5 any, T6 any](val1 T1, val2 T2, val3 T3, val4 T4, val5 T5, val6 T6, err any, messageArgs ...interface{}) (T1, T2, T3, T4, T5, T6) { +func Must6[T1, T2, T3, T4, T5, T6 any](val1 T1, val2 T2, val3 T3, val4 T4, val5 T5, val6 T6, err any, messageArgs ...any) (T1, T2, T3, T4, T5, T6) { must(err, messageArgs...) return val1, val2, val3, val4, val5, val6 } @@ -215,7 +215,7 @@ func TryOr1[A any](callback func() (A, error), fallbackA A) (A, bool) { // TryOr2 has the same behavior as Must, but returns a default value in case of error. // Play: https://go.dev/play/p/B4F7Wg2Zh9X -func TryOr2[A any, B any](callback func() (A, B, error), fallbackA A, fallbackB B) (A, B, bool) { +func TryOr2[A, B any](callback func() (A, B, error), fallbackA A, fallbackB B) (A, B, bool) { ok := false Try0(func() { @@ -232,7 +232,7 @@ func TryOr2[A any, B any](callback func() (A, B, error), fallbackA A, fallbackB // TryOr3 has the same behavior as Must, but returns a default value in case of error. // Play: https://go.dev/play/p/B4F7Wg2Zh9X -func TryOr3[A any, B any, C any](callback func() (A, B, C, error), fallbackA A, fallbackB B, fallbackC C) (A, B, C, bool) { +func TryOr3[A, B, C any](callback func() (A, B, C, error), fallbackA A, fallbackB B, fallbackC C) (A, B, C, bool) { ok := false Try0(func() { @@ -250,7 +250,7 @@ func TryOr3[A any, B any, C any](callback func() (A, B, C, error), fallbackA A, // TryOr4 has the same behavior as Must, but returns a default value in case of error. // Play: https://go.dev/play/p/B4F7Wg2Zh9X -func TryOr4[A any, B any, C any, D any](callback func() (A, B, C, D, error), fallbackA A, fallbackB B, fallbackC C, fallbackD D) (A, B, C, D, bool) { +func TryOr4[A, B, C, D any](callback func() (A, B, C, D, error), fallbackA A, fallbackB B, fallbackC C, fallbackD D) (A, B, C, D, bool) { ok := false Try0(func() { @@ -269,7 +269,7 @@ func TryOr4[A any, B any, C any, D any](callback func() (A, B, C, D, error), fal // TryOr5 has the same behavior as Must, but returns a default value in case of error. // Play: https://go.dev/play/p/B4F7Wg2Zh9X -func TryOr5[A any, B any, C any, D any, E any](callback func() (A, B, C, D, E, error), fallbackA A, fallbackB B, fallbackC C, fallbackD D, fallbackE E) (A, B, C, D, E, bool) { +func TryOr5[A, B, C, D, E any](callback func() (A, B, C, D, E, error), fallbackA A, fallbackB B, fallbackC C, fallbackD D, fallbackE E) (A, B, C, D, E, bool) { ok := false Try0(func() { @@ -289,7 +289,7 @@ func TryOr5[A any, B any, C any, D any, E any](callback func() (A, B, C, D, E, e // TryOr6 has the same behavior as Must, but returns a default value in case of error. // Play: https://go.dev/play/p/B4F7Wg2Zh9X -func TryOr6[A any, B any, C any, D any, E any, F any](callback func() (A, B, C, D, E, F, error), fallbackA A, fallbackB B, fallbackC C, fallbackD D, fallbackE E, fallbackF F) (A, B, C, D, E, F, bool) { +func TryOr6[A, B, C, D, E, F any](callback func() (A, B, C, D, E, F, error), fallbackA A, fallbackB B, fallbackC C, fallbackD D, fallbackE E, fallbackF F) (A, B, C, D, E, F, bool) { ok := false Try0(func() { diff --git a/vendor/github.com/samber/lo/find.go b/vendor/github.com/samber/lo/find.go index f8caeb8959..ea577ae2a6 100644 --- a/vendor/github.com/samber/lo/find.go +++ b/vendor/github.com/samber/lo/find.go @@ -2,18 +2,17 @@ package lo import ( "fmt" - "math/rand" + "time" - "golang.org/x/exp/constraints" + "github.com/samber/lo/internal/constraints" + "github.com/samber/lo/internal/rand" ) -// import "golang.org/x/exp/constraints" - // IndexOf returns the index at which the first occurrence of a value is found in an array or return -1 // if the value cannot be found. func IndexOf[T comparable](collection []T, element T) int { - for i, item := range collection { - if item == element { + for i := range collection { + if collection[i] == element { return i } } @@ -37,9 +36,9 @@ func LastIndexOf[T comparable](collection []T, element T) int { // Find search an element in a slice based on a predicate. It returns element and true if element was found. func Find[T any](collection []T, predicate func(item T) bool) (T, bool) { - for _, item := range collection { - if predicate(item) { - return item, true + for i := range collection { + if predicate(collection[i]) { + return collection[i], true } } @@ -50,9 +49,9 @@ func Find[T any](collection []T, predicate func(item T) bool) (T, bool) { // FindIndexOf searches an element in a slice based on a predicate and returns the index and true. // It returns -1 and false if the element is not found. func FindIndexOf[T any](collection []T, predicate func(item T) bool) (T, int, bool) { - for i, item := range collection { - if predicate(item) { - return item, i, true + for i := range collection { + if predicate(collection[i]) { + return collection[i], i, true } } @@ -77,9 +76,9 @@ func FindLastIndexOf[T any](collection []T, predicate func(item T) bool) (T, int // FindOrElse search an element in a slice based on a predicate. It returns the element if found or a given fallback value otherwise. func FindOrElse[T any](collection []T, fallback T, predicate func(item T) bool) T { - for _, item := range collection { - if predicate(item) { - return item + for i := range collection { + if predicate(collection[i]) { + return collection[i] } } @@ -88,8 +87,8 @@ func FindOrElse[T any](collection []T, fallback T, predicate func(item T) bool) // FindKey returns the key of the first value matching. func FindKey[K comparable, V comparable](object map[K]V, value V) (K, bool) { - for k, v := range object { - if v == value { + for k := range object { + if object[k] == value { return k, true } } @@ -99,8 +98,8 @@ func FindKey[K comparable, V comparable](object map[K]V, value V) (K, bool) { // FindKeyBy returns the key of the first element predicate returns truthy for. func FindKeyBy[K comparable, V any](object map[K]V, predicate func(key K, value V) bool) (K, bool) { - for k, v := range object { - if predicate(k, v) { + for k := range object { + if predicate(k, object[k]) { return k, true } } @@ -110,23 +109,23 @@ func FindKeyBy[K comparable, V any](object map[K]V, predicate func(key K, value // FindUniques returns a slice with all the unique elements of the collection. // The order of result values is determined by the order they occur in the collection. -func FindUniques[T comparable](collection []T) []T { +func FindUniques[T comparable, Slice ~[]T](collection Slice) Slice { isDupl := make(map[T]bool, len(collection)) - for _, item := range collection { - duplicated, ok := isDupl[item] + for i := range collection { + duplicated, ok := isDupl[collection[i]] if !ok { - isDupl[item] = false + isDupl[collection[i]] = false } else if !duplicated { - isDupl[item] = true + isDupl[collection[i]] = true } } - result := make([]T, 0, len(collection)-len(isDupl)) + result := make(Slice, 0, len(collection)-len(isDupl)) - for _, item := range collection { - if duplicated := isDupl[item]; !duplicated { - result = append(result, item) + for i := range collection { + if duplicated := isDupl[collection[i]]; !duplicated { + result = append(result, collection[i]) } } @@ -136,11 +135,11 @@ func FindUniques[T comparable](collection []T) []T { // FindUniquesBy returns a slice with all the unique elements of the collection. // The order of result values is determined by the order they occur in the array. It accepts `iteratee` which is // invoked for each element in array to generate the criterion by which uniqueness is computed. -func FindUniquesBy[T any, U comparable](collection []T, iteratee func(item T) U) []T { +func FindUniquesBy[T any, U comparable, Slice ~[]T](collection Slice, iteratee func(item T) U) Slice { isDupl := make(map[U]bool, len(collection)) - for _, item := range collection { - key := iteratee(item) + for i := range collection { + key := iteratee(collection[i]) duplicated, ok := isDupl[key] if !ok { @@ -150,13 +149,13 @@ func FindUniquesBy[T any, U comparable](collection []T, iteratee func(item T) U) } } - result := make([]T, 0, len(collection)-len(isDupl)) + result := make(Slice, 0, len(collection)-len(isDupl)) - for _, item := range collection { - key := iteratee(item) + for i := range collection { + key := iteratee(collection[i]) if duplicated := isDupl[key]; !duplicated { - result = append(result, item) + result = append(result, collection[i]) } } @@ -165,24 +164,24 @@ func FindUniquesBy[T any, U comparable](collection []T, iteratee func(item T) U) // FindDuplicates returns a slice with the first occurrence of each duplicated elements of the collection. // The order of result values is determined by the order they occur in the collection. -func FindDuplicates[T comparable](collection []T) []T { +func FindDuplicates[T comparable, Slice ~[]T](collection Slice) Slice { isDupl := make(map[T]bool, len(collection)) - for _, item := range collection { - duplicated, ok := isDupl[item] + for i := range collection { + duplicated, ok := isDupl[collection[i]] if !ok { - isDupl[item] = false + isDupl[collection[i]] = false } else if !duplicated { - isDupl[item] = true + isDupl[collection[i]] = true } } - result := make([]T, 0, len(collection)-len(isDupl)) + result := make(Slice, 0, len(collection)-len(isDupl)) - for _, item := range collection { - if duplicated := isDupl[item]; duplicated { - result = append(result, item) - isDupl[item] = false + for i := range collection { + if duplicated := isDupl[collection[i]]; duplicated { + result = append(result, collection[i]) + isDupl[collection[i]] = false } } @@ -192,11 +191,11 @@ func FindDuplicates[T comparable](collection []T) []T { // FindDuplicatesBy returns a slice with the first occurrence of each duplicated elements of the collection. // The order of result values is determined by the order they occur in the array. It accepts `iteratee` which is // invoked for each element in array to generate the criterion by which uniqueness is computed. -func FindDuplicatesBy[T any, U comparable](collection []T, iteratee func(item T) U) []T { +func FindDuplicatesBy[T any, U comparable, Slice ~[]T](collection Slice, iteratee func(item T) U) Slice { isDupl := make(map[U]bool, len(collection)) - for _, item := range collection { - key := iteratee(item) + for i := range collection { + key := iteratee(collection[i]) duplicated, ok := isDupl[key] if !ok { @@ -206,13 +205,13 @@ func FindDuplicatesBy[T any, U comparable](collection []T, iteratee func(item T) } } - result := make([]T, 0, len(collection)-len(isDupl)) + result := make(Slice, 0, len(collection)-len(isDupl)) - for _, item := range collection { - key := iteratee(item) + for i := range collection { + key := iteratee(collection[i]) if duplicated := isDupl[key]; duplicated { - result = append(result, item) + result = append(result, collection[i]) isDupl[key] = false } } @@ -221,7 +220,7 @@ func FindDuplicatesBy[T any, U comparable](collection []T, iteratee func(item T) } // Min search the minimum value of a collection. -// Returns zero value when collection is empty. +// Returns zero value when the collection is empty. func Min[T constraints.Ordered](collection []T) T { var min T @@ -244,7 +243,7 @@ func Min[T constraints.Ordered](collection []T) T { // MinBy search the minimum value of a collection using the given comparison function. // If several values of the collection are equal to the smallest value, returns the first such value. -// Returns zero value when collection is empty. +// Returns zero value when the collection is empty. func MinBy[T any](collection []T, comparison func(a T, b T) bool) T { var min T @@ -265,8 +264,54 @@ func MinBy[T any](collection []T, comparison func(a T, b T) bool) T { return min } +// Earliest search the minimum time.Time of a collection. +// Returns zero value when the collection is empty. +func Earliest(times ...time.Time) time.Time { + var min time.Time + + if len(times) == 0 { + return min + } + + min = times[0] + + for i := 1; i < len(times); i++ { + item := times[i] + + if item.Before(min) { + min = item + } + } + + return min +} + +// EarliestBy search the minimum time.Time of a collection using the given iteratee function. +// Returns zero value when the collection is empty. +func EarliestBy[T any](collection []T, iteratee func(item T) time.Time) T { + var earliest T + + if len(collection) == 0 { + return earliest + } + + earliest = collection[0] + earliestTime := iteratee(collection[0]) + + for i := 1; i < len(collection); i++ { + itemTime := iteratee(collection[i]) + + if itemTime.Before(earliestTime) { + earliest = collection[i] + earliestTime = itemTime + } + } + + return earliest +} + // Max searches the maximum value of a collection. -// Returns zero value when collection is empty. +// Returns zero value when the collection is empty. func Max[T constraints.Ordered](collection []T) T { var max T @@ -289,7 +334,7 @@ func Max[T constraints.Ordered](collection []T) T { // MaxBy search the maximum value of a collection using the given comparison function. // If several values of the collection are equal to the greatest value, returns the first such value. -// Returns zero value when collection is empty. +// Returns zero value when the collection is empty. func MaxBy[T any](collection []T, comparison func(a T, b T) bool) T { var max T @@ -310,16 +355,106 @@ func MaxBy[T any](collection []T, comparison func(a T, b T) bool) T { return max } +// Latest search the maximum time.Time of a collection. +// Returns zero value when the collection is empty. +func Latest(times ...time.Time) time.Time { + var max time.Time + + if len(times) == 0 { + return max + } + + max = times[0] + + for i := 1; i < len(times); i++ { + item := times[i] + + if item.After(max) { + max = item + } + } + + return max +} + +// LatestBy search the maximum time.Time of a collection using the given iteratee function. +// Returns zero value when the collection is empty. +func LatestBy[T any](collection []T, iteratee func(item T) time.Time) T { + var latest T + + if len(collection) == 0 { + return latest + } + + latest = collection[0] + latestTime := iteratee(collection[0]) + + for i := 1; i < len(collection); i++ { + itemTime := iteratee(collection[i]) + + if itemTime.After(latestTime) { + latest = collection[i] + latestTime = itemTime + } + } + + return latest +} + +// First returns the first element of a collection and check for availability of the first element. +func First[T any](collection []T) (T, bool) { + length := len(collection) + + if length == 0 { + var t T + return t, false + } + + return collection[0], true +} + +// FirstOrEmpty returns the first element of a collection or zero value if empty. +func FirstOrEmpty[T any](collection []T) T { + i, _ := First(collection) + return i +} + +// FirstOr returns the first element of a collection or the fallback value if empty. +func FirstOr[T any](collection []T, fallback T) T { + i, ok := First(collection) + if !ok { + return fallback + } + + return i +} + // Last returns the last element of a collection or error if empty. -func Last[T any](collection []T) (T, error) { +func Last[T any](collection []T) (T, bool) { length := len(collection) if length == 0 { var t T - return t, fmt.Errorf("last: cannot extract the last element of an empty slice") + return t, false + } + + return collection[length-1], true +} + +// Returns the last element of a collection or zero value if empty. +func LastOrEmpty[T any](collection []T) T { + i, _ := Last(collection) + return i +} + +// LastOr returns the last element of a collection or the fallback value if empty. +func LastOr[T any](collection []T, fallback T) T { + i, ok := Last(collection) + if !ok { + return fallback } - return collection[length-1], nil + return i } // Nth returns the element at index `nth` of collection. If `nth` is negative, the nth element @@ -345,21 +480,21 @@ func Sample[T any](collection []T) T { return Empty[T]() } - return collection[rand.Intn(size)] + return collection[rand.IntN(size)] } // Samples returns N random unique items from collection. -func Samples[T any](collection []T, count int) []T { +func Samples[T any, Slice ~[]T](collection Slice, count int) Slice { size := len(collection) - copy := append([]T{}, collection...) + copy := append(Slice{}, collection...) - results := []T{} + results := Slice{} for i := 0; i < size && i < count; i++ { copyLength := size - i - index := rand.Intn(size - i) + index := rand.IntN(size - i) results = append(results, copy[index]) // Removes element. diff --git a/vendor/github.com/samber/lo/internal/constraints/constraints.go b/vendor/github.com/samber/lo/internal/constraints/constraints.go new file mode 100644 index 0000000000..3eb1cda55f --- /dev/null +++ b/vendor/github.com/samber/lo/internal/constraints/constraints.go @@ -0,0 +1,42 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package constraints defines a set of useful constraints to be used +// with type parameters. +package constraints + +// Signed is a constraint that permits any signed integer type. +// If future releases of Go add new predeclared signed integer types, +// this constraint will be modified to include them. +type Signed interface { + ~int | ~int8 | ~int16 | ~int32 | ~int64 +} + +// Unsigned is a constraint that permits any unsigned integer type. +// If future releases of Go add new predeclared unsigned integer types, +// this constraint will be modified to include them. +type Unsigned interface { + ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr +} + +// Integer is a constraint that permits any integer type. +// If future releases of Go add new predeclared integer types, +// this constraint will be modified to include them. +type Integer interface { + Signed | Unsigned +} + +// Float is a constraint that permits any floating-point type. +// If future releases of Go add new predeclared floating-point types, +// this constraint will be modified to include them. +type Float interface { + ~float32 | ~float64 +} + +// Complex is a constraint that permits any complex numeric type. +// If future releases of Go add new predeclared complex numeric types, +// this constraint will be modified to include them. +type Complex interface { + ~complex64 | ~complex128 +} diff --git a/vendor/github.com/samber/lo/internal/constraints/ordered_go118.go b/vendor/github.com/samber/lo/internal/constraints/ordered_go118.go new file mode 100644 index 0000000000..a124366fd3 --- /dev/null +++ b/vendor/github.com/samber/lo/internal/constraints/ordered_go118.go @@ -0,0 +1,11 @@ +//go:build !go1.21 + +package constraints + +// Ordered is a constraint that permits any ordered type: any type +// that supports the operators < <= >= >. +// If future releases of Go add new ordered types, +// this constraint will be modified to include them. +type Ordered interface { + Integer | Float | ~string +} diff --git a/vendor/github.com/samber/lo/internal/constraints/ordered_go121.go b/vendor/github.com/samber/lo/internal/constraints/ordered_go121.go new file mode 100644 index 0000000000..c02de93548 --- /dev/null +++ b/vendor/github.com/samber/lo/internal/constraints/ordered_go121.go @@ -0,0 +1,9 @@ +//go:build go1.21 + +package constraints + +import ( + "cmp" +) + +type Ordered = cmp.Ordered diff --git a/vendor/github.com/samber/lo/internal/rand/ordered_go118.go b/vendor/github.com/samber/lo/internal/rand/ordered_go118.go new file mode 100644 index 0000000000..a31bb9f2ae --- /dev/null +++ b/vendor/github.com/samber/lo/internal/rand/ordered_go118.go @@ -0,0 +1,14 @@ +//go:build !go1.22 + +package rand + +import "math/rand" + +func Shuffle(n int, swap func(i, j int)) { + rand.Shuffle(n, swap) +} + +func IntN(n int) int { + // bearer:disable go_gosec_crypto_weak_random + return rand.Intn(n) +} diff --git a/vendor/github.com/samber/lo/internal/rand/ordered_go122.go b/vendor/github.com/samber/lo/internal/rand/ordered_go122.go new file mode 100644 index 0000000000..532ed33933 --- /dev/null +++ b/vendor/github.com/samber/lo/internal/rand/ordered_go122.go @@ -0,0 +1,13 @@ +//go:build go1.22 + +package rand + +import "math/rand/v2" + +func Shuffle(n int, swap func(i, j int)) { + rand.Shuffle(n, swap) +} + +func IntN(n int) int { + return rand.IntN(n) +} diff --git a/vendor/github.com/samber/lo/intersect.go b/vendor/github.com/samber/lo/intersect.go index cf6cab3d13..2df0e74157 100644 --- a/vendor/github.com/samber/lo/intersect.go +++ b/vendor/github.com/samber/lo/intersect.go @@ -2,8 +2,8 @@ package lo // Contains returns true if an element is present in a collection. func Contains[T comparable](collection []T, element T) bool { - for _, item := range collection { - if item == element { + for i := range collection { + if collection[i] == element { return true } } @@ -13,8 +13,8 @@ func Contains[T comparable](collection []T, element T) bool { // ContainsBy returns true if predicate function return true. func ContainsBy[T any](collection []T, predicate func(item T) bool) bool { - for _, item := range collection { - if predicate(item) { + for i := range collection { + if predicate(collection[i]) { return true } } @@ -24,8 +24,8 @@ func ContainsBy[T any](collection []T, predicate func(item T) bool) bool { // Every returns true if all elements of a subset are contained into a collection or if the subset is empty. func Every[T comparable](collection []T, subset []T) bool { - for _, elem := range subset { - if !Contains(collection, elem) { + for i := range subset { + if !Contains(collection, subset[i]) { return false } } @@ -35,8 +35,8 @@ func Every[T comparable](collection []T, subset []T) bool { // EveryBy returns true if the predicate returns true for all of the elements in the collection or if the collection is empty. func EveryBy[T any](collection []T, predicate func(item T) bool) bool { - for _, v := range collection { - if !predicate(v) { + for i := range collection { + if !predicate(collection[i]) { return false } } @@ -47,8 +47,8 @@ func EveryBy[T any](collection []T, predicate func(item T) bool) bool { // Some returns true if at least 1 element of a subset is contained into a collection. // If the subset is empty Some returns false. func Some[T comparable](collection []T, subset []T) bool { - for _, elem := range subset { - if Contains(collection, elem) { + for i := range subset { + if Contains(collection, subset[i]) { return true } } @@ -59,8 +59,8 @@ func Some[T comparable](collection []T, subset []T) bool { // SomeBy returns true if the predicate returns true for any of the elements in the collection. // If the collection is empty SomeBy returns false. func SomeBy[T any](collection []T, predicate func(item T) bool) bool { - for _, v := range collection { - if predicate(v) { + for i := range collection { + if predicate(collection[i]) { return true } } @@ -70,8 +70,8 @@ func SomeBy[T any](collection []T, predicate func(item T) bool) bool { // None returns true if no element of a subset are contained into a collection or if the subset is empty. func None[T comparable](collection []T, subset []T) bool { - for _, elem := range subset { - if Contains(collection, elem) { + for i := range subset { + if Contains(collection, subset[i]) { return false } } @@ -81,8 +81,8 @@ func None[T comparable](collection []T, subset []T) bool { // NoneBy returns true if the predicate returns true for none of the elements in the collection or if the collection is empty. func NoneBy[T any](collection []T, predicate func(item T) bool) bool { - for _, v := range collection { - if predicate(v) { + for i := range collection { + if predicate(collection[i]) { return false } } @@ -91,17 +91,17 @@ func NoneBy[T any](collection []T, predicate func(item T) bool) bool { } // Intersect returns the intersection between two collections. -func Intersect[T comparable](list1 []T, list2 []T) []T { - result := []T{} +func Intersect[T comparable, Slice ~[]T](list1 Slice, list2 Slice) Slice { + result := Slice{} seen := map[T]struct{}{} - for _, elem := range list1 { - seen[elem] = struct{}{} + for i := range list1 { + seen[list1[i]] = struct{}{} } - for _, elem := range list2 { - if _, ok := seen[elem]; ok { - result = append(result, elem) + for i := range list2 { + if _, ok := seen[list2[i]]; ok { + result = append(result, list2[i]) } } @@ -111,30 +111,30 @@ func Intersect[T comparable](list1 []T, list2 []T) []T { // Difference returns the difference between two collections. // The first value is the collection of element absent of list2. // The second value is the collection of element absent of list1. -func Difference[T comparable](list1 []T, list2 []T) ([]T, []T) { - left := []T{} - right := []T{} +func Difference[T comparable, Slice ~[]T](list1 Slice, list2 Slice) (Slice, Slice) { + left := Slice{} + right := Slice{} seenLeft := map[T]struct{}{} seenRight := map[T]struct{}{} - for _, elem := range list1 { - seenLeft[elem] = struct{}{} + for i := range list1 { + seenLeft[list1[i]] = struct{}{} } - for _, elem := range list2 { - seenRight[elem] = struct{}{} + for i := range list2 { + seenRight[list2[i]] = struct{}{} } - for _, elem := range list1 { - if _, ok := seenRight[elem]; !ok { - left = append(left, elem) + for i := range list1 { + if _, ok := seenRight[list1[i]]; !ok { + left = append(left, list1[i]) } } - for _, elem := range list2 { - if _, ok := seenLeft[elem]; !ok { - right = append(right, elem) + for i := range list2 { + if _, ok := seenLeft[list2[i]]; !ok { + right = append(right, list2[i]) } } @@ -143,15 +143,21 @@ func Difference[T comparable](list1 []T, list2 []T) ([]T, []T) { // Union returns all distinct elements from given collections. // result returns will not change the order of elements relatively. -func Union[T comparable](lists ...[]T) []T { - result := []T{} - seen := map[T]struct{}{} +func Union[T comparable, Slice ~[]T](lists ...Slice) Slice { + var capLen int for _, list := range lists { - for _, e := range list { - if _, ok := seen[e]; !ok { - seen[e] = struct{}{} - result = append(result, e) + capLen += len(list) + } + + result := make(Slice, 0, capLen) + seen := make(map[T]struct{}, capLen) + + for i := range lists { + for j := range lists[i] { + if _, ok := seen[lists[i][j]]; !ok { + seen[lists[i][j]] = struct{}{} + result = append(result, lists[i][j]) } } } @@ -160,26 +166,19 @@ func Union[T comparable](lists ...[]T) []T { } // Without returns slice excluding all given values. -func Without[T comparable](collection []T, exclude ...T) []T { - result := make([]T, 0, len(collection)) - for _, e := range collection { - if !Contains(exclude, e) { - result = append(result, e) +func Without[T comparable, Slice ~[]T](collection Slice, exclude ...T) Slice { + result := make(Slice, 0, len(collection)) + for i := range collection { + if !Contains(exclude, collection[i]) { + result = append(result, collection[i]) } } return result } // WithoutEmpty returns slice excluding empty values. -func WithoutEmpty[T comparable](collection []T) []T { - var empty T - - result := make([]T, 0, len(collection)) - for _, e := range collection { - if e != empty { - result = append(result, e) - } - } - - return result +// +// Deprecated: Use lo.Compact instead. +func WithoutEmpty[T comparable, Slice ~[]T](collection Slice) Slice { + return Compact(collection) } diff --git a/vendor/github.com/samber/lo/map.go b/vendor/github.com/samber/lo/map.go index 9c0ac4826b..d8feb434ec 100644 --- a/vendor/github.com/samber/lo/map.go +++ b/vendor/github.com/samber/lo/map.go @@ -2,23 +2,91 @@ package lo // Keys creates an array of the map keys. // Play: https://go.dev/play/p/Uu11fHASqrU -func Keys[K comparable, V any](in map[K]V) []K { - result := make([]K, 0, len(in)) +func Keys[K comparable, V any](in ...map[K]V) []K { + size := 0 + for i := range in { + size += len(in[i]) + } + result := make([]K, 0, size) - for k := range in { - result = append(result, k) + for i := range in { + for k := range in[i] { + result = append(result, k) + } } return result } +// UniqKeys creates an array of unique keys in the map. +// Play: https://go.dev/play/p/TPKAb6ILdHk +func UniqKeys[K comparable, V any](in ...map[K]V) []K { + size := 0 + for i := range in { + size += len(in[i]) + } + + seen := make(map[K]struct{}, size) + result := make([]K, 0) + + for i := range in { + for k := range in[i] { + if _, exists := seen[k]; exists { + continue + } + seen[k] = struct{}{} + result = append(result, k) + } + } + + return result +} + +// HasKey returns whether the given key exists. +// Play: https://go.dev/play/p/aVwubIvECqS +func HasKey[K comparable, V any](in map[K]V, key K) bool { + _, ok := in[key] + return ok +} + // Values creates an array of the map values. // Play: https://go.dev/play/p/nnRTQkzQfF6 -func Values[K comparable, V any](in map[K]V) []V { - result := make([]V, 0, len(in)) +func Values[K comparable, V any](in ...map[K]V) []V { + size := 0 + for i := range in { + size += len(in[i]) + } + result := make([]V, 0, size) - for _, v := range in { - result = append(result, v) + for i := range in { + for k := range in[i] { + result = append(result, in[i][k]) + } + } + + return result +} + +// UniqValues creates an array of unique values in the map. +// Play: https://go.dev/play/p/nf6bXMh7rM3 +func UniqValues[K comparable, V comparable](in ...map[K]V) []V { + size := 0 + for i := range in { + size += len(in[i]) + } + + seen := make(map[V]struct{}, size) + result := make([]V, 0) + + for i := range in { + for k := range in[i] { + val := in[i][k] + if _, exists := seen[val]; exists { + continue + } + seen[val] = struct{}{} + result = append(result, val) + } } return result @@ -35,11 +103,11 @@ func ValueOr[K comparable, V any](in map[K]V, key K, fallback V) V { // PickBy returns same map type filtered by given predicate. // Play: https://go.dev/play/p/kdg8GR_QMmf -func PickBy[K comparable, V any](in map[K]V, predicate func(key K, value V) bool) map[K]V { - r := map[K]V{} - for k, v := range in { - if predicate(k, v) { - r[k] = v +func PickBy[K comparable, V any, Map ~map[K]V](in Map, predicate func(key K, value V) bool) Map { + r := Map{} + for k := range in { + if predicate(k, in[k]) { + r[k] = in[k] } } return r @@ -47,11 +115,11 @@ func PickBy[K comparable, V any](in map[K]V, predicate func(key K, value V) bool // PickByKeys returns same map type filtered by given keys. // Play: https://go.dev/play/p/R1imbuci9qU -func PickByKeys[K comparable, V any](in map[K]V, keys []K) map[K]V { - r := map[K]V{} - for k, v := range in { - if Contains(keys, k) { - r[k] = v +func PickByKeys[K comparable, V any, Map ~map[K]V](in Map, keys []K) Map { + r := Map{} + for i := range keys { + if v, ok := in[keys[i]]; ok { + r[keys[i]] = v } } return r @@ -59,11 +127,11 @@ func PickByKeys[K comparable, V any](in map[K]V, keys []K) map[K]V { // PickByValues returns same map type filtered by given values. // Play: https://go.dev/play/p/1zdzSvbfsJc -func PickByValues[K comparable, V comparable](in map[K]V, values []V) map[K]V { - r := map[K]V{} - for k, v := range in { - if Contains(values, v) { - r[k] = v +func PickByValues[K comparable, V comparable, Map ~map[K]V](in Map, values []V) Map { + r := Map{} + for k := range in { + if Contains(values, in[k]) { + r[k] = in[k] } } return r @@ -71,11 +139,11 @@ func PickByValues[K comparable, V comparable](in map[K]V, values []V) map[K]V { // OmitBy returns same map type filtered by given predicate. // Play: https://go.dev/play/p/EtBsR43bdsd -func OmitBy[K comparable, V any](in map[K]V, predicate func(key K, value V) bool) map[K]V { - r := map[K]V{} - for k, v := range in { - if !predicate(k, v) { - r[k] = v +func OmitBy[K comparable, V any, Map ~map[K]V](in Map, predicate func(key K, value V) bool) Map { + r := Map{} + for k := range in { + if !predicate(k, in[k]) { + r[k] = in[k] } } return r @@ -83,23 +151,24 @@ func OmitBy[K comparable, V any](in map[K]V, predicate func(key K, value V) bool // OmitByKeys returns same map type filtered by given keys. // Play: https://go.dev/play/p/t1QjCrs-ysk -func OmitByKeys[K comparable, V any](in map[K]V, keys []K) map[K]V { - r := map[K]V{} - for k, v := range in { - if !Contains(keys, k) { - r[k] = v - } +func OmitByKeys[K comparable, V any, Map ~map[K]V](in Map, keys []K) Map { + r := Map{} + for k := range in { + r[k] = in[k] + } + for i := range keys { + delete(r, keys[i]) } return r } // OmitByValues returns same map type filtered by given values. // Play: https://go.dev/play/p/9UYZi-hrs8j -func OmitByValues[K comparable, V comparable](in map[K]V, values []V) map[K]V { - r := map[K]V{} - for k, v := range in { - if !Contains(values, v) { - r[k] = v +func OmitByValues[K comparable, V comparable, Map ~map[K]V](in Map, values []V) Map { + r := Map{} + for k := range in { + if !Contains(values, in[k]) { + r[k] = in[k] } } return r @@ -110,10 +179,10 @@ func OmitByValues[K comparable, V comparable](in map[K]V, values []V) map[K]V { func Entries[K comparable, V any](in map[K]V) []Entry[K, V] { entries := make([]Entry[K, V], 0, len(in)) - for k, v := range in { + for k := range in { entries = append(entries, Entry[K, V]{ Key: k, - Value: v, + Value: in[k], }) } @@ -132,8 +201,8 @@ func ToPairs[K comparable, V any](in map[K]V) []Entry[K, V] { func FromEntries[K comparable, V any](entries []Entry[K, V]) map[K]V { out := make(map[K]V, len(entries)) - for _, v := range entries { - out[v.Key] = v.Value + for i := range entries { + out[entries[i].Key] = entries[i].Value } return out @@ -153,8 +222,8 @@ func FromPairs[K comparable, V any](entries []Entry[K, V]) map[K]V { func Invert[K comparable, V comparable](in map[K]V) map[V]K { out := make(map[V]K, len(in)) - for k, v := range in { - out[v] = k + for k := range in { + out[in[k]] = k } return out @@ -162,12 +231,16 @@ func Invert[K comparable, V comparable](in map[K]V) map[V]K { // Assign merges multiple maps from left to right. // Play: https://go.dev/play/p/VhwfJOyxf5o -func Assign[K comparable, V any](maps ...map[K]V) map[K]V { - out := map[K]V{} +func Assign[K comparable, V any, Map ~map[K]V](maps ...Map) Map { + count := 0 + for i := range maps { + count += len(maps[i]) + } - for _, m := range maps { - for k, v := range m { - out[k] = v + out := make(Map, count) + for i := range maps { + for k := range maps[i] { + out[k] = maps[i][k] } } @@ -179,8 +252,8 @@ func Assign[K comparable, V any](maps ...map[K]V) map[K]V { func MapKeys[K comparable, V any, R comparable](in map[K]V, iteratee func(value V, key K) R) map[R]V { result := make(map[R]V, len(in)) - for k, v := range in { - result[iteratee(v, k)] = v + for k := range in { + result[iteratee(in[k], k)] = in[k] } return result @@ -191,8 +264,8 @@ func MapKeys[K comparable, V any, R comparable](in map[K]V, iteratee func(value func MapValues[K comparable, V any, R any](in map[K]V, iteratee func(value V, key K) R) map[K]R { result := make(map[K]R, len(in)) - for k, v := range in { - result[k] = iteratee(v, k) + for k := range in { + result[k] = iteratee(in[k], k) } return result @@ -203,8 +276,8 @@ func MapValues[K comparable, V any, R any](in map[K]V, iteratee func(value V, ke func MapEntries[K1 comparable, V1 any, K2 comparable, V2 any](in map[K1]V1, iteratee func(key K1, value V1) (K2, V2)) map[K2]V2 { result := make(map[K2]V2, len(in)) - for k1, v1 := range in { - k2, v2 := iteratee(k1, v1) + for k1 := range in { + k2, v2 := iteratee(k1, in[k1]) result[k2] = v2 } @@ -216,8 +289,8 @@ func MapEntries[K1 comparable, V1 any, K2 comparable, V2 any](in map[K1]V1, iter func MapToSlice[K comparable, V any, R any](in map[K]V, iteratee func(key K, value V) R) []R { result := make([]R, 0, len(in)) - for k, v := range in { - result = append(result, iteratee(k, v)) + for k := range in { + result = append(result, iteratee(k, in[k])) } return result diff --git a/vendor/github.com/samber/lo/math.go b/vendor/github.com/samber/lo/math.go index 9dce28cf83..e866f88e04 100644 --- a/vendor/github.com/samber/lo/math.go +++ b/vendor/github.com/samber/lo/math.go @@ -1,6 +1,8 @@ package lo -import "golang.org/x/exp/constraints" +import ( + "github.com/samber/lo/internal/constraints" +) // Range creates an array of numbers (positive and/or negative) with given length. // Play: https://go.dev/play/p/0r6VimXAi9H @@ -67,8 +69,8 @@ func Clamp[T constraints.Ordered](value T, min T, max T) T { // Play: https://go.dev/play/p/upfeJVqs4Bt func Sum[T constraints.Float | constraints.Integer | constraints.Complex](collection []T) T { var sum T = 0 - for _, val := range collection { - sum += val + for i := range collection { + sum += collection[i] } return sum } @@ -77,8 +79,28 @@ func Sum[T constraints.Float | constraints.Integer | constraints.Complex](collec // Play: https://go.dev/play/p/Dz_a_7jN_ca func SumBy[T any, R constraints.Float | constraints.Integer | constraints.Complex](collection []T, iteratee func(item T) R) R { var sum R = 0 - for _, item := range collection { - sum = sum + iteratee(item) + for i := range collection { + sum = sum + iteratee(collection[i]) } return sum } + +// Mean calculates the mean of a collection of numbers. +func Mean[T constraints.Float | constraints.Integer](collection []T) T { + var length T = T(len(collection)) + if length == 0 { + return 0 + } + var sum T = Sum(collection) + return sum / length +} + +// MeanBy calculates the mean of a collection of numbers using the given return value from the iteration function. +func MeanBy[T any, R constraints.Float | constraints.Integer](collection []T, iteratee func(item T) R) R { + var length R = R(len(collection)) + if length == 0 { + return 0 + } + var sum R = SumBy(collection, iteratee) + return sum / length +} diff --git a/vendor/github.com/samber/lo/retry.go b/vendor/github.com/samber/lo/retry.go index c3c264fff9..f026aa3319 100644 --- a/vendor/github.com/samber/lo/retry.go +++ b/vendor/github.com/samber/lo/retry.go @@ -26,8 +26,8 @@ func (d *debounce) reset() { } d.timer = time.AfterFunc(d.after, func() { - for _, f := range d.callbacks { - f() + for i := range d.callbacks { + d.callbacks[i]() } }) } @@ -101,8 +101,8 @@ func (d *debounceBy[T]) reset(key T) { item.count = 0 item.mu.Unlock() - for _, f := range d.callbacks { - f(key, count) + for i := range d.callbacks { + d.callbacks[i](key, count) } }) @@ -239,7 +239,7 @@ type transactionStep[T any] struct { onRollback func(T) T } -// NewTransaction instanciate a new transaction. +// NewTransaction instantiate a new transaction. func NewTransaction[T any]() *Transaction[T] { return &Transaction[T]{ steps: []transactionStep[T]{}, diff --git a/vendor/github.com/samber/lo/slice.go b/vendor/github.com/samber/lo/slice.go index 49c991f894..d2d3fd84ae 100644 --- a/vendor/github.com/samber/lo/slice.go +++ b/vendor/github.com/samber/lo/slice.go @@ -1,19 +1,20 @@ package lo import ( - "math/rand" + "sort" - "golang.org/x/exp/constraints" + "github.com/samber/lo/internal/constraints" + "github.com/samber/lo/internal/rand" ) // Filter iterates over elements of collection, returning an array of all elements predicate returns truthy for. // Play: https://go.dev/play/p/Apjg3WeSi7K -func Filter[V any](collection []V, predicate func(item V, index int) bool) []V { - result := make([]V, 0, len(collection)) +func Filter[T any, Slice ~[]T](collection Slice, predicate func(item T, index int) bool) Slice { + result := make(Slice, 0, len(collection)) - for i, item := range collection { - if predicate(item, i) { - result = append(result, item) + for i := range collection { + if predicate(collection[i], i) { + result = append(result, collection[i]) } } @@ -25,8 +26,8 @@ func Filter[V any](collection []V, predicate func(item V, index int) bool) []V { func Map[T any, R any](collection []T, iteratee func(item T, index int) R) []R { result := make([]R, len(collection)) - for i, item := range collection { - result[i] = iteratee(item, i) + for i := range collection { + result[i] = iteratee(collection[i], i) } return result @@ -41,8 +42,8 @@ func Map[T any, R any](collection []T, iteratee func(item T, index int) R) []R { func FilterMap[T any, R any](collection []T, callback func(item T, index int) (R, bool)) []R { result := []R{} - for i, item := range collection { - if r, ok := callback(item, i); ok { + for i := range collection { + if r, ok := callback(collection[i], i); ok { result = append(result, r) } } @@ -57,8 +58,8 @@ func FilterMap[T any, R any](collection []T, callback func(item T, index int) (R func FlatMap[T any, R any](collection []T, iteratee func(item T, index int) []R) []R { result := make([]R, 0, len(collection)) - for i, item := range collection { - result = append(result, iteratee(item, i)...) + for i := range collection { + result = append(result, iteratee(collection[i], i)...) } return result @@ -68,8 +69,8 @@ func FlatMap[T any, R any](collection []T, iteratee func(item T, index int) []R) // through accumulator, where each successive invocation is supplied the return value of the previous. // Play: https://go.dev/play/p/R4UHXZNaaUG func Reduce[T any, R any](collection []T, accumulator func(agg R, item T, index int) R, initial R) R { - for i, item := range collection { - initial = accumulator(initial, item, i) + for i := range collection { + initial = accumulator(initial, collection[i], i) } return initial @@ -88,8 +89,19 @@ func ReduceRight[T any, R any](collection []T, accumulator func(agg R, item T, i // ForEach iterates over elements of collection and invokes iteratee for each element. // Play: https://go.dev/play/p/oofyiUPRf8t func ForEach[T any](collection []T, iteratee func(item T, index int)) { - for i, item := range collection { - iteratee(item, i) + for i := range collection { + iteratee(collection[i], i) + } +} + +// ForEachWhile iterates over elements of collection and invokes iteratee for each element +// collection return value decide to continue or break, like do while(). +// Play: https://go.dev/play/p/QnLGt35tnow +func ForEachWhile[T any](collection []T, iteratee func(item T, index int) (goon bool)) { + for i := range collection { + if !iteratee(collection[i], i) { + break + } } } @@ -109,17 +121,17 @@ func Times[T any](count int, iteratee func(index int) T) []T { // Uniq returns a duplicate-free version of an array, in which only the first occurrence of each element is kept. // The order of result values is determined by the order they occur in the array. // Play: https://go.dev/play/p/DTzbeXZ6iEN -func Uniq[T comparable](collection []T) []T { - result := make([]T, 0, len(collection)) +func Uniq[T comparable, Slice ~[]T](collection Slice) Slice { + result := make(Slice, 0, len(collection)) seen := make(map[T]struct{}, len(collection)) - for _, item := range collection { - if _, ok := seen[item]; ok { + for i := range collection { + if _, ok := seen[collection[i]]; ok { continue } - seen[item] = struct{}{} - result = append(result, item) + seen[collection[i]] = struct{}{} + result = append(result, collection[i]) } return result @@ -129,19 +141,19 @@ func Uniq[T comparable](collection []T) []T { // The order of result values is determined by the order they occur in the array. It accepts `iteratee` which is // invoked for each element in array to generate the criterion by which uniqueness is computed. // Play: https://go.dev/play/p/g42Z3QSb53u -func UniqBy[T any, U comparable](collection []T, iteratee func(item T) U) []T { - result := make([]T, 0, len(collection)) +func UniqBy[T any, U comparable, Slice ~[]T](collection Slice, iteratee func(item T) U) Slice { + result := make(Slice, 0, len(collection)) seen := make(map[U]struct{}, len(collection)) - for _, item := range collection { - key := iteratee(item) + for i := range collection { + key := iteratee(collection[i]) if _, ok := seen[key]; ok { continue } seen[key] = struct{}{} - result = append(result, item) + result = append(result, collection[i]) } return result @@ -149,13 +161,13 @@ func UniqBy[T any, U comparable](collection []T, iteratee func(item T) U) []T { // GroupBy returns an object composed of keys generated from the results of running each element of collection through iteratee. // Play: https://go.dev/play/p/XnQBd_v6brd -func GroupBy[T any, U comparable](collection []T, iteratee func(item T) U) map[U][]T { - result := map[U][]T{} +func GroupBy[T any, U comparable, Slice ~[]T](collection Slice, iteratee func(item T) U) map[U]Slice { + result := map[U]Slice{} - for _, item := range collection { - key := iteratee(item) + for i := range collection { + key := iteratee(collection[i]) - result[key] = append(result[key], item) + result[key] = append(result[key], collection[i]) } return result @@ -164,7 +176,7 @@ func GroupBy[T any, U comparable](collection []T, iteratee func(item T) U) map[U // Chunk returns an array of elements split into groups the length of size. If array can't be split evenly, // the final chunk will be the remaining elements. // Play: https://go.dev/play/p/EeKl0AuTehH -func Chunk[T any](collection []T, size int) [][]T { +func Chunk[T any, Slice ~[]T](collection Slice, size int) []Slice { if size <= 0 { panic("Second parameter must be greater than 0") } @@ -174,14 +186,14 @@ func Chunk[T any](collection []T, size int) [][]T { chunksNum += 1 } - result := make([][]T, 0, chunksNum) + result := make([]Slice, 0, chunksNum) for i := 0; i < chunksNum; i++ { last := (i + 1) * size if last > len(collection) { last = len(collection) } - result = append(result, collection[i*size:last]) + result = append(result, collection[i*size:last:last]) } return result @@ -191,21 +203,21 @@ func Chunk[T any](collection []T, size int) [][]T { // determined by the order they occur in collection. The grouping is generated from the results // of running each element of collection through iteratee. // Play: https://go.dev/play/p/NfQ_nGjkgXW -func PartitionBy[T any, K comparable](collection []T, iteratee func(item T) K) [][]T { - result := [][]T{} +func PartitionBy[T any, K comparable, Slice ~[]T](collection Slice, iteratee func(item T) K) []Slice { + result := []Slice{} seen := map[K]int{} - for _, item := range collection { - key := iteratee(item) + for i := range collection { + key := iteratee(collection[i]) resultIndex, ok := seen[key] if !ok { resultIndex = len(result) seen[key] = resultIndex - result = append(result, []T{}) + result = append(result, Slice{}) } - result[resultIndex] = append(result[resultIndex], item) + result[resultIndex] = append(result[resultIndex], collection[i]) } return result @@ -217,13 +229,13 @@ func PartitionBy[T any, K comparable](collection []T, iteratee func(item T) K) [ // Flatten returns an array a single level deep. // Play: https://go.dev/play/p/rbp9ORaMpjw -func Flatten[T any](collection [][]T) []T { +func Flatten[T any, Slice ~[]T](collection []Slice) Slice { totalLen := 0 for i := range collection { totalLen += len(collection[i]) } - result := make([]T, 0, totalLen) + result := make(Slice, 0, totalLen) for i := range collection { result = append(result, collection[i]...) } @@ -232,16 +244,16 @@ func Flatten[T any](collection [][]T) []T { } // Interleave round-robin alternating input slices and sequentially appending value at index into result -// Play: https://go.dev/play/p/DDhlwrShbwe -func Interleave[T any](collections ...[]T) []T { +// Play: https://go.dev/play/p/-RJkTLQEDVt +func Interleave[T any, Slice ~[]T](collections ...Slice) Slice { if len(collections) == 0 { - return []T{} + return Slice{} } maxSize := 0 totalSize := 0 - for _, c := range collections { - size := len(c) + for i := range collections { + size := len(collections[i]) totalSize += size if size > maxSize { maxSize = size @@ -249,10 +261,10 @@ func Interleave[T any](collections ...[]T) []T { } if maxSize == 0 { - return []T{} + return Slice{} } - result := make([]T, totalSize) + result := make(Slice, totalSize) resultIdx := 0 for i := 0; i < maxSize; i++ { @@ -271,7 +283,7 @@ func Interleave[T any](collections ...[]T) []T { // Shuffle returns an array of shuffled values. Uses the Fisher-Yates shuffle algorithm. // Play: https://go.dev/play/p/Qp73bnTDnc7 -func Shuffle[T any](collection []T) []T { +func Shuffle[T any, Slice ~[]T](collection Slice) Slice { rand.Shuffle(len(collection), func(i, j int) { collection[i], collection[j] = collection[j], collection[i] }) @@ -281,7 +293,7 @@ func Shuffle[T any](collection []T) []T { // Reverse reverses array so that the first element becomes the last, the second element becomes the second to last, and so on. // Play: https://go.dev/play/p/fhUMLvZ7vS6 -func Reverse[T any](collection []T) []T { +func Reverse[T any, Slice ~[]T](collection Slice) Slice { length := len(collection) half := length / 2 @@ -334,9 +346,9 @@ func RepeatBy[T any](count int, predicate func(index int) T) []T { func KeyBy[K comparable, V any](collection []V, iteratee func(item V) K) map[K]V { result := make(map[K]V, len(collection)) - for _, v := range collection { - k := iteratee(v) - result[k] = v + for i := range collection { + k := iteratee(collection[i]) + result[k] = collection[i] } return result @@ -349,8 +361,8 @@ func KeyBy[K comparable, V any](collection []V, iteratee func(item V) K) map[K]V func Associate[T any, K comparable, V any](collection []T, transform func(item T) (K, V)) map[K]V { result := make(map[K]V, len(collection)) - for _, t := range collection { - k, v := transform(t) + for i := range collection { + k, v := transform(collection[i]) result[k] = v } @@ -368,30 +380,30 @@ func SliceToMap[T any, K comparable, V any](collection []T, transform func(item // Drop drops n elements from the beginning of a slice or array. // Play: https://go.dev/play/p/JswS7vXRJP2 -func Drop[T any](collection []T, n int) []T { +func Drop[T any, Slice ~[]T](collection Slice, n int) Slice { if len(collection) <= n { - return make([]T, 0) + return make(Slice, 0) } - result := make([]T, 0, len(collection)-n) + result := make(Slice, 0, len(collection)-n) return append(result, collection[n:]...) } // DropRight drops n elements from the end of a slice or array. // Play: https://go.dev/play/p/GG0nXkSJJa3 -func DropRight[T any](collection []T, n int) []T { +func DropRight[T any, Slice ~[]T](collection Slice, n int) Slice { if len(collection) <= n { - return []T{} + return Slice{} } - result := make([]T, 0, len(collection)-n) + result := make(Slice, 0, len(collection)-n) return append(result, collection[:len(collection)-n]...) } // DropWhile drops elements from the beginning of a slice or array while the predicate returns true. // Play: https://go.dev/play/p/7gBPYw2IK16 -func DropWhile[T any](collection []T, predicate func(item T) bool) []T { +func DropWhile[T any, Slice ~[]T](collection Slice, predicate func(item T) bool) Slice { i := 0 for ; i < len(collection); i++ { if !predicate(collection[i]) { @@ -399,13 +411,13 @@ func DropWhile[T any](collection []T, predicate func(item T) bool) []T { } } - result := make([]T, 0, len(collection)-i) + result := make(Slice, 0, len(collection)-i) return append(result, collection[i:]...) } // DropRightWhile drops elements from the end of a slice or array while the predicate returns true. // Play: https://go.dev/play/p/3-n71oEC0Hz -func DropRightWhile[T any](collection []T, predicate func(item T) bool) []T { +func DropRightWhile[T any, Slice ~[]T](collection Slice, predicate func(item T) bool) Slice { i := len(collection) - 1 for ; i >= 0; i-- { if !predicate(collection[i]) { @@ -413,29 +425,94 @@ func DropRightWhile[T any](collection []T, predicate func(item T) bool) []T { } } - result := make([]T, 0, i+1) + result := make(Slice, 0, i+1) return append(result, collection[:i+1]...) } +// DropByIndex drops elements from a slice or array by the index. +// A negative index will drop elements from the end of the slice. +// Play: https://go.dev/play/p/bPIH4npZRxS +func DropByIndex[T any](collection []T, indexes ...int) []T { + initialSize := len(collection) + if initialSize == 0 { + return make([]T, 0) + } + + for i := range indexes { + if indexes[i] < 0 { + indexes[i] = initialSize + indexes[i] + } + } + + indexes = Uniq(indexes) + sort.Ints(indexes) + + result := make([]T, 0, initialSize) + result = append(result, collection...) + + for i := range indexes { + if indexes[i]-i < 0 || indexes[i]-i >= initialSize-i { + continue + } + + result = append(result[:indexes[i]-i], result[indexes[i]-i+1:]...) + } + + return result +} + // Reject is the opposite of Filter, this method returns the elements of collection that predicate does not return truthy for. // Play: https://go.dev/play/p/YkLMODy1WEL -func Reject[V any](collection []V, predicate func(item V, index int) bool) []V { - result := []V{} +func Reject[T any, Slice ~[]T](collection Slice, predicate func(item T, index int) bool) Slice { + result := Slice{} + + for i := range collection { + if !predicate(collection[i], i) { + result = append(result, collection[i]) + } + } + + return result +} + +// RejectMap is the opposite of FilterMap, this method returns a slice which obtained after both filtering and mapping using the given callback function. +// The callback function should return two values: +// - the result of the mapping operation and +// - whether the result element should be included or not. +func RejectMap[T any, R any](collection []T, callback func(item T, index int) (R, bool)) []R { + result := []R{} - for i, item := range collection { - if !predicate(item, i) { - result = append(result, item) + for i := range collection { + if r, ok := callback(collection[i], i); !ok { + result = append(result, r) } } return result } +// FilterReject mixes Filter and Reject, this method returns two slices, one for the elements of collection that +// predicate returns truthy for and one for the elements that predicate does not return truthy for. +func FilterReject[T any, Slice ~[]T](collection Slice, predicate func(T, int) bool) (kept Slice, rejected Slice) { + kept = make(Slice, 0, len(collection)) + rejected = make(Slice, 0, len(collection)) + + for i := range collection { + if predicate(collection[i], i) { + kept = append(kept, collection[i]) + } else { + rejected = append(rejected, collection[i]) + } + } + + return kept, rejected +} + // Count counts the number of elements in the collection that compare equal to value. // Play: https://go.dev/play/p/Y3FlK54yveC func Count[T comparable](collection []T, value T) (count int) { - for _, item := range collection { - if item == value { + for i := range collection { + if collection[i] == value { count++ } } @@ -446,8 +523,8 @@ func Count[T comparable](collection []T, value T) (count int) { // CountBy counts the number of elements in the collection for which predicate is true. // Play: https://go.dev/play/p/ByQbNYQQi4X func CountBy[T any](collection []T, predicate func(item T) bool) (count int) { - for _, item := range collection { - if predicate(item) { + for i := range collection { + if predicate(collection[i]) { count++ } } @@ -460,8 +537,8 @@ func CountBy[T any](collection []T, predicate func(item T) bool) (count int) { func CountValues[T comparable](collection []T) map[T]int { result := make(map[T]int) - for _, item := range collection { - result[item]++ + for i := range collection { + result[collection[i]]++ } return result @@ -473,8 +550,8 @@ func CountValues[T comparable](collection []T) map[T]int { func CountValuesBy[T any, U comparable](collection []T, mapper func(item T) U) map[U]int { result := make(map[U]int) - for _, item := range collection { - result[mapper(item)]++ + for i := range collection { + result[mapper(collection[i])]++ } return result @@ -482,7 +559,7 @@ func CountValuesBy[T any, U comparable](collection []T, mapper func(item T) U) m // Subset returns a copy of a slice from `offset` up to `length` elements. Like `slice[start:start+length]`, but does not panic on overflow. // Play: https://go.dev/play/p/tOQu1GhFcog -func Subset[T any](collection []T, offset int, length uint) []T { +func Subset[T any, Slice ~[]T](collection Slice, offset int, length uint) Slice { size := len(collection) if offset < 0 { @@ -493,7 +570,7 @@ func Subset[T any](collection []T, offset int, length uint) []T { } if offset > size { - return []T{} + return Slice{} } if length > uint(size)-uint(offset) { @@ -505,11 +582,11 @@ func Subset[T any](collection []T, offset int, length uint) []T { // Slice returns a copy of a slice from `start` up to, but not including `end`. Like `slice[start:end]`, but does not panic on overflow. // Play: https://go.dev/play/p/8XWYhfMMA1h -func Slice[T any](collection []T, start int, end int) []T { +func Slice[T any, Slice ~[]T](collection Slice, start int, end int) Slice { size := len(collection) if start >= end { - return []T{} + return Slice{} } if start > size { @@ -531,8 +608,8 @@ func Slice[T any](collection []T, start int, end int) []T { // Replace returns a copy of the slice with the first n non-overlapping instances of old replaced by new. // Play: https://go.dev/play/p/XfPzmf9gql6 -func Replace[T comparable](collection []T, old T, new T, n int) []T { - result := make([]T, len(collection)) +func Replace[T comparable, Slice ~[]T](collection Slice, old T, new T, n int) Slice { + result := make(Slice, len(collection)) copy(result, collection) for i := range result { @@ -547,20 +624,20 @@ func Replace[T comparable](collection []T, old T, new T, n int) []T { // ReplaceAll returns a copy of the slice with all non-overlapping instances of old replaced by new. // Play: https://go.dev/play/p/a9xZFUHfYcV -func ReplaceAll[T comparable](collection []T, old T, new T) []T { +func ReplaceAll[T comparable, Slice ~[]T](collection Slice, old T, new T) Slice { return Replace(collection, old, new, -1) } // Compact returns a slice of all non-zero elements. // Play: https://go.dev/play/p/tXiy-iK6PAc -func Compact[T comparable](collection []T) []T { +func Compact[T comparable, Slice ~[]T](collection Slice) Slice { var zero T - result := make([]T, 0, len(collection)) + result := make(Slice, 0, len(collection)) - for _, item := range collection { - if item != zero { - result = append(result, item) + for i := range collection { + if collection[i] != zero { + result = append(result, collection[i]) } } @@ -592,3 +669,27 @@ func IsSortedByKey[T any, K constraints.Ordered](collection []T, iteratee func(i return true } + +// Splice inserts multiple elements at index i. A negative index counts back +// from the end of the slice. The helper is protected against overflow errors. +// Play: https://go.dev/play/p/G5_GhkeSUBA +func Splice[T any, Slice ~[]T](collection Slice, i int, elements ...T) Slice { + sizeCollection := len(collection) + sizeElements := len(elements) + output := make(Slice, 0, sizeCollection+sizeElements) // preallocate memory for the output slice + + if sizeElements == 0 { + return append(output, collection...) // simple copy + } else if i > sizeCollection { + // positive overflow + return append(append(output, collection...), elements...) + } else if i < -sizeCollection { + // negative overflow + return append(append(output, elements...), collection...) + } else if i < 0 { + // backward + i = sizeCollection + i + } + + return append(append(append(output, collection[:i]...), elements...), collection[i:]...) +} diff --git a/vendor/github.com/samber/lo/string.go b/vendor/github.com/samber/lo/string.go index a7a959a395..1d808788cc 100644 --- a/vendor/github.com/samber/lo/string.go +++ b/vendor/github.com/samber/lo/string.go @@ -1,9 +1,15 @@ package lo import ( - "math/rand" + "regexp" "strings" + "unicode" "unicode/utf8" + + "github.com/samber/lo/internal/rand" + + "golang.org/x/text/cases" + "golang.org/x/text/language" ) var ( @@ -14,6 +20,11 @@ var ( AlphanumericCharset = append(LettersCharset, NumbersCharset...) SpecialCharset = []rune("!@#$%^&*()_+-=[]{}|;':\",./<>?") AllCharset = append(AlphanumericCharset, SpecialCharset...) + + // bearer:disable go_lang_permissive_regex_validation + splitWordReg = regexp.MustCompile(`([a-z])([A-Z0-9])|([a-zA-Z])([0-9])|([0-9])([a-zA-Z])|([A-Z])([A-Z])([a-z])`) + // bearer:disable go_lang_permissive_regex_validation + splitNumberLetterReg = regexp.MustCompile(`([0-9])([a-zA-Z])`) ) // RandomString return a random string. @@ -29,7 +40,7 @@ func RandomString(size int, charset []rune) string { b := make([]rune, size) possibleCharactersCount := len(charset) for i := range b { - b[i] = charset[rand.Intn(possibleCharactersCount)] + b[i] = charset[rand.IntN(possibleCharactersCount)] } return string(b) } @@ -47,7 +58,7 @@ func Substring[T ~string](str T, offset int, length uint) T { } } - if offset > size { + if offset >= size { return Empty[T]() } @@ -94,3 +105,76 @@ func ChunkString[T ~string](str T, size int) []T { func RuneLength(str string) int { return utf8.RuneCountInString(str) } + +// PascalCase converts string to pascal case. +func PascalCase(str string) string { + items := Words(str) + for i := range items { + items[i] = Capitalize(items[i]) + } + return strings.Join(items, "") +} + +// CamelCase converts string to camel case. +func CamelCase(str string) string { + items := Words(str) + for i, item := range items { + item = strings.ToLower(item) + if i > 0 { + item = Capitalize(item) + } + items[i] = item + } + return strings.Join(items, "") +} + +// KebabCase converts string to kebab case. +func KebabCase(str string) string { + items := Words(str) + for i := range items { + items[i] = strings.ToLower(items[i]) + } + return strings.Join(items, "-") +} + +// SnakeCase converts string to snake case. +func SnakeCase(str string) string { + items := Words(str) + for i := range items { + items[i] = strings.ToLower(items[i]) + } + return strings.Join(items, "_") +} + +// Words splits string into an array of its words. +func Words(str string) []string { + str = splitWordReg.ReplaceAllString(str, `$1$3$5$7 $2$4$6$8$9`) + // example: Int8Value => Int 8Value => Int 8 Value + str = splitNumberLetterReg.ReplaceAllString(str, "$1 $2") + var result strings.Builder + for _, r := range str { + if unicode.IsLetter(r) || unicode.IsDigit(r) { + result.WriteRune(r) + } else { + result.WriteRune(' ') + } + } + return strings.Fields(result.String()) +} + +// Capitalize converts the first character of string to upper case and the remaining to lower case. +func Capitalize(str string) string { + return cases.Title(language.English).String(str) +} + +// Elipse truncates a string to a specified length and appends an ellipsis if truncated. +func Elipse(str string, length int) string { + if len(str) > length { + if len(str) < 3 || length < 3 { + return "..." + } + return str[0:length-3] + "..." + } + + return str +} diff --git a/vendor/github.com/samber/lo/time.go b/vendor/github.com/samber/lo/time.go new file mode 100644 index 0000000000..e98e80f9e8 --- /dev/null +++ b/vendor/github.com/samber/lo/time.go @@ -0,0 +1,85 @@ +package lo + +import "time" + +// Duration returns the time taken to execute a function. +func Duration(cb func()) time.Duration { + return Duration0(cb) +} + +// Duration0 returns the time taken to execute a function. +func Duration0(cb func()) time.Duration { + start := time.Now() + cb() + return time.Since(start) +} + +// Duration1 returns the time taken to execute a function. +func Duration1[A any](cb func() A) (A, time.Duration) { + start := time.Now() + a := cb() + return a, time.Since(start) +} + +// Duration2 returns the time taken to execute a function. +func Duration2[A, B any](cb func() (A, B)) (A, B, time.Duration) { + start := time.Now() + a, b := cb() + return a, b, time.Since(start) +} + +// Duration3 returns the time taken to execute a function. +func Duration3[A, B, C any](cb func() (A, B, C)) (A, B, C, time.Duration) { + start := time.Now() + a, b, c := cb() + return a, b, c, time.Since(start) +} + +// Duration4 returns the time taken to execute a function. +func Duration4[A, B, C, D any](cb func() (A, B, C, D)) (A, B, C, D, time.Duration) { + start := time.Now() + a, b, c, d := cb() + return a, b, c, d, time.Since(start) +} + +// Duration5 returns the time taken to execute a function. +func Duration5[A, B, C, D, E any](cb func() (A, B, C, D, E)) (A, B, C, D, E, time.Duration) { + start := time.Now() + a, b, c, d, e := cb() + return a, b, c, d, e, time.Since(start) +} + +// Duration6 returns the time taken to execute a function. +func Duration6[A, B, C, D, E, F any](cb func() (A, B, C, D, E, F)) (A, B, C, D, E, F, time.Duration) { + start := time.Now() + a, b, c, d, e, f := cb() + return a, b, c, d, e, f, time.Since(start) +} + +// Duration7 returns the time taken to execute a function. +func Duration7[A, B, C, D, E, F, G any](cb func() (A, B, C, D, E, F, G)) (A, B, C, D, E, F, G, time.Duration) { + start := time.Now() + a, b, c, d, e, f, g := cb() + return a, b, c, d, e, f, g, time.Since(start) +} + +// Duration8 returns the time taken to execute a function. +func Duration8[A, B, C, D, E, F, G, H any](cb func() (A, B, C, D, E, F, G, H)) (A, B, C, D, E, F, G, H, time.Duration) { + start := time.Now() + a, b, c, d, e, f, g, h := cb() + return a, b, c, d, e, f, g, h, time.Since(start) +} + +// Duration9 returns the time taken to execute a function. +func Duration9[A, B, C, D, E, F, G, H, I any](cb func() (A, B, C, D, E, F, G, H, I)) (A, B, C, D, E, F, G, H, I, time.Duration) { + start := time.Now() + a, b, c, d, e, f, g, h, i := cb() + return a, b, c, d, e, f, g, h, i, time.Since(start) +} + +// Duration10 returns the time taken to execute a function. +func Duration10[A, B, C, D, E, F, G, H, I, J any](cb func() (A, B, C, D, E, F, G, H, I, J)) (A, B, C, D, E, F, G, H, I, J, time.Duration) { + start := time.Now() + a, b, c, d, e, f, g, h, i, j := cb() + return a, b, c, d, e, f, g, h, i, j, time.Since(start) +} diff --git a/vendor/github.com/samber/lo/tuples.go b/vendor/github.com/samber/lo/tuples.go index cdddf6afc1..18a03009dc 100644 --- a/vendor/github.com/samber/lo/tuples.go +++ b/vendor/github.com/samber/lo/tuples.go @@ -2,97 +2,97 @@ package lo // T2 creates a tuple from a list of values. // Play: https://go.dev/play/p/IllL3ZO4BQm -func T2[A any, B any](a A, b B) Tuple2[A, B] { +func T2[A, B any](a A, b B) Tuple2[A, B] { return Tuple2[A, B]{A: a, B: b} } // T3 creates a tuple from a list of values. // Play: https://go.dev/play/p/IllL3ZO4BQm -func T3[A any, B any, C any](a A, b B, c C) Tuple3[A, B, C] { +func T3[A, B, C any](a A, b B, c C) Tuple3[A, B, C] { return Tuple3[A, B, C]{A: a, B: b, C: c} } // T4 creates a tuple from a list of values. // Play: https://go.dev/play/p/IllL3ZO4BQm -func T4[A any, B any, C any, D any](a A, b B, c C, d D) Tuple4[A, B, C, D] { +func T4[A, B, C, D any](a A, b B, c C, d D) Tuple4[A, B, C, D] { return Tuple4[A, B, C, D]{A: a, B: b, C: c, D: d} } // T5 creates a tuple from a list of values. // Play: https://go.dev/play/p/IllL3ZO4BQm -func T5[A any, B any, C any, D any, E any](a A, b B, c C, d D, e E) Tuple5[A, B, C, D, E] { +func T5[A, B, C, D, E any](a A, b B, c C, d D, e E) Tuple5[A, B, C, D, E] { return Tuple5[A, B, C, D, E]{A: a, B: b, C: c, D: d, E: e} } // T6 creates a tuple from a list of values. // Play: https://go.dev/play/p/IllL3ZO4BQm -func T6[A any, B any, C any, D any, E any, F any](a A, b B, c C, d D, e E, f F) Tuple6[A, B, C, D, E, F] { +func T6[A, B, C, D, E, F any](a A, b B, c C, d D, e E, f F) Tuple6[A, B, C, D, E, F] { return Tuple6[A, B, C, D, E, F]{A: a, B: b, C: c, D: d, E: e, F: f} } // T7 creates a tuple from a list of values. // Play: https://go.dev/play/p/IllL3ZO4BQm -func T7[A any, B any, C any, D any, E any, F any, G any](a A, b B, c C, d D, e E, f F, g G) Tuple7[A, B, C, D, E, F, G] { +func T7[A, B, C, D, E, F, G any](a A, b B, c C, d D, e E, f F, g G) Tuple7[A, B, C, D, E, F, G] { return Tuple7[A, B, C, D, E, F, G]{A: a, B: b, C: c, D: d, E: e, F: f, G: g} } // T8 creates a tuple from a list of values. // Play: https://go.dev/play/p/IllL3ZO4BQm -func T8[A any, B any, C any, D any, E any, F any, G any, H any](a A, b B, c C, d D, e E, f F, g G, h H) Tuple8[A, B, C, D, E, F, G, H] { +func T8[A, B, C, D, E, F, G, H any](a A, b B, c C, d D, e E, f F, g G, h H) Tuple8[A, B, C, D, E, F, G, H] { return Tuple8[A, B, C, D, E, F, G, H]{A: a, B: b, C: c, D: d, E: e, F: f, G: g, H: h} } // T9 creates a tuple from a list of values. // Play: https://go.dev/play/p/IllL3ZO4BQm -func T9[A any, B any, C any, D any, E any, F any, G any, H any, I any](a A, b B, c C, d D, e E, f F, g G, h H, i I) Tuple9[A, B, C, D, E, F, G, H, I] { +func T9[A, B, C, D, E, F, G, H, I any](a A, b B, c C, d D, e E, f F, g G, h H, i I) Tuple9[A, B, C, D, E, F, G, H, I] { return Tuple9[A, B, C, D, E, F, G, H, I]{A: a, B: b, C: c, D: d, E: e, F: f, G: g, H: h, I: i} } // Unpack2 returns values contained in tuple. // Play: https://go.dev/play/p/xVP_k0kJ96W -func Unpack2[A any, B any](tuple Tuple2[A, B]) (A, B) { +func Unpack2[A, B any](tuple Tuple2[A, B]) (A, B) { return tuple.A, tuple.B } // Unpack3 returns values contained in tuple. // Play: https://go.dev/play/p/xVP_k0kJ96W -func Unpack3[A any, B any, C any](tuple Tuple3[A, B, C]) (A, B, C) { +func Unpack3[A, B, C any](tuple Tuple3[A, B, C]) (A, B, C) { return tuple.A, tuple.B, tuple.C } // Unpack4 returns values contained in tuple. // Play: https://go.dev/play/p/xVP_k0kJ96W -func Unpack4[A any, B any, C any, D any](tuple Tuple4[A, B, C, D]) (A, B, C, D) { +func Unpack4[A, B, C, D any](tuple Tuple4[A, B, C, D]) (A, B, C, D) { return tuple.A, tuple.B, tuple.C, tuple.D } // Unpack5 returns values contained in tuple. // Play: https://go.dev/play/p/xVP_k0kJ96W -func Unpack5[A any, B any, C any, D any, E any](tuple Tuple5[A, B, C, D, E]) (A, B, C, D, E) { +func Unpack5[A, B, C, D, E any](tuple Tuple5[A, B, C, D, E]) (A, B, C, D, E) { return tuple.A, tuple.B, tuple.C, tuple.D, tuple.E } // Unpack6 returns values contained in tuple. // Play: https://go.dev/play/p/xVP_k0kJ96W -func Unpack6[A any, B any, C any, D any, E any, F any](tuple Tuple6[A, B, C, D, E, F]) (A, B, C, D, E, F) { +func Unpack6[A, B, C, D, E, F any](tuple Tuple6[A, B, C, D, E, F]) (A, B, C, D, E, F) { return tuple.A, tuple.B, tuple.C, tuple.D, tuple.E, tuple.F } // Unpack7 returns values contained in tuple. // Play: https://go.dev/play/p/xVP_k0kJ96W -func Unpack7[A any, B any, C any, D any, E any, F any, G any](tuple Tuple7[A, B, C, D, E, F, G]) (A, B, C, D, E, F, G) { +func Unpack7[A, B, C, D, E, F, G any](tuple Tuple7[A, B, C, D, E, F, G]) (A, B, C, D, E, F, G) { return tuple.A, tuple.B, tuple.C, tuple.D, tuple.E, tuple.F, tuple.G } // Unpack8 returns values contained in tuple. // Play: https://go.dev/play/p/xVP_k0kJ96W -func Unpack8[A any, B any, C any, D any, E any, F any, G any, H any](tuple Tuple8[A, B, C, D, E, F, G, H]) (A, B, C, D, E, F, G, H) { +func Unpack8[A, B, C, D, E, F, G, H any](tuple Tuple8[A, B, C, D, E, F, G, H]) (A, B, C, D, E, F, G, H) { return tuple.A, tuple.B, tuple.C, tuple.D, tuple.E, tuple.F, tuple.G, tuple.H } // Unpack9 returns values contained in tuple. // Play: https://go.dev/play/p/xVP_k0kJ96W -func Unpack9[A any, B any, C any, D any, E any, F any, G any, H any, I any](tuple Tuple9[A, B, C, D, E, F, G, H, I]) (A, B, C, D, E, F, G, H, I) { +func Unpack9[A, B, C, D, E, F, G, H, I any](tuple Tuple9[A, B, C, D, E, F, G, H, I]) (A, B, C, D, E, F, G, H, I) { return tuple.A, tuple.B, tuple.C, tuple.D, tuple.E, tuple.F, tuple.G, tuple.H, tuple.I } @@ -100,7 +100,7 @@ func Unpack9[A any, B any, C any, D any, E any, F any, G any, H any, I any](tupl // of the given arrays, the second of which contains the second elements of the given arrays, and so on. // When collections have different size, the Tuple attributes are filled with zero value. // Play: https://go.dev/play/p/jujaA6GaJTp -func Zip2[A any, B any](a []A, b []B) []Tuple2[A, B] { +func Zip2[A, B any](a []A, b []B) []Tuple2[A, B] { size := Max([]int{len(a), len(b)}) result := make([]Tuple2[A, B], 0, size) @@ -122,7 +122,7 @@ func Zip2[A any, B any](a []A, b []B) []Tuple2[A, B] { // of the given arrays, the second of which contains the second elements of the given arrays, and so on. // When collections have different size, the Tuple attributes are filled with zero value. // Play: https://go.dev/play/p/jujaA6GaJTp -func Zip3[A any, B any, C any](a []A, b []B, c []C) []Tuple3[A, B, C] { +func Zip3[A, B, C any](a []A, b []B, c []C) []Tuple3[A, B, C] { size := Max([]int{len(a), len(b), len(c)}) result := make([]Tuple3[A, B, C], 0, size) @@ -146,7 +146,7 @@ func Zip3[A any, B any, C any](a []A, b []B, c []C) []Tuple3[A, B, C] { // of the given arrays, the second of which contains the second elements of the given arrays, and so on. // When collections have different size, the Tuple attributes are filled with zero value. // Play: https://go.dev/play/p/jujaA6GaJTp -func Zip4[A any, B any, C any, D any](a []A, b []B, c []C, d []D) []Tuple4[A, B, C, D] { +func Zip4[A, B, C, D any](a []A, b []B, c []C, d []D) []Tuple4[A, B, C, D] { size := Max([]int{len(a), len(b), len(c), len(d)}) result := make([]Tuple4[A, B, C, D], 0, size) @@ -172,7 +172,7 @@ func Zip4[A any, B any, C any, D any](a []A, b []B, c []C, d []D) []Tuple4[A, B, // of the given arrays, the second of which contains the second elements of the given arrays, and so on. // When collections have different size, the Tuple attributes are filled with zero value. // Play: https://go.dev/play/p/jujaA6GaJTp -func Zip5[A any, B any, C any, D any, E any](a []A, b []B, c []C, d []D, e []E) []Tuple5[A, B, C, D, E] { +func Zip5[A, B, C, D, E any](a []A, b []B, c []C, d []D, e []E) []Tuple5[A, B, C, D, E] { size := Max([]int{len(a), len(b), len(c), len(d), len(e)}) result := make([]Tuple5[A, B, C, D, E], 0, size) @@ -200,7 +200,7 @@ func Zip5[A any, B any, C any, D any, E any](a []A, b []B, c []C, d []D, e []E) // of the given arrays, the second of which contains the second elements of the given arrays, and so on. // When collections have different size, the Tuple attributes are filled with zero value. // Play: https://go.dev/play/p/jujaA6GaJTp -func Zip6[A any, B any, C any, D any, E any, F any](a []A, b []B, c []C, d []D, e []E, f []F) []Tuple6[A, B, C, D, E, F] { +func Zip6[A, B, C, D, E, F any](a []A, b []B, c []C, d []D, e []E, f []F) []Tuple6[A, B, C, D, E, F] { size := Max([]int{len(a), len(b), len(c), len(d), len(e), len(f)}) result := make([]Tuple6[A, B, C, D, E, F], 0, size) @@ -230,7 +230,7 @@ func Zip6[A any, B any, C any, D any, E any, F any](a []A, b []B, c []C, d []D, // of the given arrays, the second of which contains the second elements of the given arrays, and so on. // When collections have different size, the Tuple attributes are filled with zero value. // Play: https://go.dev/play/p/jujaA6GaJTp -func Zip7[A any, B any, C any, D any, E any, F any, G any](a []A, b []B, c []C, d []D, e []E, f []F, g []G) []Tuple7[A, B, C, D, E, F, G] { +func Zip7[A, B, C, D, E, F, G any](a []A, b []B, c []C, d []D, e []E, f []F, g []G) []Tuple7[A, B, C, D, E, F, G] { size := Max([]int{len(a), len(b), len(c), len(d), len(e), len(f), len(g)}) result := make([]Tuple7[A, B, C, D, E, F, G], 0, size) @@ -262,7 +262,7 @@ func Zip7[A any, B any, C any, D any, E any, F any, G any](a []A, b []B, c []C, // of the given arrays, the second of which contains the second elements of the given arrays, and so on. // When collections have different size, the Tuple attributes are filled with zero value. // Play: https://go.dev/play/p/jujaA6GaJTp -func Zip8[A any, B any, C any, D any, E any, F any, G any, H any](a []A, b []B, c []C, d []D, e []E, f []F, g []G, h []H) []Tuple8[A, B, C, D, E, F, G, H] { +func Zip8[A, B, C, D, E, F, G, H any](a []A, b []B, c []C, d []D, e []E, f []F, g []G, h []H) []Tuple8[A, B, C, D, E, F, G, H] { size := Max([]int{len(a), len(b), len(c), len(d), len(e), len(f), len(g), len(h)}) result := make([]Tuple8[A, B, C, D, E, F, G, H], 0, size) @@ -296,7 +296,7 @@ func Zip8[A any, B any, C any, D any, E any, F any, G any, H any](a []A, b []B, // of the given arrays, the second of which contains the second elements of the given arrays, and so on. // When collections have different size, the Tuple attributes are filled with zero value. // Play: https://go.dev/play/p/jujaA6GaJTp -func Zip9[A any, B any, C any, D any, E any, F any, G any, H any, I any](a []A, b []B, c []C, d []D, e []E, f []F, g []G, h []H, i []I) []Tuple9[A, B, C, D, E, F, G, H, I] { +func Zip9[A, B, C, D, E, F, G, H, I any](a []A, b []B, c []C, d []D, e []E, f []F, g []G, h []H, i []I) []Tuple9[A, B, C, D, E, F, G, H, I] { size := Max([]int{len(a), len(b), len(c), len(d), len(e), len(f), len(g), len(h), len(i)}) result := make([]Tuple9[A, B, C, D, E, F, G, H, I], 0, size) @@ -328,17 +328,189 @@ func Zip9[A any, B any, C any, D any, E any, F any, G any, H any, I any](a []A, return result } +// ZipBy2 creates a slice of transformed elements, the first of which contains the first elements +// of the given arrays, the second of which contains the second elements of the given arrays, and so on. +// When collections have different size, the Tuple attributes are filled with zero value. +func ZipBy2[A any, B any, Out any](a []A, b []B, iteratee func(a A, b B) Out) []Out { + size := Max([]int{len(a), len(b)}) + + result := make([]Out, 0, size) + + for index := 0; index < size; index++ { + _a, _ := Nth(a, index) + _b, _ := Nth(b, index) + + result = append(result, iteratee(_a, _b)) + } + + return result +} + +// ZipBy3 creates a slice of transformed elements, the first of which contains the first elements +// of the given arrays, the second of which contains the second elements of the given arrays, and so on. +// When collections have different size, the Tuple attributes are filled with zero value. +func ZipBy3[A any, B any, C any, Out any](a []A, b []B, c []C, iteratee func(a A, b B, c C) Out) []Out { + size := Max([]int{len(a), len(b), len(c)}) + + result := make([]Out, 0, size) + + for index := 0; index < size; index++ { + _a, _ := Nth(a, index) + _b, _ := Nth(b, index) + _c, _ := Nth(c, index) + + result = append(result, iteratee(_a, _b, _c)) + } + + return result +} + +// ZipBy4 creates a slice of transformed elements, the first of which contains the first elements +// of the given arrays, the second of which contains the second elements of the given arrays, and so on. +// When collections have different size, the Tuple attributes are filled with zero value. +func ZipBy4[A any, B any, C any, D any, Out any](a []A, b []B, c []C, d []D, iteratee func(a A, b B, c C, d D) Out) []Out { + size := Max([]int{len(a), len(b), len(c), len(d)}) + + result := make([]Out, 0, size) + + for index := 0; index < size; index++ { + _a, _ := Nth(a, index) + _b, _ := Nth(b, index) + _c, _ := Nth(c, index) + _d, _ := Nth(d, index) + + result = append(result, iteratee(_a, _b, _c, _d)) + } + + return result +} + +// ZipBy5 creates a slice of transformed elements, the first of which contains the first elements +// of the given arrays, the second of which contains the second elements of the given arrays, and so on. +// When collections have different size, the Tuple attributes are filled with zero value. +func ZipBy5[A any, B any, C any, D any, E any, Out any](a []A, b []B, c []C, d []D, e []E, iteratee func(a A, b B, c C, d D, e E) Out) []Out { + size := Max([]int{len(a), len(b), len(c), len(d), len(e)}) + + result := make([]Out, 0, size) + + for index := 0; index < size; index++ { + _a, _ := Nth(a, index) + _b, _ := Nth(b, index) + _c, _ := Nth(c, index) + _d, _ := Nth(d, index) + _e, _ := Nth(e, index) + + result = append(result, iteratee(_a, _b, _c, _d, _e)) + } + + return result +} + +// ZipBy6 creates a slice of transformed elements, the first of which contains the first elements +// of the given arrays, the second of which contains the second elements of the given arrays, and so on. +// When collections have different size, the Tuple attributes are filled with zero value. +func ZipBy6[A any, B any, C any, D any, E any, F any, Out any](a []A, b []B, c []C, d []D, e []E, f []F, iteratee func(a A, b B, c C, d D, e E, f F) Out) []Out { + size := Max([]int{len(a), len(b), len(c), len(d), len(e), len(f)}) + + result := make([]Out, 0, size) + + for index := 0; index < size; index++ { + _a, _ := Nth(a, index) + _b, _ := Nth(b, index) + _c, _ := Nth(c, index) + _d, _ := Nth(d, index) + _e, _ := Nth(e, index) + _f, _ := Nth(f, index) + + result = append(result, iteratee(_a, _b, _c, _d, _e, _f)) + } + + return result +} + +// ZipBy7 creates a slice of transformed elements, the first of which contains the first elements +// of the given arrays, the second of which contains the second elements of the given arrays, and so on. +// When collections have different size, the Tuple attributes are filled with zero value. +func ZipBy7[A any, B any, C any, D any, E any, F any, G any, Out any](a []A, b []B, c []C, d []D, e []E, f []F, g []G, iteratee func(a A, b B, c C, d D, e E, f F, g G) Out) []Out { + size := Max([]int{len(a), len(b), len(c), len(d), len(e), len(f)}) + + result := make([]Out, 0, size) + + for index := 0; index < size; index++ { + _a, _ := Nth(a, index) + _b, _ := Nth(b, index) + _c, _ := Nth(c, index) + _d, _ := Nth(d, index) + _e, _ := Nth(e, index) + _f, _ := Nth(f, index) + _g, _ := Nth(g, index) + + result = append(result, iteratee(_a, _b, _c, _d, _e, _f, _g)) + } + + return result +} + +// ZipBy8 creates a slice of transformed elements, the first of which contains the first elements +// of the given arrays, the second of which contains the second elements of the given arrays, and so on. +// When collections have different size, the Tuple attributes are filled with zero value. +func ZipBy8[A any, B any, C any, D any, E any, F any, G any, H any, Out any](a []A, b []B, c []C, d []D, e []E, f []F, g []G, h []H, iteratee func(a A, b B, c C, d D, e E, f F, g G, h H) Out) []Out { + size := Max([]int{len(a), len(b), len(c), len(d), len(e), len(f), len(g)}) + + result := make([]Out, 0, size) + + for index := 0; index < size; index++ { + _a, _ := Nth(a, index) + _b, _ := Nth(b, index) + _c, _ := Nth(c, index) + _d, _ := Nth(d, index) + _e, _ := Nth(e, index) + _f, _ := Nth(f, index) + _g, _ := Nth(g, index) + _h, _ := Nth(h, index) + + result = append(result, iteratee(_a, _b, _c, _d, _e, _f, _g, _h)) + } + + return result +} + +// ZipBy9 creates a slice of transformed elements, the first of which contains the first elements +// of the given arrays, the second of which contains the second elements of the given arrays, and so on. +// When collections have different size, the Tuple attributes are filled with zero value. +func ZipBy9[A any, B any, C any, D any, E any, F any, G any, H any, I any, Out any](a []A, b []B, c []C, d []D, e []E, f []F, g []G, h []H, i []I, iteratee func(a A, b B, c C, d D, e E, f F, g G, h H, i I) Out) []Out { + size := Max([]int{len(a), len(b), len(c), len(d), len(e), len(f), len(g), len(h), len(i)}) + + result := make([]Out, 0, size) + + for index := 0; index < size; index++ { + _a, _ := Nth(a, index) + _b, _ := Nth(b, index) + _c, _ := Nth(c, index) + _d, _ := Nth(d, index) + _e, _ := Nth(e, index) + _f, _ := Nth(f, index) + _g, _ := Nth(g, index) + _h, _ := Nth(h, index) + _i, _ := Nth(i, index) + + result = append(result, iteratee(_a, _b, _c, _d, _e, _f, _g, _h, _i)) + } + + return result +} + // Unzip2 accepts an array of grouped elements and creates an array regrouping the elements // to their pre-zip configuration. // Play: https://go.dev/play/p/ciHugugvaAW -func Unzip2[A any, B any](tuples []Tuple2[A, B]) ([]A, []B) { +func Unzip2[A, B any](tuples []Tuple2[A, B]) ([]A, []B) { size := len(tuples) r1 := make([]A, 0, size) r2 := make([]B, 0, size) - for _, tuple := range tuples { - r1 = append(r1, tuple.A) - r2 = append(r2, tuple.B) + for i := range tuples { + r1 = append(r1, tuples[i].A) + r2 = append(r2, tuples[i].B) } return r1, r2 @@ -347,16 +519,16 @@ func Unzip2[A any, B any](tuples []Tuple2[A, B]) ([]A, []B) { // Unzip3 accepts an array of grouped elements and creates an array regrouping the elements // to their pre-zip configuration. // Play: https://go.dev/play/p/ciHugugvaAW -func Unzip3[A any, B any, C any](tuples []Tuple3[A, B, C]) ([]A, []B, []C) { +func Unzip3[A, B, C any](tuples []Tuple3[A, B, C]) ([]A, []B, []C) { size := len(tuples) r1 := make([]A, 0, size) r2 := make([]B, 0, size) r3 := make([]C, 0, size) - for _, tuple := range tuples { - r1 = append(r1, tuple.A) - r2 = append(r2, tuple.B) - r3 = append(r3, tuple.C) + for i := range tuples { + r1 = append(r1, tuples[i].A) + r2 = append(r2, tuples[i].B) + r3 = append(r3, tuples[i].C) } return r1, r2, r3 @@ -365,18 +537,18 @@ func Unzip3[A any, B any, C any](tuples []Tuple3[A, B, C]) ([]A, []B, []C) { // Unzip4 accepts an array of grouped elements and creates an array regrouping the elements // to their pre-zip configuration. // Play: https://go.dev/play/p/ciHugugvaAW -func Unzip4[A any, B any, C any, D any](tuples []Tuple4[A, B, C, D]) ([]A, []B, []C, []D) { +func Unzip4[A, B, C, D any](tuples []Tuple4[A, B, C, D]) ([]A, []B, []C, []D) { size := len(tuples) r1 := make([]A, 0, size) r2 := make([]B, 0, size) r3 := make([]C, 0, size) r4 := make([]D, 0, size) - for _, tuple := range tuples { - r1 = append(r1, tuple.A) - r2 = append(r2, tuple.B) - r3 = append(r3, tuple.C) - r4 = append(r4, tuple.D) + for i := range tuples { + r1 = append(r1, tuples[i].A) + r2 = append(r2, tuples[i].B) + r3 = append(r3, tuples[i].C) + r4 = append(r4, tuples[i].D) } return r1, r2, r3, r4 @@ -385,7 +557,7 @@ func Unzip4[A any, B any, C any, D any](tuples []Tuple4[A, B, C, D]) ([]A, []B, // Unzip5 accepts an array of grouped elements and creates an array regrouping the elements // to their pre-zip configuration. // Play: https://go.dev/play/p/ciHugugvaAW -func Unzip5[A any, B any, C any, D any, E any](tuples []Tuple5[A, B, C, D, E]) ([]A, []B, []C, []D, []E) { +func Unzip5[A, B, C, D, E any](tuples []Tuple5[A, B, C, D, E]) ([]A, []B, []C, []D, []E) { size := len(tuples) r1 := make([]A, 0, size) r2 := make([]B, 0, size) @@ -393,12 +565,12 @@ func Unzip5[A any, B any, C any, D any, E any](tuples []Tuple5[A, B, C, D, E]) ( r4 := make([]D, 0, size) r5 := make([]E, 0, size) - for _, tuple := range tuples { - r1 = append(r1, tuple.A) - r2 = append(r2, tuple.B) - r3 = append(r3, tuple.C) - r4 = append(r4, tuple.D) - r5 = append(r5, tuple.E) + for i := range tuples { + r1 = append(r1, tuples[i].A) + r2 = append(r2, tuples[i].B) + r3 = append(r3, tuples[i].C) + r4 = append(r4, tuples[i].D) + r5 = append(r5, tuples[i].E) } return r1, r2, r3, r4, r5 @@ -407,7 +579,7 @@ func Unzip5[A any, B any, C any, D any, E any](tuples []Tuple5[A, B, C, D, E]) ( // Unzip6 accepts an array of grouped elements and creates an array regrouping the elements // to their pre-zip configuration. // Play: https://go.dev/play/p/ciHugugvaAW -func Unzip6[A any, B any, C any, D any, E any, F any](tuples []Tuple6[A, B, C, D, E, F]) ([]A, []B, []C, []D, []E, []F) { +func Unzip6[A, B, C, D, E, F any](tuples []Tuple6[A, B, C, D, E, F]) ([]A, []B, []C, []D, []E, []F) { size := len(tuples) r1 := make([]A, 0, size) r2 := make([]B, 0, size) @@ -416,13 +588,13 @@ func Unzip6[A any, B any, C any, D any, E any, F any](tuples []Tuple6[A, B, C, D r5 := make([]E, 0, size) r6 := make([]F, 0, size) - for _, tuple := range tuples { - r1 = append(r1, tuple.A) - r2 = append(r2, tuple.B) - r3 = append(r3, tuple.C) - r4 = append(r4, tuple.D) - r5 = append(r5, tuple.E) - r6 = append(r6, tuple.F) + for i := range tuples { + r1 = append(r1, tuples[i].A) + r2 = append(r2, tuples[i].B) + r3 = append(r3, tuples[i].C) + r4 = append(r4, tuples[i].D) + r5 = append(r5, tuples[i].E) + r6 = append(r6, tuples[i].F) } return r1, r2, r3, r4, r5, r6 @@ -431,7 +603,7 @@ func Unzip6[A any, B any, C any, D any, E any, F any](tuples []Tuple6[A, B, C, D // Unzip7 accepts an array of grouped elements and creates an array regrouping the elements // to their pre-zip configuration. // Play: https://go.dev/play/p/ciHugugvaAW -func Unzip7[A any, B any, C any, D any, E any, F any, G any](tuples []Tuple7[A, B, C, D, E, F, G]) ([]A, []B, []C, []D, []E, []F, []G) { +func Unzip7[A, B, C, D, E, F, G any](tuples []Tuple7[A, B, C, D, E, F, G]) ([]A, []B, []C, []D, []E, []F, []G) { size := len(tuples) r1 := make([]A, 0, size) r2 := make([]B, 0, size) @@ -441,14 +613,14 @@ func Unzip7[A any, B any, C any, D any, E any, F any, G any](tuples []Tuple7[A, r6 := make([]F, 0, size) r7 := make([]G, 0, size) - for _, tuple := range tuples { - r1 = append(r1, tuple.A) - r2 = append(r2, tuple.B) - r3 = append(r3, tuple.C) - r4 = append(r4, tuple.D) - r5 = append(r5, tuple.E) - r6 = append(r6, tuple.F) - r7 = append(r7, tuple.G) + for i := range tuples { + r1 = append(r1, tuples[i].A) + r2 = append(r2, tuples[i].B) + r3 = append(r3, tuples[i].C) + r4 = append(r4, tuples[i].D) + r5 = append(r5, tuples[i].E) + r6 = append(r6, tuples[i].F) + r7 = append(r7, tuples[i].G) } return r1, r2, r3, r4, r5, r6, r7 @@ -457,7 +629,7 @@ func Unzip7[A any, B any, C any, D any, E any, F any, G any](tuples []Tuple7[A, // Unzip8 accepts an array of grouped elements and creates an array regrouping the elements // to their pre-zip configuration. // Play: https://go.dev/play/p/ciHugugvaAW -func Unzip8[A any, B any, C any, D any, E any, F any, G any, H any](tuples []Tuple8[A, B, C, D, E, F, G, H]) ([]A, []B, []C, []D, []E, []F, []G, []H) { +func Unzip8[A, B, C, D, E, F, G, H any](tuples []Tuple8[A, B, C, D, E, F, G, H]) ([]A, []B, []C, []D, []E, []F, []G, []H) { size := len(tuples) r1 := make([]A, 0, size) r2 := make([]B, 0, size) @@ -468,15 +640,15 @@ func Unzip8[A any, B any, C any, D any, E any, F any, G any, H any](tuples []Tup r7 := make([]G, 0, size) r8 := make([]H, 0, size) - for _, tuple := range tuples { - r1 = append(r1, tuple.A) - r2 = append(r2, tuple.B) - r3 = append(r3, tuple.C) - r4 = append(r4, tuple.D) - r5 = append(r5, tuple.E) - r6 = append(r6, tuple.F) - r7 = append(r7, tuple.G) - r8 = append(r8, tuple.H) + for i := range tuples { + r1 = append(r1, tuples[i].A) + r2 = append(r2, tuples[i].B) + r3 = append(r3, tuples[i].C) + r4 = append(r4, tuples[i].D) + r5 = append(r5, tuples[i].E) + r6 = append(r6, tuples[i].F) + r7 = append(r7, tuples[i].G) + r8 = append(r8, tuples[i].H) } return r1, r2, r3, r4, r5, r6, r7, r8 @@ -485,7 +657,7 @@ func Unzip8[A any, B any, C any, D any, E any, F any, G any, H any](tuples []Tup // Unzip9 accepts an array of grouped elements and creates an array regrouping the elements // to their pre-zip configuration. // Play: https://go.dev/play/p/ciHugugvaAW -func Unzip9[A any, B any, C any, D any, E any, F any, G any, H any, I any](tuples []Tuple9[A, B, C, D, E, F, G, H, I]) ([]A, []B, []C, []D, []E, []F, []G, []H, []I) { +func Unzip9[A, B, C, D, E, F, G, H, I any](tuples []Tuple9[A, B, C, D, E, F, G, H, I]) ([]A, []B, []C, []D, []E, []F, []G, []H, []I) { size := len(tuples) r1 := make([]A, 0, size) r2 := make([]B, 0, size) @@ -497,16 +669,200 @@ func Unzip9[A any, B any, C any, D any, E any, F any, G any, H any, I any](tuple r8 := make([]H, 0, size) r9 := make([]I, 0, size) - for _, tuple := range tuples { - r1 = append(r1, tuple.A) - r2 = append(r2, tuple.B) - r3 = append(r3, tuple.C) - r4 = append(r4, tuple.D) - r5 = append(r5, tuple.E) - r6 = append(r6, tuple.F) - r7 = append(r7, tuple.G) - r8 = append(r8, tuple.H) - r9 = append(r9, tuple.I) + for i := range tuples { + r1 = append(r1, tuples[i].A) + r2 = append(r2, tuples[i].B) + r3 = append(r3, tuples[i].C) + r4 = append(r4, tuples[i].D) + r5 = append(r5, tuples[i].E) + r6 = append(r6, tuples[i].F) + r7 = append(r7, tuples[i].G) + r8 = append(r8, tuples[i].H) + r9 = append(r9, tuples[i].I) + } + + return r1, r2, r3, r4, r5, r6, r7, r8, r9 +} + +// UnzipBy2 iterates over a collection and creates an array regrouping the elements +// to their pre-zip configuration. +func UnzipBy2[In any, A any, B any](items []In, iteratee func(In) (a A, b B)) ([]A, []B) { + size := len(items) + r1 := make([]A, 0, size) + r2 := make([]B, 0, size) + + for i := range items { + a, b := iteratee(items[i]) + r1 = append(r1, a) + r2 = append(r2, b) + } + + return r1, r2 +} + +// UnzipBy3 iterates over a collection and creates an array regrouping the elements +// to their pre-zip configuration. +func UnzipBy3[In any, A any, B any, C any](items []In, iteratee func(In) (a A, b B, c C)) ([]A, []B, []C) { + size := len(items) + r1 := make([]A, 0, size) + r2 := make([]B, 0, size) + r3 := make([]C, 0, size) + + for i := range items { + a, b, c := iteratee(items[i]) + r1 = append(r1, a) + r2 = append(r2, b) + r3 = append(r3, c) + } + + return r1, r2, r3 +} + +// UnzipBy4 iterates over a collection and creates an array regrouping the elements +// to their pre-zip configuration. +func UnzipBy4[In any, A any, B any, C any, D any](items []In, iteratee func(In) (a A, b B, c C, d D)) ([]A, []B, []C, []D) { + size := len(items) + r1 := make([]A, 0, size) + r2 := make([]B, 0, size) + r3 := make([]C, 0, size) + r4 := make([]D, 0, size) + + for i := range items { + a, b, c, d := iteratee(items[i]) + r1 = append(r1, a) + r2 = append(r2, b) + r3 = append(r3, c) + r4 = append(r4, d) + } + + return r1, r2, r3, r4 +} + +// UnzipBy5 iterates over a collection and creates an array regrouping the elements +// to their pre-zip configuration. +func UnzipBy5[In any, A any, B any, C any, D any, E any](items []In, iteratee func(In) (a A, b B, c C, d D, e E)) ([]A, []B, []C, []D, []E) { + size := len(items) + r1 := make([]A, 0, size) + r2 := make([]B, 0, size) + r3 := make([]C, 0, size) + r4 := make([]D, 0, size) + r5 := make([]E, 0, size) + + for i := range items { + a, b, c, d, e := iteratee(items[i]) + r1 = append(r1, a) + r2 = append(r2, b) + r3 = append(r3, c) + r4 = append(r4, d) + r5 = append(r5, e) + } + + return r1, r2, r3, r4, r5 +} + +// UnzipBy6 iterates over a collection and creates an array regrouping the elements +// to their pre-zip configuration. +func UnzipBy6[In any, A any, B any, C any, D any, E any, F any](items []In, iteratee func(In) (a A, b B, c C, d D, e E, f F)) ([]A, []B, []C, []D, []E, []F) { + size := len(items) + r1 := make([]A, 0, size) + r2 := make([]B, 0, size) + r3 := make([]C, 0, size) + r4 := make([]D, 0, size) + r5 := make([]E, 0, size) + r6 := make([]F, 0, size) + + for i := range items { + a, b, c, d, e, f := iteratee(items[i]) + r1 = append(r1, a) + r2 = append(r2, b) + r3 = append(r3, c) + r4 = append(r4, d) + r5 = append(r5, e) + r6 = append(r6, f) + } + + return r1, r2, r3, r4, r5, r6 +} + +// UnzipBy7 iterates over a collection and creates an array regrouping the elements +// to their pre-zip configuration. +func UnzipBy7[In any, A any, B any, C any, D any, E any, F any, G any](items []In, iteratee func(In) (a A, b B, c C, d D, e E, f F, g G)) ([]A, []B, []C, []D, []E, []F, []G) { + size := len(items) + r1 := make([]A, 0, size) + r2 := make([]B, 0, size) + r3 := make([]C, 0, size) + r4 := make([]D, 0, size) + r5 := make([]E, 0, size) + r6 := make([]F, 0, size) + r7 := make([]G, 0, size) + + for i := range items { + a, b, c, d, e, f, g := iteratee(items[i]) + r1 = append(r1, a) + r2 = append(r2, b) + r3 = append(r3, c) + r4 = append(r4, d) + r5 = append(r5, e) + r6 = append(r6, f) + r7 = append(r7, g) + } + + return r1, r2, r3, r4, r5, r6, r7 +} + +// UnzipBy8 iterates over a collection and creates an array regrouping the elements +// to their pre-zip configuration. +func UnzipBy8[In any, A any, B any, C any, D any, E any, F any, G any, H any](items []In, iteratee func(In) (a A, b B, c C, d D, e E, f F, g G, h H)) ([]A, []B, []C, []D, []E, []F, []G, []H) { + size := len(items) + r1 := make([]A, 0, size) + r2 := make([]B, 0, size) + r3 := make([]C, 0, size) + r4 := make([]D, 0, size) + r5 := make([]E, 0, size) + r6 := make([]F, 0, size) + r7 := make([]G, 0, size) + r8 := make([]H, 0, size) + + for i := range items { + a, b, c, d, e, f, g, h := iteratee(items[i]) + r1 = append(r1, a) + r2 = append(r2, b) + r3 = append(r3, c) + r4 = append(r4, d) + r5 = append(r5, e) + r6 = append(r6, f) + r7 = append(r7, g) + r8 = append(r8, h) + } + + return r1, r2, r3, r4, r5, r6, r7, r8 +} + +// UnzipBy9 iterates over a collection and creates an array regrouping the elements +// to their pre-zip configuration. +func UnzipBy9[In any, A any, B any, C any, D any, E any, F any, G any, H any, I any](items []In, iteratee func(In) (a A, b B, c C, d D, e E, f F, g G, h H, i I)) ([]A, []B, []C, []D, []E, []F, []G, []H, []I) { + size := len(items) + r1 := make([]A, 0, size) + r2 := make([]B, 0, size) + r3 := make([]C, 0, size) + r4 := make([]D, 0, size) + r5 := make([]E, 0, size) + r6 := make([]F, 0, size) + r7 := make([]G, 0, size) + r8 := make([]H, 0, size) + r9 := make([]I, 0, size) + + for i := range items { + a, b, c, d, e, f, g, h, i := iteratee(items[i]) + r1 = append(r1, a) + r2 = append(r2, b) + r3 = append(r3, c) + r4 = append(r4, d) + r5 = append(r5, e) + r6 = append(r6, f) + r7 = append(r7, g) + r8 = append(r8, h) + r9 = append(r9, i) } return r1, r2, r3, r4, r5, r6, r7, r8, r9 diff --git a/vendor/github.com/samber/lo/type_manipulation.go b/vendor/github.com/samber/lo/type_manipulation.go index 45d8fe2037..ef070281aa 100644 --- a/vendor/github.com/samber/lo/type_manipulation.go +++ b/vendor/github.com/samber/lo/type_manipulation.go @@ -2,11 +2,22 @@ package lo import "reflect" +// IsNil checks if a value is nil or if it's a reference type with a nil underlying value. +func IsNil(x any) bool { + defer func() { recover() }() // nolint:errcheck + return x == nil || reflect.ValueOf(x).IsNil() +} + // ToPtr returns a pointer copy of value. func ToPtr[T any](x T) *T { return &x } +// Nil returns a nil pointer of type. +func Nil[T any]() *T { + return nil +} + // EmptyableToPtr returns a pointer copy of value if it's nonzero. // Otherwise, returns nil pointer. func EmptyableToPtr[T any](x T) *T { @@ -39,16 +50,40 @@ func FromPtrOr[T any](x *T, fallback T) T { // ToSlicePtr returns a slice of pointer copy of value. func ToSlicePtr[T any](collection []T) []*T { - return Map(collection, func(x T, _ int) *T { - return &x + result := make([]*T, len(collection)) + + for i := range collection { + result[i] = &collection[i] + } + return result +} + +// FromSlicePtr returns a slice with the pointer values. +// Returns a zero value in case of a nil pointer element. +func FromSlicePtr[T any](collection []*T) []T { + return Map(collection, func(x *T, _ int) T { + if x == nil { + return Empty[T]() + } + return *x + }) +} + +// FromSlicePtr returns a slice with the pointer values or the fallback value. +func FromSlicePtrOr[T any](collection []*T, fallback T) []T { + return Map(collection, func(x *T, _ int) T { + if x == nil { + return fallback + } + return *x }) } // ToAnySlice returns a slice with all elements mapped to `any` type func ToAnySlice[T any](collection []T) []any { result := make([]any, len(collection)) - for i, item := range collection { - result[i] = item + for i := range collection { + result[i] = collection[i] } return result } @@ -64,8 +99,8 @@ func FromAnySlice[T any](in []any) (out []T, ok bool) { }() result := make([]T, len(in)) - for i, item := range in { - result[i] = item.(T) + for i := range in { + result[i] = in[i].(T) } return result, true } @@ -89,10 +124,10 @@ func IsNotEmpty[T comparable](v T) bool { } // Coalesce returns the first non-empty arguments. Arguments must be comparable. -func Coalesce[T comparable](v ...T) (result T, ok bool) { - for _, e := range v { - if e != result { - result = e +func Coalesce[T comparable](values ...T) (result T, ok bool) { + for i := range values { + if values[i] != result { + result = values[i] ok = true return } @@ -100,3 +135,9 @@ func Coalesce[T comparable](v ...T) (result T, ok bool) { return } + +// CoalesceOrEmpty returns the first non-empty arguments. Arguments must be comparable. +func CoalesceOrEmpty[T comparable](v ...T) T { + result, _ := Coalesce(v...) + return result +} diff --git a/vendor/github.com/samber/lo/types.go b/vendor/github.com/samber/lo/types.go index 271c5b4fdf..1c6f0d0057 100644 --- a/vendor/github.com/samber/lo/types.go +++ b/vendor/github.com/samber/lo/types.go @@ -7,7 +7,7 @@ type Entry[K comparable, V any] struct { } // Tuple2 is a group of 2 elements (pair). -type Tuple2[A any, B any] struct { +type Tuple2[A, B any] struct { A A B B } @@ -18,7 +18,7 @@ func (t Tuple2[A, B]) Unpack() (A, B) { } // Tuple3 is a group of 3 elements. -type Tuple3[A any, B any, C any] struct { +type Tuple3[A, B, C any] struct { A A B B C C @@ -30,7 +30,7 @@ func (t Tuple3[A, B, C]) Unpack() (A, B, C) { } // Tuple4 is a group of 4 elements. -type Tuple4[A any, B any, C any, D any] struct { +type Tuple4[A, B, C, D any] struct { A A B B C C @@ -43,7 +43,7 @@ func (t Tuple4[A, B, C, D]) Unpack() (A, B, C, D) { } // Tuple5 is a group of 5 elements. -type Tuple5[A any, B any, C any, D any, E any] struct { +type Tuple5[A, B, C, D, E any] struct { A A B B C C @@ -57,7 +57,7 @@ func (t Tuple5[A, B, C, D, E]) Unpack() (A, B, C, D, E) { } // Tuple6 is a group of 6 elements. -type Tuple6[A any, B any, C any, D any, E any, F any] struct { +type Tuple6[A, B, C, D, E, F any] struct { A A B B C C @@ -72,7 +72,7 @@ func (t Tuple6[A, B, C, D, E, F]) Unpack() (A, B, C, D, E, F) { } // Tuple7 is a group of 7 elements. -type Tuple7[A any, B any, C any, D any, E any, F any, G any] struct { +type Tuple7[A, B, C, D, E, F, G any] struct { A A B B C C @@ -88,7 +88,7 @@ func (t Tuple7[A, B, C, D, E, F, G]) Unpack() (A, B, C, D, E, F, G) { } // Tuple8 is a group of 8 elements. -type Tuple8[A any, B any, C any, D any, E any, F any, G any, H any] struct { +type Tuple8[A, B, C, D, E, F, G, H any] struct { A A B B C C @@ -105,7 +105,7 @@ func (t Tuple8[A, B, C, D, E, F, G, H]) Unpack() (A, B, C, D, E, F, G, H) { } // Tuple9 is a group of 9 elements. -type Tuple9[A any, B any, C any, D any, E any, F any, G any, H any, I any] struct { +type Tuple9[A, B, C, D, E, F, G, H, I any] struct { A A B B C C diff --git a/vendor/modules.txt b/vendor/modules.txt index f51ac7e57d..91b752c9b1 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -445,9 +445,11 @@ github.com/prometheus/common/model github.com/prometheus/procfs github.com/prometheus/procfs/internal/fs github.com/prometheus/procfs/internal/util -# github.com/samber/lo v1.38.1 +# github.com/samber/lo v1.47.0 ## explicit; go 1.18 github.com/samber/lo +github.com/samber/lo/internal/constraints +github.com/samber/lo/internal/rand # github.com/shopspring/decimal v1.3.1 ## explicit; go 1.13 github.com/shopspring/decimal