From 866011ad636a5afb702fb7f237cfc8d246f6e2c7 Mon Sep 17 00:00:00 2001 From: MartinForReal Date: Mon, 9 Dec 2024 11:33:20 +0800 Subject: [PATCH] remove track1 pls client from codebase --- .../azure_privatelinkserviceclient.go | 460 ------------------ .../azure_privatelinkserviceclient_test.go | 370 -------------- .../privatelinkserviceclient/doc.go | 18 - .../privatelinkserviceclient/interface.go | 54 -- .../mockprivatelinkserviceclient/doc.go | 18 - .../mockprivatelinkserviceclient/interface.go | 131 ----- 6 files changed, 1051 deletions(-) delete mode 100644 pkg/azureclients/privatelinkserviceclient/azure_privatelinkserviceclient.go delete mode 100644 pkg/azureclients/privatelinkserviceclient/azure_privatelinkserviceclient_test.go delete mode 100644 pkg/azureclients/privatelinkserviceclient/doc.go delete mode 100644 pkg/azureclients/privatelinkserviceclient/interface.go delete mode 100644 pkg/azureclients/privatelinkserviceclient/mockprivatelinkserviceclient/doc.go delete mode 100644 pkg/azureclients/privatelinkserviceclient/mockprivatelinkserviceclient/interface.go diff --git a/pkg/azureclients/privatelinkserviceclient/azure_privatelinkserviceclient.go b/pkg/azureclients/privatelinkserviceclient/azure_privatelinkserviceclient.go deleted file mode 100644 index 6d15589903..0000000000 --- a/pkg/azureclients/privatelinkserviceclient/azure_privatelinkserviceclient.go +++ /dev/null @@ -1,460 +0,0 @@ -/* -Copyright 2021 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 privatelinkserviceclient implements the client for PrivateLinkService. -package privatelinkserviceclient - -import ( - "context" - "net/http" - "strings" - "time" - - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - - "k8s.io/client-go/util/flowcontrol" - "k8s.io/klog/v2" - "k8s.io/utils/ptr" - - azclients "sigs.k8s.io/cloud-provider-azure/pkg/azureclients" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient" - "sigs.k8s.io/cloud-provider-azure/pkg/metrics" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -var _ Interface = &Client{} - -const ( - PLSResourceType = "Microsoft.Network/privatelinkservices" - PEConnResourceType = "privateEndpointConnections" -) - -// Client implements privatelinkservice Interface. -type Client struct { - armClient armclient.Interface - cloudName string - subscriptionID string - - // Rate limiting configures. - rateLimiterReader flowcontrol.RateLimiter - rateLimiterWriter flowcontrol.RateLimiter - - // ARM throttling configures. - RetryAfterReader time.Time - RetryAfterWriter time.Time -} - -// New creates a new private link service client. -func New(config *azclients.ClientConfig) *Client { - - apiVersion := APIVersion - if strings.EqualFold(config.CloudName, AzureStackCloudName) && !config.DisableAzureStackCloud { - apiVersion = AzureStackCloudAPIVersion - } - armClient := armclient.New(config.Authorizer, *config, config.ResourceManagerEndpoint, apiVersion) - - rateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(config.RateLimitConfig) - if azclients.RateLimitEnabled(config.RateLimitConfig) { - klog.V(2).Infof("Azure PrivateLinkServicesClient (read ops) using rate limit config: QPS=%g, bucket=%d", - config.RateLimitConfig.CloudProviderRateLimitQPS, - config.RateLimitConfig.CloudProviderRateLimitBucket) - klog.V(2).Infof("Azure PrivateLinkServicesClient (write ops) using rate limit config: QPS=%g, bucket=%d", - config.RateLimitConfig.CloudProviderRateLimitQPSWrite, - config.RateLimitConfig.CloudProviderRateLimitBucketWrite) - } - - client := &Client{ - armClient: armClient, - rateLimiterReader: rateLimiterReader, - rateLimiterWriter: rateLimiterWriter, - subscriptionID: config.SubscriptionID, - cloudName: config.CloudName, - } - return client -} - -// CreateOrUpdate creates or updates a private link service . -func (c *Client) CreateOrUpdate(ctx context.Context, resourceGroupName string, privateLinkServiceName string, privateLinkService network.PrivateLinkService, etag string) *retry.Error { - mc := metrics.NewMetricContext("private_link_services", "create_or_update", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterWriter.TryAccept() { - mc.RateLimitedCount() - return retry.GetRateLimitError(true, "PLSCreateOrUpdate") - } - - // Report errors if the client is throttled. - if c.RetryAfterWriter.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("PLSCreateOrUpdate", "client throttled", c.RetryAfterWriter) - return rerr - } - - rerr := c.createOrUpdatePLS(ctx, resourceGroupName, privateLinkServiceName, privateLinkService, etag) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterWriter = rerr.RetryAfter - } - - return rerr - } - return nil -} -func (c *Client) createOrUpdatePLS(ctx context.Context, resourceGroupName string, privateLinkServiceName string, parameters network.PrivateLinkService, etag string) *retry.Error { - resourceID := armclient.GetResourceID( - c.subscriptionID, - resourceGroupName, - PLSResourceType, - privateLinkServiceName, - ) - decorators := []autorest.PrepareDecorator{} - if etag != "" { - decorators = append(decorators, autorest.WithHeader("If-Match", autorest.String(etag))) - } - - response, rerr := c.armClient.PutResource(ctx, resourceID, parameters, decorators...) - defer c.armClient.CloseResponse(ctx, response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "privatelinkservice.put.request", resourceID, rerr.Error()) - return rerr - } - - if response != nil && response.StatusCode != http.StatusNoContent { - _, rerr = c.createOrUpdateResponder(response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "privatelinkservice.put.respond", resourceID, rerr.Error()) - return rerr - } - } - return nil -} - -func (c *Client) createOrUpdateResponder(resp *http.Response) (*network.PrivateLinkService, *retry.Error) { - result := &network.PrivateLinkService{} - err := autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result)) - result.Response = autorest.Response{Response: resp} - return result, retry.GetError(resp, err) -} - -// Get gets the private link service -func (c *Client) Get(ctx context.Context, resourceGroupName string, privateLinkServiceName string, expand string) (network.PrivateLinkService, *retry.Error) { - mc := metrics.NewMetricContext("private_link_services", "get", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterReader.TryAccept() { - mc.RateLimitedCount() - return network.PrivateLinkService{}, retry.GetRateLimitError(false, "PLSGet") - } - - // Report errors if the client is throttled. - if c.RetryAfterReader.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("PLSGet", "client throttled", c.RetryAfterReader) - return network.PrivateLinkService{}, rerr - } - result, rerr := c.getPLS(ctx, resourceGroupName, privateLinkServiceName, expand) - - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterReader = rerr.RetryAfter - } - return result, rerr - } - return result, nil -} - -// getPLS gets a privatelinkservice. -func (c *Client) getPLS(ctx context.Context, resourceGroupName string, privateLinkServiceName string, expand string) (network.PrivateLinkService, *retry.Error) { - resourceID := armclient.GetResourceID( - c.subscriptionID, - resourceGroupName, - PLSResourceType, - privateLinkServiceName, - ) - result := network.PrivateLinkService{} - response, rerr := c.armClient.GetResourceWithExpandQuery(ctx, resourceID, expand) - defer c.armClient.CloseResponse(ctx, response) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "privatelinkservice.get.request", resourceID, rerr.Error()) - return result, rerr - } - - err := autorest.Respond( - response, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result)) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "privatelinkservice.get.respond", resourceID, err) - return result, retry.GetError(response, err) - } - - result.Response = autorest.Response{Response: response} - return result, nil -} - -// List gets a list of PrivateLinkServices in the resource group. -func (c *Client) List(ctx context.Context, resourceGroupName string) ([]network.PrivateLinkService, *retry.Error) { - mc := metrics.NewMetricContext("private_link_services", "list", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterReader.TryAccept() { - mc.RateLimitedCount() - return nil, retry.GetRateLimitError(false, "PLSList") - } - - // Report errors if the client is throttled. - if c.RetryAfterReader.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("PLSList", "client throttled", c.RetryAfterReader) - return nil, rerr - } - - result, rerr := c.listPLS(ctx, resourceGroupName) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterReader = rerr.RetryAfter - } - - return result, rerr - } - - return result, nil -} - -// listPLS gets a list of PrivateLinkServices in the resource group. -func (c *Client) listPLS(ctx context.Context, resourceGroupName string) ([]network.PrivateLinkService, *retry.Error) { - resourceID := armclient.GetResourceListID(c.subscriptionID, resourceGroupName, PLSResourceType) - result := make([]network.PrivateLinkService, 0) - page := &PrivateLinkServiceListResultPage{} - page.fn = c.listNextResults - - resp, rerr := c.armClient.GetResource(ctx, resourceID) - defer c.armClient.CloseResponse(ctx, resp) - if rerr != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "privatelinkservice.list.request", resourceID, rerr.Error()) - return result, rerr - } - - var err error - page.plslr, err = c.listResponder(resp) - if err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "privatelinkservice.list.respond", resourceID, err) - return result, retry.GetError(resp, err) - } - - for { - result = append(result, page.Values()...) - - // Abort the loop when there's no nextLink in the response. - if ptr.Deref(page.Response().NextLink, "") == "" { - break - } - - if err = page.NextWithContext(ctx); err != nil { - klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "privatelinkservice.list.next", resourceID, err) - return result, retry.GetError(page.Response().Response.Response, err) - } - } - - return result, nil -} - -func (c *Client) Delete(ctx context.Context, resourceGroupName string, privateLinkServiceName string) *retry.Error { - mc := metrics.NewMetricContext("private_link_services", "delete", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterWriter.TryAccept() { - mc.RateLimitedCount() - return retry.GetRateLimitError(true, "PLSDelete") - } - - // Report errors if the client is throttled. - if c.RetryAfterWriter.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("PLSDelete", "client throttled", c.RetryAfterWriter) - return rerr - } - - rerr := c.deletePLS(ctx, resourceGroupName, privateLinkServiceName) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterWriter = rerr.RetryAfter - } - - return rerr - } - - return nil -} - -// deletePLS deletes a privatelinkservice by name. -func (c *Client) deletePLS(ctx context.Context, resourceGroupName string, privateLinkServiceName string) *retry.Error { - resourceID := armclient.GetResourceID( - c.subscriptionID, - resourceGroupName, - PLSResourceType, - privateLinkServiceName, - ) - - return c.armClient.DeleteResource(ctx, resourceID) -} - -func (c *Client) DeletePEConnection(ctx context.Context, resourceGroupName string, privateLinkServiceName string, privateEndpointConnectionName string) *retry.Error { - mc := metrics.NewMetricContext("private_endpoint_connection", "delete", resourceGroupName, c.subscriptionID, "") - - // Report errors if the client is rate limited. - if !c.rateLimiterWriter.TryAccept() { - mc.RateLimitedCount() - return retry.GetRateLimitError(true, "PEConnDelete") - } - - // Report errors if the client is throttled. - if c.RetryAfterWriter.After(time.Now()) { - mc.ThrottledCount() - rerr := retry.GetThrottlingError("PEConnDelete", "client throttled", c.RetryAfterWriter) - return rerr - } - - rerr := c.deletePEConn(ctx, resourceGroupName, privateLinkServiceName, privateEndpointConnectionName) - mc.Observe(rerr) - if rerr != nil { - if rerr.IsThrottled() { - // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. - c.RetryAfterWriter = rerr.RetryAfter - } - - return rerr - } - - return nil -} - -// deletePLS deletes a private endpoint connection by name. -func (c *Client) deletePEConn(ctx context.Context, resourceGroupName string, privateLinkServiceName string, privateEndpointConnectionName string) *retry.Error { - resourceID := armclient.GetChildResourceID( - c.subscriptionID, - resourceGroupName, - PLSResourceType, - privateLinkServiceName, - PEConnResourceType, - privateEndpointConnectionName, - ) - - return c.armClient.DeleteResource(ctx, resourceID) -} - -func (c *Client) listResponder(resp *http.Response) (result network.PrivateLinkServiceListResult, err error) { - err = autorest.Respond( - resp, - autorest.ByIgnoring(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result)) - result.Response = autorest.Response{Response: resp} - return -} - -// privateLinkServiceListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (c *Client) privateLinkServiceListResultPreparer(ctx context.Context, plslr network.PrivateLinkServiceListResult) (*http.Request, error) { - if plslr.NextLink == nil || len(ptr.Deref(plslr.NextLink, "")) < 1 { - return nil, nil - } - - decorators := []autorest.PrepareDecorator{ - autorest.WithBaseURL(ptr.Deref(plslr.NextLink, "")), - } - return c.armClient.PrepareGetRequest(ctx, decorators...) -} - -// listNextResults retrieves the next set of results, if any. -func (c *Client) listNextResults(ctx context.Context, lastResults network.PrivateLinkServiceListResult) (result network.PrivateLinkServiceListResult, err error) { - req, err := c.privateLinkServiceListResultPreparer(ctx, lastResults) - if err != nil { - return result, autorest.NewErrorWithError(err, "privatelinkserviceclient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - - resp, rerr := c.armClient.Send(ctx, req) - defer c.armClient.CloseResponse(ctx, resp) - if rerr != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(rerr.Error(), "privatelinkserviceclient", "listNextResults", resp, "Failure sending next results request") - } - - result, err = c.listResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "privatelinkserviceclient", "listNextResults", resp, "Failure responding to next results request") - } - - return -} - -// PrivateLinkServiceListResultPage contains a page of PrivateLinkService values. -type PrivateLinkServiceListResultPage struct { - fn func(context.Context, network.PrivateLinkServiceListResult) (network.PrivateLinkServiceListResult, error) - plslr network.PrivateLinkServiceListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *PrivateLinkServiceListResultPage) NextWithContext(ctx context.Context) (err error) { - next, err := page.fn(ctx, page.plslr) - if err != nil { - return err - } - page.plslr = next - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *PrivateLinkServiceListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page PrivateLinkServiceListResultPage) NotDone() bool { - return !page.plslr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page PrivateLinkServiceListResultPage) Response() network.PrivateLinkServiceListResult { - return page.plslr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page PrivateLinkServiceListResultPage) Values() []network.PrivateLinkService { - if page.plslr.IsEmpty() { - return nil - } - return *page.plslr.Value -} diff --git a/pkg/azureclients/privatelinkserviceclient/azure_privatelinkserviceclient_test.go b/pkg/azureclients/privatelinkserviceclient/azure_privatelinkserviceclient_test.go deleted file mode 100644 index 006f386aa1..0000000000 --- a/pkg/azureclients/privatelinkserviceclient/azure_privatelinkserviceclient_test.go +++ /dev/null @@ -1,370 +0,0 @@ -/* -Copyright 2021 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 privatelinkserviceclient implements the client for PrivateLinkService. -package privatelinkserviceclient - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "testing" - "time" - - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - "github.com/Azure/go-autorest/autorest" - "github.com/stretchr/testify/assert" - - "go.uber.org/mock/gomock" - - "k8s.io/utils/ptr" - - azclients "sigs.k8s.io/cloud-provider-azure/pkg/azureclients" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient" - "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/armclient/mockarmclient" - "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -const ( - testResourceID = "/subscriptions/subscriptionID/resourceGroups/rg/providers/" + PLSResourceType + "/pls1" - testResourcePrefix = "/subscriptions/subscriptionID/resourceGroups/rg/providers/" + PLSResourceType -) - -func TestNew(t *testing.T) { - config := &azclients.ClientConfig{ - SubscriptionID: "sub", - ResourceManagerEndpoint: "endpoint", - Location: "eastus", - RateLimitConfig: &azclients.RateLimitConfig{ - CloudProviderRateLimit: true, - CloudProviderRateLimitQPS: 0.5, - CloudProviderRateLimitBucket: 1, - CloudProviderRateLimitQPSWrite: 0.5, - CloudProviderRateLimitBucketWrite: 1, - }, - Backoff: &retry.Backoff{Steps: 1}, - } - - plsClient := New(config) - assert.Equal(t, "sub", plsClient.subscriptionID) - assert.NotEmpty(t, plsClient.rateLimiterReader) - assert.NotEmpty(t, plsClient.rateLimiterWriter) -} - -func TestNewAzureStack(t *testing.T) { - config := &azclients.ClientConfig{ - CloudName: "AZURESTACKCLOUD", - SubscriptionID: "sub", - ResourceManagerEndpoint: "endpoint", - Location: "eastus", - RateLimitConfig: &azclients.RateLimitConfig{ - CloudProviderRateLimit: true, - CloudProviderRateLimitQPS: 0.5, - CloudProviderRateLimitBucket: 1, - CloudProviderRateLimitQPSWrite: 0.5, - CloudProviderRateLimitBucketWrite: 1, - }, - Backoff: &retry.Backoff{Steps: 1}, - } - - plsClient := New(config) - assert.Equal(t, "AZURESTACKCLOUD", plsClient.cloudName) - assert.Equal(t, "sub", plsClient.subscriptionID) -} - -func TestGetNotFound(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusNotFound, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResourceWithExpandQuery(gomock.Any(), testResourceID, "").Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - plsClient := getTestPrivateLinkServiceClient(armClient) - expected := network.PrivateLinkService{Response: autorest.Response{}} - result, rerr := plsClient.Get(context.TODO(), "rg", "pls1", "") - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusNotFound, rerr.HTTPStatusCode) -} - -func TestGetInternalError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusInternalServerError, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResourceWithExpandQuery(gomock.Any(), testResourceID, "").Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - plsClient := getTestPrivateLinkServiceClient(armClient) - expected := network.PrivateLinkService{Response: autorest.Response{}} - result, rerr := plsClient.Get(context.TODO(), "rg", "pls1", "") - assert.Equal(t, expected, result) - assert.NotNil(t, rerr) - assert.Equal(t, http.StatusInternalServerError, rerr.HTTPStatusCode) -} - -func TestGetThrottle(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - response := &http.Response{ - StatusCode: http.StatusTooManyRequests, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().GetResourceWithExpandQuery(gomock.Any(), testResourceID, "").Return(response, throttleErr).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - plsClient := getTestPrivateLinkServiceClient(armClient) - result, rerr := plsClient.Get(context.TODO(), "rg", "pls1", "") - assert.Empty(t, result) - assert.Equal(t, throttleErr, rerr) -} - -func TestList(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - plsList := []network.PrivateLinkService{getTestPrivateLinkService("pls1"), getTestPrivateLinkService("pls2"), getTestPrivateLinkService("pls3")} - responseBody, err := json.Marshal(network.PrivateLinkServiceListResult{Value: &plsList}) - assert.NoError(t, err) - armClient.EXPECT().GetResource(gomock.Any(), testResourcePrefix).Return( - &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader(responseBody)), - }, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - plsClient := getTestPrivateLinkServiceClient(armClient) - result, rerr := plsClient.List(context.TODO(), "rg") - assert.Nil(t, rerr) - assert.Equal(t, 3, len(result)) - - response := &http.Response{ - StatusCode: http.StatusTooManyRequests, - Body: io.NopCloser(bytes.NewReader([]byte("{}"))), - } - throttleErr := &retry.Error{ - HTTPStatusCode: http.StatusTooManyRequests, - RawError: fmt.Errorf("error"), - Retriable: true, - RetryAfter: time.Unix(100, 0), - } - armClient.EXPECT().GetResource(gomock.Any(), testResourcePrefix).Return(response, throttleErr).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - _, rerr = plsClient.List(context.TODO(), "rg") - assert.Equal(t, throttleErr, rerr) -} - -func TestListWithNextPage(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - armClient := mockarmclient.NewMockInterface(ctrl) - plsList := []network.PrivateLinkService{getTestPrivateLinkService("pls1"), getTestPrivateLinkService("pls2"), getTestPrivateLinkService("pls3")} - partialResponse, err := json.Marshal(network.PrivateLinkServiceListResult{Value: &plsList, NextLink: ptr.To("nextLink")}) - assert.NoError(t, err) - _, err = json.Marshal(network.PrivateLinkServiceListResult{Value: &plsList}) - assert.NoError(t, err) - armClient.EXPECT().GetResource(gomock.Any(), testResourcePrefix).Return( - &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader(partialResponse)), - }, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - plsClient := getTestPrivateLinkServiceClient(armClient) - result, rerr := plsClient.List(context.TODO(), "rg") - assert.Nil(t, rerr) - assert.Equal(t, 3, len(result)) -} - -func TestListNextResultsMultiPages(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - tests := []struct { - prepareErr error - sendErr *retry.Error - }{ - { - prepareErr: nil, - sendErr: nil, - }, - { - prepareErr: fmt.Errorf("error"), - }, - { - sendErr: &retry.Error{RawError: fmt.Errorf("error")}, - }, - } - - lastResult := network.PrivateLinkServiceListResult{ - NextLink: ptr.To("next"), - } - - for _, test := range tests { - armClient := mockarmclient.NewMockInterface(ctrl) - req := &http.Request{ - Method: "GET", - } - armClient.EXPECT().PrepareGetRequest(gomock.Any(), gomock.Any()).Return(req, test.prepareErr) - if test.prepareErr == nil { - armClient.EXPECT().Send(gomock.Any(), req).Return(&http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte(`{"foo":"bar"}`))), - }, test.sendErr) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()) - } - - plsClient := getTestPrivateLinkServiceClient(armClient) - result, err := plsClient.listNextResults(context.TODO(), lastResult) - if test.prepareErr != nil || test.sendErr != nil { - assert.Error(t, err) - } else { - assert.NoError(t, err) - } - if test.prepareErr != nil { - assert.Empty(t, result) - } else { - assert.NotEmpty(t, result) - } - } -} - -func TestCreateOrUpdate(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - pls := getTestPrivateLinkService("pls1") - armClient := mockarmclient.NewMockInterface(ctrl) - response := &http.Response{ - StatusCode: http.StatusOK, - Body: io.NopCloser(bytes.NewReader([]byte(""))), - } - armClient.EXPECT().PutResource(gomock.Any(), ptr.Deref(pls.ID, ""), pls, gomock.Any()).Return(response, nil).Times(1) - armClient.EXPECT().CloseResponse(gomock.Any(), gomock.Any()).Times(1) - - plsClient := getTestPrivateLinkServiceClient(armClient) - rerr := plsClient.CreateOrUpdate(context.TODO(), "rg", "pls1", pls, "") - assert.Nil(t, rerr) -} - -func TestDelete(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - tests := []struct { - description string - armClientErr *retry.Error - expectedErr *retry.Error - }{ - { - description: "Delete should report the throttling error", - armClientErr: &retry.Error{HTTPStatusCode: http.StatusTooManyRequests}, - expectedErr: &retry.Error{HTTPStatusCode: http.StatusTooManyRequests}, - }, - { - description: "Delete should not report any error if there's no error from arm client", - }, - } - - pls := getTestPrivateLinkService("pls1") - - for _, test := range tests { - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().DeleteResource(gomock.Any(), ptr.Deref(pls.ID, "")).Return(test.armClientErr) - - plsClient := getTestPrivateLinkServiceClient(armClient) - rerr := plsClient.Delete(context.TODO(), "rg", "pls1") - assert.Equal(t, test.expectedErr, rerr) - } -} - -func TestDeletePEConnection(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - tests := []struct { - description string - armClientErr *retry.Error - expectedErr *retry.Error - }{ - { - description: "Delete should report the throttling error", - armClientErr: &retry.Error{HTTPStatusCode: http.StatusTooManyRequests}, - expectedErr: &retry.Error{HTTPStatusCode: http.StatusTooManyRequests}, - }, - { - description: "Delete should not report any error if there's no error from arm client", - }, - } - - peConn := getTestPrivateEndpointConnection("pls1", "peconn") - - for _, test := range tests { - armClient := mockarmclient.NewMockInterface(ctrl) - armClient.EXPECT().DeleteResource(gomock.Any(), ptr.Deref(peConn.ID, "")).Return(test.armClientErr) - - plsClient := getTestPrivateLinkServiceClient(armClient) - rerr := plsClient.DeletePEConnection(context.TODO(), "rg", "pls1", "peconn") - assert.Equal(t, test.expectedErr, rerr) - } -} - -func getTestPrivateLinkService(name string) network.PrivateLinkService { - return network.PrivateLinkService{ - ID: ptr.To(fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/%s/%s", PLSResourceType, name)), - Name: ptr.To(name), - Location: ptr.To("eastus"), - } -} - -func getTestPrivateEndpointConnection(PLSName string, PEConnName string) network.PrivateEndpointConnection { - return network.PrivateEndpointConnection{ - ID: ptr.To(fmt.Sprintf("/subscriptions/subscriptionID/resourceGroups/rg/providers/%s/%s/%s/%s", PLSResourceType, PLSName, PEConnResourceType, PEConnName)), - Name: ptr.To(PEConnName), - } -} - -func getTestPrivateLinkServiceClient(armClient armclient.Interface) *Client { - rateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(&azclients.RateLimitConfig{}) - return &Client{ - armClient: armClient, - subscriptionID: "subscriptionID", - rateLimiterReader: rateLimiterReader, - rateLimiterWriter: rateLimiterWriter, - } -} diff --git a/pkg/azureclients/privatelinkserviceclient/doc.go b/pkg/azureclients/privatelinkserviceclient/doc.go deleted file mode 100644 index 148b675baf..0000000000 --- a/pkg/azureclients/privatelinkserviceclient/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2020 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 privatelinkserviceclient implements the client for PrivateLinkService. -package privatelinkserviceclient // import "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/privatelinkserviceclient" diff --git a/pkg/azureclients/privatelinkserviceclient/interface.go b/pkg/azureclients/privatelinkserviceclient/interface.go deleted file mode 100644 index d18b182d57..0000000000 --- a/pkg/azureclients/privatelinkserviceclient/interface.go +++ /dev/null @@ -1,54 +0,0 @@ -/* -Copyright 2020 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 privatelinkserviceclient - -import ( - "context" - - "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - - "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -const ( - // APIVersion is the API version for network. - APIVersion = "2022-07-01" - // AzureStackCloudAPIVersion is the API version for Azure Stack - AzureStackCloudAPIVersion = "2019-03-01" - // AzureStackCloudName is the cloud name of Azure Stack - AzureStackCloudName = "AZURESTACKCLOUD" -) - -// Interface is the client interface for Private Link Services. -// Don't forget to run "hack/update-mock-clients.sh" command to generate the mock client. -type Interface interface { - - // Get gets the private link service - Get(ctx context.Context, resourceGroupName string, privateLinkServiceName string, expand string) (result network.PrivateLinkService, rerr *retry.Error) - - // List gets a list of PrivateLinkService in the resource group. - List(ctx context.Context, resourceGroupName string) (result []network.PrivateLinkService, rerr *retry.Error) - - // CreateOrUpdate creates or updates a private link service. - CreateOrUpdate(ctx context.Context, resourceGroupName string, privateLinkServiceName string, privateLinkService network.PrivateLinkService, etag string) *retry.Error - - // Delete deletes a private link service by name. - Delete(ctx context.Context, resourceGroupName string, privateLinkServiceName string) *retry.Error - - // Delete deletes a private endpoint connection to the private link service by name - DeletePEConnection(ctx context.Context, resourceGroupName string, privateLinkServiceName string, privateEndpointConnectionName string) *retry.Error -} diff --git a/pkg/azureclients/privatelinkserviceclient/mockprivatelinkserviceclient/doc.go b/pkg/azureclients/privatelinkserviceclient/mockprivatelinkserviceclient/doc.go deleted file mode 100644 index b51d667dbe..0000000000 --- a/pkg/azureclients/privatelinkserviceclient/mockprivatelinkserviceclient/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Copyright 2020 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 mockprivatelinkserviceclient implements the mock client for PrivateLinkService. -package mockprivatelinkserviceclient // import "sigs.k8s.io/cloud-provider-azure/pkg/azureclients/privatelinkserviceclient/mockprivatelinkserviceclient" diff --git a/pkg/azureclients/privatelinkserviceclient/mockprivatelinkserviceclient/interface.go b/pkg/azureclients/privatelinkserviceclient/mockprivatelinkserviceclient/interface.go deleted file mode 100644 index 8b3e62cb0f..0000000000 --- a/pkg/azureclients/privatelinkserviceclient/mockprivatelinkserviceclient/interface.go +++ /dev/null @@ -1,131 +0,0 @@ -// /* -// Copyright 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. -// */ -// - -// Code generated by MockGen. DO NOT EDIT. -// Source: pkg/azureclients/privatelinkserviceclient/interface.go -// -// Generated by this command: -// -// mockgen -copyright_file=/home/runner/work/cloud-provider-azure/cloud-provider-azure/hack/boilerplate/boilerplate.generatego.txt -source=pkg/azureclients/privatelinkserviceclient/interface.go -package=mockprivatelinkserviceclient Interface -// - -// Package mockprivatelinkserviceclient is a generated GoMock package. -package mockprivatelinkserviceclient - -import ( - context "context" - reflect "reflect" - - network "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2022-07-01/network" - gomock "go.uber.org/mock/gomock" - retry "sigs.k8s.io/cloud-provider-azure/pkg/retry" -) - -// MockInterface is a mock of Interface interface. -type MockInterface struct { - ctrl *gomock.Controller - recorder *MockInterfaceMockRecorder -} - -// MockInterfaceMockRecorder is the mock recorder for MockInterface. -type MockInterfaceMockRecorder struct { - mock *MockInterface -} - -// NewMockInterface creates a new mock instance. -func NewMockInterface(ctrl *gomock.Controller) *MockInterface { - mock := &MockInterface{ctrl: ctrl} - mock.recorder = &MockInterfaceMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockInterface) EXPECT() *MockInterfaceMockRecorder { - return m.recorder -} - -// CreateOrUpdate mocks base method. -func (m *MockInterface) CreateOrUpdate(ctx context.Context, resourceGroupName, privateLinkServiceName string, privateLinkService network.PrivateLinkService, etag string) *retry.Error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateOrUpdate", ctx, resourceGroupName, privateLinkServiceName, privateLinkService, etag) - ret0, _ := ret[0].(*retry.Error) - return ret0 -} - -// CreateOrUpdate indicates an expected call of CreateOrUpdate. -func (mr *MockInterfaceMockRecorder) CreateOrUpdate(ctx, resourceGroupName, privateLinkServiceName, privateLinkService, etag any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateOrUpdate", reflect.TypeOf((*MockInterface)(nil).CreateOrUpdate), ctx, resourceGroupName, privateLinkServiceName, privateLinkService, etag) -} - -// Delete mocks base method. -func (m *MockInterface) Delete(ctx context.Context, resourceGroupName, privateLinkServiceName string) *retry.Error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Delete", ctx, resourceGroupName, privateLinkServiceName) - ret0, _ := ret[0].(*retry.Error) - return ret0 -} - -// Delete indicates an expected call of Delete. -func (mr *MockInterfaceMockRecorder) Delete(ctx, resourceGroupName, privateLinkServiceName any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*MockInterface)(nil).Delete), ctx, resourceGroupName, privateLinkServiceName) -} - -// DeletePEConnection mocks base method. -func (m *MockInterface) DeletePEConnection(ctx context.Context, resourceGroupName, privateLinkServiceName, privateEndpointConnectionName string) *retry.Error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeletePEConnection", ctx, resourceGroupName, privateLinkServiceName, privateEndpointConnectionName) - ret0, _ := ret[0].(*retry.Error) - return ret0 -} - -// DeletePEConnection indicates an expected call of DeletePEConnection. -func (mr *MockInterfaceMockRecorder) DeletePEConnection(ctx, resourceGroupName, privateLinkServiceName, privateEndpointConnectionName any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeletePEConnection", reflect.TypeOf((*MockInterface)(nil).DeletePEConnection), ctx, resourceGroupName, privateLinkServiceName, privateEndpointConnectionName) -} - -// Get mocks base method. -func (m *MockInterface) Get(ctx context.Context, resourceGroupName, privateLinkServiceName, expand string) (network.PrivateLinkService, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Get", ctx, resourceGroupName, privateLinkServiceName, expand) - ret0, _ := ret[0].(network.PrivateLinkService) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// Get indicates an expected call of Get. -func (mr *MockInterfaceMockRecorder) Get(ctx, resourceGroupName, privateLinkServiceName, expand any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockInterface)(nil).Get), ctx, resourceGroupName, privateLinkServiceName, expand) -} - -// List mocks base method. -func (m *MockInterface) List(ctx context.Context, resourceGroupName string) ([]network.PrivateLinkService, *retry.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "List", ctx, resourceGroupName) - ret0, _ := ret[0].([]network.PrivateLinkService) - ret1, _ := ret[1].(*retry.Error) - return ret0, ret1 -} - -// List indicates an expected call of List. -func (mr *MockInterfaceMockRecorder) List(ctx, resourceGroupName any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockInterface)(nil).List), ctx, resourceGroupName) -}