Repository: kubernetes-sigs/cloud-provider-azure
Pull request #3811 (2023-04-23 09:53:08)

feat: add PickRandomMatchingAccount in account search
<!--  Thanks for sending a pull request!  Here are some tips for you:

1. If this is your first time, please read our contributor guidelines: https://git.k8s.io/community/contributors/guide/first-contribution.md#your-first-contribution and developer guide https://git.k8s.io/community/contributors/devel/development.md#development-guide
2. Please label this pull request according to what type of issue you are addressing, especially if this is a release targeted pull request. For reference on required PR/issue labels, read here:
https://git.k8s.io/community/contributors/devel/sig-release/release.md#issuepr-kind-label
3. Ensure you have added or ran the appropriate tests for your PR: https://git.k8s.io/community/contributors/devel/sig-testing/testing.md
4. If you want *faster* PR reviews, read how: https://git.k8s.io/community/contributors/guide/pull-requests.md#best-practices-for-faster-reviews
5. If the PR is unfinished, see how to mark it: https://git.k8s.io/community/contributors/guide/pull-requests.md#marking-unfinished-pull-requests
-->

#### What type of PR is this?
/kind feature

#### What this PR does / why we need it:
This PR:
 - add PickRandomMatchingAccount in account search
 - add PublicNetworkAccess in disk creation

#### Which issue(s) this PR fixes:
<!--
*Automatically closes linked issue when PR is merged.
Usage: `Fixes #<issue number>`, or `Fixes (paste link of issue)`.
_If PR is about `failing-tests or flakes`, please post the related issues/tests in a comment and do not use `Fixes`_*
-->
Fixes #

#### Special notes for your reviewer:

#### Does this PR introduce a user-facing change?
<!--
If no, just write "NONE" in the release-note block below.
If yes, a release note is required:
Enter your extended release note in the block below. If the PR requires additional action from users switching to the new release, include the string "action required".

For more information on release notes see: https://git.k8s.io/community/contributors/guide/release-notes.md
-->
```release-note
 - add PickRandomMatchingAccount in account search
 - add PublicNetworkAccess in disk creation
```

#### Additional documentation e.g., KEPs (Kubernetes Enhancement Proposals), usage docs, etc.:

<!--
This section can be blank if this pull request does not require a release note.

When adding links which point to resources within git repositories, like
KEPs or supporting documentation, please reference a specific commit and avoid
linking directly to the master branch. This ensures that links reference a
specific point in time, rather than a document that may change over time.

See here for guidance on getting permanent links to files: https://help.github.com/en/articles/getting-permanent-links-to-files

Please use the following format for linking documentation:
- [KEP]: <link>
- [Usage]: <link>
- [Other doc]: <link>
-->
```docs
 - add PickRandomMatchingAccount in account search
 - add PublicNetworkAccess in disk creation
```



Patch:
diff --git a/pkg/provider/azure_managedDiskController.go b/pkg/provider/azure_managedDiskController.go
index 5e3a057e7..0762d4b1c 100644
--- a/pkg/provider/azure_managedDiskController.go
+++ b/pkg/provider/azure_managedDiskController.go
@@ -76,6 +76,8 @@ type ManagedDiskOptions struct {
 	LogicalSectorSize int32
 	// SkipGetDiskOperation indicates whether skip GetDisk operation(mainly due to throttling)
 	SkipGetDiskOperation bool
+	// PublicNetworkAccess - Possible values include: 'Enabled', 'Disabled'
+	PublicNetworkAccess compute.PublicNetworkAccess
 	// NetworkAccessPolicy - Possible values include: 'AllowAll', 'AllowPrivate', 'DenyAll'
 	NetworkAccessPolicy compute.NetworkAccessPolicy
 	// DiskAccessID - ARM id of the DiskAccess resource for using private endpoints on disks.
@@ -139,6 +141,10 @@ func (c *ManagedDiskController) CreateManagedDisk(ctx context.Context, options *
 		BurstingEnabled: options.BurstingEnabled,
 	}
 
+	if options.PublicNetworkAccess != "" {
+		diskProperties.PublicNetworkAccess = options.PublicNetworkAccess
+	}
+
 	if options.NetworkAccessPolicy != "" {
 		diskProperties.NetworkAccessPolicy = options.NetworkAccessPolicy
 		if options.NetworkAccessPolicy == compute.AllowPrivate {
diff --git a/pkg/provider/azure_storageaccount.go b/pkg/provider/azure_storageaccount.go
index 1a0f6b717..d4afbf251 100644
--- a/pkg/provider/azure_storageaccount.go
+++ b/pkg/provider/azure_storageaccount.go
@@ -18,7 +18,9 @@ package provider
 
 import (
 	"context"
+	"crypto/rand"
 	"fmt"
+	"math/big"
 	"strings"
 
 	"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network"
@@ -75,6 +77,8 @@ type AccountOptions struct {
 	EnableBlobVersioning                    *bool
 	SoftDeleteBlobs                         int32
 	SoftDeleteContainers                    int32
+	// indicate whether to get a random matching account, if false, will get the first matching account
+	PickRandomMatchingAccount bool
 }
 
 type accountWithLocation struct {
@@ -212,7 +216,17 @@ func (az *Cloud) EnsureStorageAccount(ctx context.Context, accountOptions *Accou
 			}
 
 			if len(accounts) > 0 {
-				accountName = accounts[0].Name
+				index := 0
+				if accountOptions.PickRandomMatchingAccount {
+					// randomly pick one matching account
+					n, err := rand.Int(rand.Reader, big.NewInt(int64(len(accounts))))
+					if err != nil || n == nil {
+						return "", "", err
+					}
+					index = int(n.Int64())
+					klog.V(4).Infof("randomly pick one matching account, index: %d", index)
+				}
+				accountName = accounts[index].Name
 				createNewAccount = false
 				klog.V(4).Infof("found a matching account %s type %s location %s", accounts[0].Name, accounts[0].StorageType, accounts[0].Location)
 			}


Test patch:
diff --git a/pkg/provider/azure_managedDiskController_test.go b/pkg/provider/azure_managedDiskController_test.go
index 08cb94b9e..0354d5ea8 100644
--- a/pkg/provider/azure_managedDiskController_test.go
+++ b/pkg/provider/azure_managedDiskController_test.go
@@ -65,6 +65,7 @@ func TestCreateManagedDisk(t *testing.T) {
 		diskEncryptionType  string
 		subscriptionID      string
 		resouceGroup        string
+		publicNetworkAccess compute.PublicNetworkAccess
 		networkAccessPolicy compute.NetworkAccessPolicy
 		diskAccessID        *string
 		expectedDiskID      string
@@ -204,6 +205,7 @@ func TestCreateManagedDisk(t *testing.T) {
 			storageAccountType:  compute.StandardLRS,
 			diskEncryptionSetID: goodDiskEncryptionSetID,
 			networkAccessPolicy: compute.DenyAll,
+			publicNetworkAccess: compute.Disabled,
 			expectedDiskID:      disk1ID,
 			existedDisk:         compute.Disk{ID: pointer.String(disk1ID), Name: pointer.String(disk1Name), DiskProperties: &compute.DiskProperties{Encryption: &compute.Encryption{DiskEncryptionSetID: &goodDiskEncryptionSetID, Type: compute.EncryptionTypeEncryptionAtRestWithCustomerKey}, ProvisioningState: pointer.String("Succeeded")}, Tags: testTags},
 			expectedErr:         false,
@@ -216,6 +218,7 @@ func TestCreateManagedDisk(t *testing.T) {
 			diskEncryptionSetID: goodDiskEncryptionSetID,
 			diskEncryptionType:  "EncryptionAtRestWithCustomerKey",
 			networkAccessPolicy: compute.AllowAll,
+			publicNetworkAccess: compute.Enabled,
 			expectedDiskID:      disk1ID,
 			existedDisk:         compute.Disk{ID: pointer.String(disk1ID), Name: pointer.String(disk1Name), DiskProperties: &compute.DiskProperties{Encryption: &compute.Encryption{DiskEncryptionSetID: &goodDiskEncryptionSetID, Type: compute.EncryptionTypeEncryptionAtRestWithCustomerKey}, ProvisioningState: pointer.String("Succeeded")}, Tags: testTags},
 			expectedErr:         false,
@@ -274,6 +277,7 @@ func TestCreateManagedDisk(t *testing.T) {
 			DiskEncryptionType:  test.diskEncryptionType,
 			MaxShares:           maxShare,
 			NetworkAccessPolicy: test.networkAccessPolicy,
+			PublicNetworkAccess: test.publicNetworkAccess,
 			DiskAccessID:        test.diskAccessID,
 			SubscriptionID:      test.subscriptionID,
 		}
diff --git a/pkg/provider/azure_storageaccount_test.go b/pkg/provider/azure_storageaccount_test.go
index 6b3dd1827..d40b84477 100644
--- a/pkg/provider/azure_storageaccount_test.go
+++ b/pkg/provider/azure_storageaccount_test.go
@@ -378,6 +378,7 @@ func TestEnsureStorageAccount(t *testing.T) {
 		SubnetPropertiesFormatNil       bool
 		mockStorageAccountsClient       bool
 		setAccountOptions               bool
+		pickRandomMatchingAccount       bool
 		accessTier                      string
 		storageType                     StorageType
 		requireInfrastructureEncryption *bool
@@ -393,6 +394,7 @@ func TestEnsureStorageAccount(t *testing.T) {
 			createPrivateEndpoint:           true,
 			mockStorageAccountsClient:       true,
 			setAccountOptions:               true,
+			pickRandomMatchingAccount:       true,
 			storageType:                     StorageTypeBlob,
 			requireInfrastructureEncryption: pointer.Bool(true),
 			keyVaultURL:                     pointer.String("keyVaultURL"),
@@ -502,16 +504,17 @@ func TestEnsureStorageAccount(t *testing.T) {
 		var testAccountOptions *AccountOptions
 		if test.setAccountOptions {
 			testAccountOptions = &AccountOptions{
-				ResourceGroup:         test.resourceGroup,
-				CreatePrivateEndpoint: test.createPrivateEndpoint,
-				Name:                  test.accountName,
-				CreateAccount:         test.createAccount,
-				SubscriptionID:        test.subscriptionID,
-				AccessTier:            test.accessTier,
-				StorageType:           test.storageType,
-				EnableBlobVersioning:  pointer.Bool(true),
-				SoftDeleteBlobs:       7,
-				SoftDeleteContainers:  7,
+				ResourceGroup:             test.resourceGroup,
+				CreatePrivateEndpoint:     test.createPrivateEndpoint,
+				Name:                      test.accountName,
+				CreateAccount:             test.createAccount,
+				SubscriptionID:            test.subscriptionID,
+				AccessTier:                test.accessTier,
+				StorageType:               test.storageType,
+				EnableBlobVersioning:      pointer.Bool(true),
+				SoftDeleteBlobs:           7,
+				SoftDeleteContainers:      7,
+				PickRandomMatchingAccount: test.pickRandomMatchingAccount,
 			}
 		}