From b8676a0ead6fda97cd53417c3a992c4b95a60344 Mon Sep 17 00:00:00 2001 From: Marc Sensenich Date: Sun, 18 Nov 2018 12:49:44 +0000 Subject: [PATCH 01/23] [GH-42] Add Service Bus Subscription Count Client Adds the client and metric request structure for gathering message counts from Azure Service Bus Topic Subscriptions --- pkg/azure/servicebus/metricrequest.go | 113 ++++++++++++++ pkg/azure/servicebus/metricrequest_test.go | 146 ++++++++++++++++++ .../servicebus/subscription_count_client.go | 79 ++++++++++ .../subscription_count_client_test.go | 107 +++++++++++++ 4 files changed, 445 insertions(+) create mode 100644 pkg/azure/servicebus/metricrequest.go create mode 100644 pkg/azure/servicebus/metricrequest_test.go create mode 100644 pkg/azure/servicebus/subscription_count_client.go create mode 100644 pkg/azure/servicebus/subscription_count_client_test.go diff --git a/pkg/azure/servicebus/metricrequest.go b/pkg/azure/servicebus/metricrequest.go new file mode 100644 index 00000000..42f42598 --- /dev/null +++ b/pkg/azure/servicebus/metricrequest.go @@ -0,0 +1,113 @@ +package servicebus + +import ( + "errors" + "fmt" + + "github.com/golang/glog" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/apimachinery/pkg/selection" +) + +type AzureMetricRequest struct { + MetricName string + ResourceGroup string + Namespace string + Topic string + Subscription string + SubscriptionID string +} + +func ParseAzureMetric(metricSelector labels.Selector, defaultSubscriptionID string) (AzureMetricRequest, error) { + glog.V(4).Infof("Parsing a received AzureMetric") + glog.V(6).Infof("%v", metricSelector) + + if metricSelector == nil { + return AzureMetricRequest{}, fmt.Errorf("metricSelector cannot be nil") + } + + // Using selectors to pass required values thorugh + // to retain camel case as azure provider is case sensitive. + // + // There is are restrictions so using some conversion + // restrictions here + // note: requirement values are already validated by apiserver + merticReq := AzureMetricRequest{ + SubscriptionID: defaultSubscriptionID, + } + requirements, _ := metricSelector.Requirements() + for _, request := range requirements { + if request.Operator() != selection.Equals { + return AzureMetricRequest{}, errors.New("selector type not supported. only equals is supported at this time") + } + + value := request.Values().List()[0] + + switch request.Key() { + case "metricName": + glog.V(4).Infof("AzureMetric metricName: %s", value) + merticReq.MetricName = value + case "resourceGroup": + glog.V(4).Infof("AzureMetric resourceGroup: %s", value) + merticReq.ResourceGroup = value + case "namespace": + glog.V(4).Infof("AzureMetric namespace: %s", value) + merticReq.Namespace = value + case "topic": + glog.V(4).Infof("AzureMetric topic: %s", value) + merticReq.Topic = value + case "subscription": + glog.V(4).Infof("AzureMetric subscription: %s", value) + merticReq.Subscription = value + case "subscriptionID": + // if sub id is passed via label selectors then it takes precedence + glog.V(4).Infof("AzureMetric override azure subscription id with : %s", value) + merticReq.SubscriptionID = value + default: + return AzureMetricRequest{}, fmt.Errorf("selector label '%s' not supported", request.Key()) + } + } + + glog.V(2).Infof("Successfully parsed AzureMetric %s", merticReq.MetricName) + + return merticReq, nil +} + +type InvalidMetricRequestError struct { + err string +} + +func (i InvalidMetricRequestError) Error() string { + return fmt.Sprintf(i.err) +} + +func IsInvalidMetricRequestError(err error) bool { + if _, ok := err.(InvalidMetricRequestError); ok { + return true + } + return false +} + +func (amr AzureMetricRequest) Validate() error { + if amr.MetricName == "" { + return InvalidMetricRequestError{err: "metricName is required"} + } + if amr.ResourceGroup == "" { + return InvalidMetricRequestError{err: "resourceGroup is required"} + } + if amr.Namespace == "" { + return InvalidMetricRequestError{err: "namespace is required"} + } + if amr.Topic == "" { + return InvalidMetricRequestError{err: "topic is required"} + } + if amr.Subscription == "" { + return InvalidMetricRequestError{err: "subscription is required"} + } + if amr.SubscriptionID == "" { + return InvalidMetricRequestError{err: "subscriptionID is required. set a default or pass via label selectors"} + } + + // if here then valid! + return nil +} diff --git a/pkg/azure/servicebus/metricrequest_test.go b/pkg/azure/servicebus/metricrequest_test.go new file mode 100644 index 00000000..e66e85a3 --- /dev/null +++ b/pkg/azure/servicebus/metricrequest_test.go @@ -0,0 +1,146 @@ +package servicebus + +import ( + "fmt" + "reflect" + "testing" + + "k8s.io/apimachinery/pkg/labels" +) + +const subscription = "test-sub" +const topic = "test-topic" +const namespace = "test-namespace" +const resourceGroup = "test-resource-group" +const metricName = "metric-name" +const subscriptionID = "1234-5678" + +var validLabelSelector = fmt.Sprintf("subscription=%s,topic=%s,namespace=%s,resourceGroup=%s,metricName=%s", subscription, topic, namespace, resourceGroup, metricName) + +type testArguments struct { + metricSelector string + defaultSubscriptionID string +} + +// List of test cases that will be run for validating the parsing of metric configuration +var testCases = []struct { + name string + args testArguments + want AzureMetricRequest + wantErr bool + validate bool +}{ + // Begin test cases + { + name: "Test if metricSelector is nil do not fail", + args: testArguments{ + defaultSubscriptionID: "", + metricSelector: "", + }, + want: AzureMetricRequest{}, + wantErr: true, + validate: false, + }, + { + name: "Test insufficient data expect an error", + args: testArguments{ + defaultSubscriptionID: "", + metricSelector: "namespace=testing", + }, + want: AzureMetricRequest{}, + wantErr: true, + validate: true, + }, + { + name: "Test valid case with overriding subscription ID passed in", + args: testArguments{ + defaultSubscriptionID: subscriptionID, + metricSelector: validLabelSelector, + }, + want: AzureMetricRequest{ + Namespace: namespace, + Subscription: subscription, + Topic: topic, + MetricName: metricName, + ResourceGroup: resourceGroup, + SubscriptionID: subscriptionID, + }, + wantErr: false, + validate: true, + }, + { + name: "Test valid case with overriding subscription ID in selector", + args: testArguments{ + defaultSubscriptionID: subscriptionID, + metricSelector: fmt.Sprintf("%s,subscriptionID=%s", validLabelSelector, subscriptionID), + }, + want: AzureMetricRequest{ + Namespace: namespace, + Subscription: subscription, + Topic: topic, + MetricName: metricName, + ResourceGroup: resourceGroup, + SubscriptionID: subscriptionID, + }, + wantErr: false, + validate: true, + }, + { + name: "Test valid case with overriding subscription ID in selector", + args: testArguments{ + defaultSubscriptionID: subscriptionID, + metricSelector: fmt.Sprintf("%s,subscriptionID=%s", validLabelSelector, subscriptionID), + }, + want: AzureMetricRequest{ + Namespace: namespace, + Subscription: subscription, + Topic: topic, + MetricName: metricName, + ResourceGroup: resourceGroup, + SubscriptionID: subscriptionID, + }, + wantErr: false, + validate: true, + }, +} + +// Test the parsing of the External Metric Configuration that is expected from +// the Custom Resource Definition for the External Metric Provider +func TestParsingAzureExternalMetricConfiguration(t *testing.T) { + // Run through the test cases and valid expected outcomes + for _, tt := range testCases { + t.Run(tt.name, func(t *testing.T) { + metricSelector, err := labels.Parse(tt.args.metricSelector) + if err != nil { + t.Errorf("ParseAzureMetric() error parsing metricSelector %s", metricSelector) + } + + if len(tt.args.metricSelector) == 0 { + metricSelector = nil + } + + got, parseErr := ParseAzureMetric(metricSelector, tt.args.defaultSubscriptionID) + + if tt.validate { + err = got.Validate() + if (err != nil) != tt.wantErr { + t.Errorf("ParseAzureMetric() validation error = %v", err) + } + } + + if err != nil { + return + } + + if (parseErr != nil) != tt.wantErr { + t.Errorf("ParseAzureMetric() error = %v, wantErr %v", parseErr, tt.wantErr) + return + } + + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("ParseAzureMetric() = %v, want %v", got, tt.want) + return + } + }) + } +} diff --git a/pkg/azure/servicebus/subscription_count_client.go b/pkg/azure/servicebus/subscription_count_client.go new file mode 100644 index 00000000..244e7e24 --- /dev/null +++ b/pkg/azure/servicebus/subscription_count_client.go @@ -0,0 +1,79 @@ +package servicebus + +import ( + "context" + + "github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus" + "github.com/Azure/go-autorest/autorest/azure/auth" + "github.com/golang/glog" +) + +type AzureMetricResponse struct { + Total int64 +} + +type AzureServiceBusSubscriptionClient interface { + GetAzureMetric(azMetricRequest AzureMetricRequest) (AzureMetricResponse, error) +} + +type servicebusSubscriptionsClient interface { + Get(ctx context.Context, resourceGroupName string, namespaceName string, topicName string, subscriptionName string) (result servicebus.SBSubscription, err error) +} + +type servicebusClient struct { + client servicebusSubscriptionsClient + DefaultSubscriptionID string +} + +func NewClient(defaultSubscriptionID string) AzureServiceBusSubscriptionClient { + glog.V(2).Info("Creating a new Azure Service Bus Subscriptions client") + client := servicebus.NewSubscriptionsClient(defaultSubscriptionID) + authorizer, err := auth.NewAuthorizerFromEnvironment() + if err == nil { + client.Authorizer = authorizer + } + + return &servicebusClient{ + client: client, + DefaultSubscriptionID: defaultSubscriptionID, + } +} + +func newClient(defaultsubscriptionID string, client servicebusSubscriptionsClient) servicebusClient { + return servicebusClient{ + client: client, + DefaultSubscriptionID: defaultsubscriptionID, + } +} + +func (c *servicebusClient) GetAzureMetric(azMetricRequest AzureMetricRequest) (AzureMetricResponse, error) { + glog.V(6).Infof("Received metric request:\n%v", azMetricRequest) + err := azMetricRequest.Validate() + if err != nil { + return AzureMetricResponse{}, err + } + + glog.V(2).Infof("Requesting Service Bus Subscription %s to topic %s in namespace %s from resource group %s", azMetricRequest.Subscription, azMetricRequest.Topic, azMetricRequest.Namespace, azMetricRequest.ResourceGroup) + subscriptionResult, err := c.client.Get( + context.Background(), + azMetricRequest.ResourceGroup, + azMetricRequest.Namespace, + azMetricRequest.Topic, + azMetricRequest.Subscription, + ) + if err != nil { + return AzureMetricResponse{}, err + } + + glog.V(2).Infof("Successfully retrieved Service Bus Subscription %s to topic %s in namespace %s from resource group %s", azMetricRequest.Subscription, azMetricRequest.Topic, azMetricRequest.Namespace, azMetricRequest.ResourceGroup) + glog.V(6).Infof("%v", subscriptionResult.Response) + + activeMessageCount := *subscriptionResult.SBSubscriptionProperties.CountDetails.ActiveMessageCount + + glog.V(4).Infof("Service Bus Subscription active message count: %d", activeMessageCount) + + // TODO set Value based on aggregations type + return AzureMetricResponse{ + Total: activeMessageCount, + }, nil +} diff --git a/pkg/azure/servicebus/subscription_count_client_test.go b/pkg/azure/servicebus/subscription_count_client_test.go new file mode 100644 index 00000000..2fdd24f4 --- /dev/null +++ b/pkg/azure/servicebus/subscription_count_client_test.go @@ -0,0 +1,107 @@ +package servicebus + +import ( + "context" + "errors" + "testing" + + "github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus" +) + +func TestIfEmptyRequestGetError(t *testing.T) { + monitorClient := newFakeServicebusClient(servicebus.SBSubscription{}, nil) + + client := newClient("", monitorClient) + + request := AzureMetricRequest{} + _, err := client.GetAzureMetric(request) + + if err == nil { + t.Errorf("no error after processing got: %v, want error", nil) + } + + if !IsInvalidMetricRequestError(err) { + t.Errorf("should be InvalidMetricRequest error got %v, want InvalidMetricRequestError", err) + } +} + +func TestIfFailedResponseGetError(t *testing.T) { + fakeError := errors.New("fake servicebus failed") + serviceBusClient := newFakeServicebusClient(servicebus.SBSubscription{}, fakeError) + + client := newClient("", serviceBusClient) + + request := newMetricRequest() + _, err := client.GetAzureMetric(request) + + if err == nil { + t.Errorf("no error after processing got: %v, want error", nil) + } + + if err.Error() != fakeError.Error() { + t.Errorf("should be InvalidMetricRequest error got: %v, want: %v", err.Error(), fakeError.Error()) + } +} + +func TestIfValidRequestGetResult(t *testing.T) { + response := makeResponse(15) + serviceBusClient := newFakeServicebusClient(response, nil) + + client := newClient("", serviceBusClient) + + request := newMetricRequest() + metricResponse, err := client.GetAzureMetric(request) + + if err != nil { + t.Errorf("error after processing got: %v, want nil", err) + } + + if metricResponse.Total != 15 { + t.Errorf("metricResponse.Total = %v, want = %v", metricResponse.Total, 15) + } +} + +func makeResponse(value int64) servicebus.SBSubscription { + messageCountDetails := servicebus.MessageCountDetails{ + ActiveMessageCount: &value, + } + + subscriptionProperties := servicebus.SBSubscriptionProperties{ + CountDetails: &messageCountDetails, + } + + response := servicebus.SBSubscription{ + SBSubscriptionProperties: &subscriptionProperties, + } + + return response +} + +func newMetricRequest() AzureMetricRequest { + return AzureMetricRequest{ + ResourceGroup: "ResourceGroup", + SubscriptionID: "SubscriptionID", + MetricName: "MetricName", + Topic: "Topic", + Subscription: "Subscription", + Namespace: "Namespace", + } +} + +func newFakeServicebusClient(result servicebus.SBSubscription, err error) fakeServicebusClient { + return fakeServicebusClient{ + err: err, + result: result, + } +} + +type fakeServicebusClient struct { + result servicebus.SBSubscription + err error +} + +func (f fakeServicebusClient) Get(ctx context.Context, resourceGroupName string, namespaceName string, topicName string, subscriptionName string) (result servicebus.SBSubscription, err error) { + result = f.result + err = f.err + return +} From a4cc5b9d550fb6865252c47a899097cb7ba10cd6 Mon Sep 17 00:00:00 2001 From: Marc Sensenich Date: Sun, 18 Nov 2018 13:02:17 +0000 Subject: [PATCH 02/23] [GH-42] Add vendor packages for Service Bus --- .../mgmt/2017-04-01/servicebus/client.go | 51 + .../servicebus/disasterrecoveryconfigs.go | 923 ++++++ .../mgmt/2017-04-01/servicebus/eventhubs.go | 146 + .../2017-04-01/servicebus/migrationconfigs.go | 548 ++++ .../mgmt/2017-04-01/servicebus/models.go | 2912 +++++++++++++++++ .../mgmt/2017-04-01/servicebus/namespaces.go | 1146 +++++++ .../mgmt/2017-04-01/servicebus/operations.go | 126 + .../servicebus/premiummessagingregions.go | 130 + .../mgmt/2017-04-01/servicebus/queues.go | 958 ++++++ .../mgmt/2017-04-01/servicebus/regions.go | 141 + .../mgmt/2017-04-01/servicebus/rules.go | 450 +++ .../2017-04-01/servicebus/subscriptions.go | 430 +++ .../mgmt/2017-04-01/servicebus/topics.go | 958 ++++++ .../mgmt/2017-04-01/servicebus/version.go | 30 + 14 files changed, 8949 insertions(+) create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/disasterrecoveryconfigs.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/eventhubs.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/migrationconfigs.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/models.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/namespaces.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/operations.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/premiummessagingregions.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/queues.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/regions.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/rules.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/subscriptions.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/topics.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/version.go diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/client.go b/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/client.go new file mode 100644 index 00000000..d061bd5a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/client.go @@ -0,0 +1,51 @@ +// Package servicebus implements the Azure ARM Servicebus service API version 2017-04-01. +// +// Azure Service Bus client +package servicebus + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// 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 Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" +) + +const ( + // DefaultBaseURI is the default URI used for the service Servicebus + DefaultBaseURI = "https://management.azure.com" +) + +// BaseClient is the base client for Servicebus. +type BaseClient struct { + autorest.Client + BaseURI string + SubscriptionID string +} + +// New creates an instance of the BaseClient client. +func New(subscriptionID string) BaseClient { + return NewWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewWithBaseURI creates an instance of the BaseClient client. +func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient { + return BaseClient{ + Client: autorest.NewClientWithUserAgent(UserAgent()), + BaseURI: baseURI, + SubscriptionID: subscriptionID, + } +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/disasterrecoveryconfigs.go b/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/disasterrecoveryconfigs.go new file mode 100644 index 00000000..5c5ea8b8 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/disasterrecoveryconfigs.go @@ -0,0 +1,923 @@ +package servicebus + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// 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 Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "net/http" +) + +// DisasterRecoveryConfigsClient is the azure Service Bus client +type DisasterRecoveryConfigsClient struct { + BaseClient +} + +// NewDisasterRecoveryConfigsClient creates an instance of the DisasterRecoveryConfigsClient client. +func NewDisasterRecoveryConfigsClient(subscriptionID string) DisasterRecoveryConfigsClient { + return NewDisasterRecoveryConfigsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewDisasterRecoveryConfigsClientWithBaseURI creates an instance of the DisasterRecoveryConfigsClient client. +func NewDisasterRecoveryConfigsClientWithBaseURI(baseURI string, subscriptionID string) DisasterRecoveryConfigsClient { + return DisasterRecoveryConfigsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// BreakPairing this operation disables the Disaster Recovery and stops replicating changes from primary to secondary +// namespaces +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// alias - the Disaster Recovery configuration name +func (client DisasterRecoveryConfigsClient) BreakPairing(ctx context.Context, resourceGroupName string, namespaceName string, alias string) (result autorest.Response, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: alias, + Constraints: []validation.Constraint{{Target: "alias", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "alias", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.DisasterRecoveryConfigsClient", "BreakPairing", err.Error()) + } + + req, err := client.BreakPairingPreparer(ctx, resourceGroupName, namespaceName, alias) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.DisasterRecoveryConfigsClient", "BreakPairing", nil, "Failure preparing request") + return + } + + resp, err := client.BreakPairingSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "servicebus.DisasterRecoveryConfigsClient", "BreakPairing", resp, "Failure sending request") + return + } + + result, err = client.BreakPairingResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.DisasterRecoveryConfigsClient", "BreakPairing", resp, "Failure responding to request") + } + + return +} + +// BreakPairingPreparer prepares the BreakPairing request. +func (client DisasterRecoveryConfigsClient) BreakPairingPreparer(ctx context.Context, resourceGroupName string, namespaceName string, alias string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "alias": autorest.Encode("path", alias), + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/disasterRecoveryConfigs/{alias}/breakPairing", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// BreakPairingSender sends the BreakPairing request. The method will close the +// http.Response Body if it receives an error. +func (client DisasterRecoveryConfigsClient) BreakPairingSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// BreakPairingResponder handles the response to the BreakPairing request. The method always +// closes the http.Response Body. +func (client DisasterRecoveryConfigsClient) BreakPairingResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByClosing()) + result.Response = resp + return +} + +// CheckNameAvailabilityMethod check the give namespace name availability. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// parameters - parameters to check availability of the given namespace name +func (client DisasterRecoveryConfigsClient) CheckNameAvailabilityMethod(ctx context.Context, resourceGroupName string, namespaceName string, parameters CheckNameAvailability) (result CheckNameAvailabilityResult, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.Name", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.DisasterRecoveryConfigsClient", "CheckNameAvailabilityMethod", err.Error()) + } + + req, err := client.CheckNameAvailabilityMethodPreparer(ctx, resourceGroupName, namespaceName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.DisasterRecoveryConfigsClient", "CheckNameAvailabilityMethod", nil, "Failure preparing request") + return + } + + resp, err := client.CheckNameAvailabilityMethodSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.DisasterRecoveryConfigsClient", "CheckNameAvailabilityMethod", resp, "Failure sending request") + return + } + + result, err = client.CheckNameAvailabilityMethodResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.DisasterRecoveryConfigsClient", "CheckNameAvailabilityMethod", resp, "Failure responding to request") + } + + return +} + +// CheckNameAvailabilityMethodPreparer prepares the CheckNameAvailabilityMethod request. +func (client DisasterRecoveryConfigsClient) CheckNameAvailabilityMethodPreparer(ctx context.Context, resourceGroupName string, namespaceName string, parameters CheckNameAvailability) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/disasterRecoveryConfigs/CheckNameAvailability", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CheckNameAvailabilityMethodSender sends the CheckNameAvailabilityMethod request. The method will close the +// http.Response Body if it receives an error. +func (client DisasterRecoveryConfigsClient) CheckNameAvailabilityMethodSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// CheckNameAvailabilityMethodResponder handles the response to the CheckNameAvailabilityMethod request. The method always +// closes the http.Response Body. +func (client DisasterRecoveryConfigsClient) CheckNameAvailabilityMethodResponder(resp *http.Response) (result CheckNameAvailabilityResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// CreateOrUpdate creates or updates a new Alias(Disaster Recovery configuration) +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// alias - the Disaster Recovery configuration name +// parameters - parameters required to create an Alias(Disaster Recovery configuration) +func (client DisasterRecoveryConfigsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, namespaceName string, alias string, parameters ArmDisasterRecovery) (result ArmDisasterRecovery, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: alias, + Constraints: []validation.Constraint{{Target: "alias", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "alias", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.DisasterRecoveryConfigsClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, namespaceName, alias, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.DisasterRecoveryConfigsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.DisasterRecoveryConfigsClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.DisasterRecoveryConfigsClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client DisasterRecoveryConfigsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, namespaceName string, alias string, parameters ArmDisasterRecovery) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "alias": autorest.Encode("path", alias), + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/disasterRecoveryConfigs/{alias}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client DisasterRecoveryConfigsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client DisasterRecoveryConfigsClient) CreateOrUpdateResponder(resp *http.Response) (result ArmDisasterRecovery, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes an Alias(Disaster Recovery configuration) +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// alias - the Disaster Recovery configuration name +func (client DisasterRecoveryConfigsClient) Delete(ctx context.Context, resourceGroupName string, namespaceName string, alias string) (result autorest.Response, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: alias, + Constraints: []validation.Constraint{{Target: "alias", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "alias", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.DisasterRecoveryConfigsClient", "Delete", err.Error()) + } + + req, err := client.DeletePreparer(ctx, resourceGroupName, namespaceName, alias) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.DisasterRecoveryConfigsClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "servicebus.DisasterRecoveryConfigsClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.DisasterRecoveryConfigsClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client DisasterRecoveryConfigsClient) DeletePreparer(ctx context.Context, resourceGroupName string, namespaceName string, alias string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "alias": autorest.Encode("path", alias), + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/disasterRecoveryConfigs/{alias}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client DisasterRecoveryConfigsClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client DisasterRecoveryConfigsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByClosing()) + result.Response = resp + return +} + +// FailOver envokes GEO DR failover and reconfigure the alias to point to the secondary namespace +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// alias - the Disaster Recovery configuration name +func (client DisasterRecoveryConfigsClient) FailOver(ctx context.Context, resourceGroupName string, namespaceName string, alias string) (result autorest.Response, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: alias, + Constraints: []validation.Constraint{{Target: "alias", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "alias", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.DisasterRecoveryConfigsClient", "FailOver", err.Error()) + } + + req, err := client.FailOverPreparer(ctx, resourceGroupName, namespaceName, alias) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.DisasterRecoveryConfigsClient", "FailOver", nil, "Failure preparing request") + return + } + + resp, err := client.FailOverSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "servicebus.DisasterRecoveryConfigsClient", "FailOver", resp, "Failure sending request") + return + } + + result, err = client.FailOverResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.DisasterRecoveryConfigsClient", "FailOver", resp, "Failure responding to request") + } + + return +} + +// FailOverPreparer prepares the FailOver request. +func (client DisasterRecoveryConfigsClient) FailOverPreparer(ctx context.Context, resourceGroupName string, namespaceName string, alias string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "alias": autorest.Encode("path", alias), + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/disasterRecoveryConfigs/{alias}/failover", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// FailOverSender sends the FailOver request. The method will close the +// http.Response Body if it receives an error. +func (client DisasterRecoveryConfigsClient) FailOverSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// FailOverResponder handles the response to the FailOver request. The method always +// closes the http.Response Body. +func (client DisasterRecoveryConfigsClient) FailOverResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get retrieves Alias(Disaster Recovery configuration) for primary or secondary namespace +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// alias - the Disaster Recovery configuration name +func (client DisasterRecoveryConfigsClient) Get(ctx context.Context, resourceGroupName string, namespaceName string, alias string) (result ArmDisasterRecovery, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: alias, + Constraints: []validation.Constraint{{Target: "alias", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "alias", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.DisasterRecoveryConfigsClient", "Get", err.Error()) + } + + req, err := client.GetPreparer(ctx, resourceGroupName, namespaceName, alias) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.DisasterRecoveryConfigsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.DisasterRecoveryConfigsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.DisasterRecoveryConfigsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client DisasterRecoveryConfigsClient) GetPreparer(ctx context.Context, resourceGroupName string, namespaceName string, alias string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "alias": autorest.Encode("path", alias), + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/disasterRecoveryConfigs/{alias}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client DisasterRecoveryConfigsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client DisasterRecoveryConfigsClient) GetResponder(resp *http.Response) (result ArmDisasterRecovery, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetAuthorizationRule gets an authorization rule for a namespace by rule name. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// alias - the Disaster Recovery configuration name +// authorizationRuleName - the authorizationrule name. +func (client DisasterRecoveryConfigsClient) GetAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, alias string, authorizationRuleName string) (result SBAuthorizationRule, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: alias, + Constraints: []validation.Constraint{{Target: "alias", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "alias", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: authorizationRuleName, + Constraints: []validation.Constraint{{Target: "authorizationRuleName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "authorizationRuleName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.DisasterRecoveryConfigsClient", "GetAuthorizationRule", err.Error()) + } + + req, err := client.GetAuthorizationRulePreparer(ctx, resourceGroupName, namespaceName, alias, authorizationRuleName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.DisasterRecoveryConfigsClient", "GetAuthorizationRule", nil, "Failure preparing request") + return + } + + resp, err := client.GetAuthorizationRuleSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.DisasterRecoveryConfigsClient", "GetAuthorizationRule", resp, "Failure sending request") + return + } + + result, err = client.GetAuthorizationRuleResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.DisasterRecoveryConfigsClient", "GetAuthorizationRule", resp, "Failure responding to request") + } + + return +} + +// GetAuthorizationRulePreparer prepares the GetAuthorizationRule request. +func (client DisasterRecoveryConfigsClient) GetAuthorizationRulePreparer(ctx context.Context, resourceGroupName string, namespaceName string, alias string, authorizationRuleName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "alias": autorest.Encode("path", alias), + "authorizationRuleName": autorest.Encode("path", authorizationRuleName), + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/disasterRecoveryConfigs/{alias}/AuthorizationRules/{authorizationRuleName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetAuthorizationRuleSender sends the GetAuthorizationRule request. The method will close the +// http.Response Body if it receives an error. +func (client DisasterRecoveryConfigsClient) GetAuthorizationRuleSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetAuthorizationRuleResponder handles the response to the GetAuthorizationRule request. The method always +// closes the http.Response Body. +func (client DisasterRecoveryConfigsClient) GetAuthorizationRuleResponder(resp *http.Response) (result SBAuthorizationRule, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List gets all Alias(Disaster Recovery configurations) +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +func (client DisasterRecoveryConfigsClient) List(ctx context.Context, resourceGroupName string, namespaceName string) (result ArmDisasterRecoveryListResultPage, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.DisasterRecoveryConfigsClient", "List", err.Error()) + } + + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, namespaceName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.DisasterRecoveryConfigsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.adrlr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.DisasterRecoveryConfigsClient", "List", resp, "Failure sending request") + return + } + + result.adrlr, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.DisasterRecoveryConfigsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client DisasterRecoveryConfigsClient) ListPreparer(ctx context.Context, resourceGroupName string, namespaceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/disasterRecoveryConfigs", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client DisasterRecoveryConfigsClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client DisasterRecoveryConfigsClient) ListResponder(resp *http.Response) (result ArmDisasterRecoveryListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listNextResults retrieves the next set of results, if any. +func (client DisasterRecoveryConfigsClient) listNextResults(lastResults ArmDisasterRecoveryListResult) (result ArmDisasterRecoveryListResult, err error) { + req, err := lastResults.armDisasterRecoveryListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "servicebus.DisasterRecoveryConfigsClient", "listNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "servicebus.DisasterRecoveryConfigsClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.DisasterRecoveryConfigsClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client DisasterRecoveryConfigsClient) ListComplete(ctx context.Context, resourceGroupName string, namespaceName string) (result ArmDisasterRecoveryListResultIterator, err error) { + result.page, err = client.List(ctx, resourceGroupName, namespaceName) + return +} + +// ListAuthorizationRules gets the authorization rules for a namespace. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// alias - the Disaster Recovery configuration name +func (client DisasterRecoveryConfigsClient) ListAuthorizationRules(ctx context.Context, resourceGroupName string, namespaceName string, alias string) (result SBAuthorizationRuleListResultPage, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: alias, + Constraints: []validation.Constraint{{Target: "alias", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "alias", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.DisasterRecoveryConfigsClient", "ListAuthorizationRules", err.Error()) + } + + result.fn = client.listAuthorizationRulesNextResults + req, err := client.ListAuthorizationRulesPreparer(ctx, resourceGroupName, namespaceName, alias) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.DisasterRecoveryConfigsClient", "ListAuthorizationRules", nil, "Failure preparing request") + return + } + + resp, err := client.ListAuthorizationRulesSender(req) + if err != nil { + result.sarlr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.DisasterRecoveryConfigsClient", "ListAuthorizationRules", resp, "Failure sending request") + return + } + + result.sarlr, err = client.ListAuthorizationRulesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.DisasterRecoveryConfigsClient", "ListAuthorizationRules", resp, "Failure responding to request") + } + + return +} + +// ListAuthorizationRulesPreparer prepares the ListAuthorizationRules request. +func (client DisasterRecoveryConfigsClient) ListAuthorizationRulesPreparer(ctx context.Context, resourceGroupName string, namespaceName string, alias string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "alias": autorest.Encode("path", alias), + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/disasterRecoveryConfigs/{alias}/AuthorizationRules", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListAuthorizationRulesSender sends the ListAuthorizationRules request. The method will close the +// http.Response Body if it receives an error. +func (client DisasterRecoveryConfigsClient) ListAuthorizationRulesSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListAuthorizationRulesResponder handles the response to the ListAuthorizationRules request. The method always +// closes the http.Response Body. +func (client DisasterRecoveryConfigsClient) ListAuthorizationRulesResponder(resp *http.Response) (result SBAuthorizationRuleListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listAuthorizationRulesNextResults retrieves the next set of results, if any. +func (client DisasterRecoveryConfigsClient) listAuthorizationRulesNextResults(lastResults SBAuthorizationRuleListResult) (result SBAuthorizationRuleListResult, err error) { + req, err := lastResults.sBAuthorizationRuleListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "servicebus.DisasterRecoveryConfigsClient", "listAuthorizationRulesNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListAuthorizationRulesSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "servicebus.DisasterRecoveryConfigsClient", "listAuthorizationRulesNextResults", resp, "Failure sending next results request") + } + result, err = client.ListAuthorizationRulesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.DisasterRecoveryConfigsClient", "listAuthorizationRulesNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListAuthorizationRulesComplete enumerates all values, automatically crossing page boundaries as required. +func (client DisasterRecoveryConfigsClient) ListAuthorizationRulesComplete(ctx context.Context, resourceGroupName string, namespaceName string, alias string) (result SBAuthorizationRuleListResultIterator, err error) { + result.page, err = client.ListAuthorizationRules(ctx, resourceGroupName, namespaceName, alias) + return +} + +// ListKeys gets the primary and secondary connection strings for the namespace. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// alias - the Disaster Recovery configuration name +// authorizationRuleName - the authorizationrule name. +func (client DisasterRecoveryConfigsClient) ListKeys(ctx context.Context, resourceGroupName string, namespaceName string, alias string, authorizationRuleName string) (result AccessKeys, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: alias, + Constraints: []validation.Constraint{{Target: "alias", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "alias", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: authorizationRuleName, + Constraints: []validation.Constraint{{Target: "authorizationRuleName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "authorizationRuleName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.DisasterRecoveryConfigsClient", "ListKeys", err.Error()) + } + + req, err := client.ListKeysPreparer(ctx, resourceGroupName, namespaceName, alias, authorizationRuleName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.DisasterRecoveryConfigsClient", "ListKeys", nil, "Failure preparing request") + return + } + + resp, err := client.ListKeysSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.DisasterRecoveryConfigsClient", "ListKeys", resp, "Failure sending request") + return + } + + result, err = client.ListKeysResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.DisasterRecoveryConfigsClient", "ListKeys", resp, "Failure responding to request") + } + + return +} + +// ListKeysPreparer prepares the ListKeys request. +func (client DisasterRecoveryConfigsClient) ListKeysPreparer(ctx context.Context, resourceGroupName string, namespaceName string, alias string, authorizationRuleName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "alias": autorest.Encode("path", alias), + "authorizationRuleName": autorest.Encode("path", authorizationRuleName), + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/disasterRecoveryConfigs/{alias}/AuthorizationRules/{authorizationRuleName}/listKeys", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListKeysSender sends the ListKeys request. The method will close the +// http.Response Body if it receives an error. +func (client DisasterRecoveryConfigsClient) ListKeysSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListKeysResponder handles the response to the ListKeys request. The method always +// closes the http.Response Body. +func (client DisasterRecoveryConfigsClient) ListKeysResponder(resp *http.Response) (result AccessKeys, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/eventhubs.go b/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/eventhubs.go new file mode 100644 index 00000000..c0b9ea63 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/eventhubs.go @@ -0,0 +1,146 @@ +package servicebus + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// 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 Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "net/http" +) + +// EventHubsClient is the azure Service Bus client +type EventHubsClient struct { + BaseClient +} + +// NewEventHubsClient creates an instance of the EventHubsClient client. +func NewEventHubsClient(subscriptionID string) EventHubsClient { + return NewEventHubsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewEventHubsClientWithBaseURI creates an instance of the EventHubsClient client. +func NewEventHubsClientWithBaseURI(baseURI string, subscriptionID string) EventHubsClient { + return EventHubsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// ListByNamespace gets all the Event Hubs in a service bus Namespace. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +func (client EventHubsClient) ListByNamespace(ctx context.Context, resourceGroupName string, namespaceName string) (result EventHubListResultPage, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.EventHubsClient", "ListByNamespace", err.Error()) + } + + result.fn = client.listByNamespaceNextResults + req, err := client.ListByNamespacePreparer(ctx, resourceGroupName, namespaceName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.EventHubsClient", "ListByNamespace", nil, "Failure preparing request") + return + } + + resp, err := client.ListByNamespaceSender(req) + if err != nil { + result.ehlr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.EventHubsClient", "ListByNamespace", resp, "Failure sending request") + return + } + + result.ehlr, err = client.ListByNamespaceResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.EventHubsClient", "ListByNamespace", resp, "Failure responding to request") + } + + return +} + +// ListByNamespacePreparer prepares the ListByNamespace request. +func (client EventHubsClient) ListByNamespacePreparer(ctx context.Context, resourceGroupName string, namespaceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/eventhubs", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByNamespaceSender sends the ListByNamespace request. The method will close the +// http.Response Body if it receives an error. +func (client EventHubsClient) ListByNamespaceSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListByNamespaceResponder handles the response to the ListByNamespace request. The method always +// closes the http.Response Body. +func (client EventHubsClient) ListByNamespaceResponder(resp *http.Response) (result EventHubListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listByNamespaceNextResults retrieves the next set of results, if any. +func (client EventHubsClient) listByNamespaceNextResults(lastResults EventHubListResult) (result EventHubListResult, err error) { + req, err := lastResults.eventHubListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "servicebus.EventHubsClient", "listByNamespaceNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListByNamespaceSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "servicebus.EventHubsClient", "listByNamespaceNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByNamespaceResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.EventHubsClient", "listByNamespaceNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByNamespaceComplete enumerates all values, automatically crossing page boundaries as required. +func (client EventHubsClient) ListByNamespaceComplete(ctx context.Context, resourceGroupName string, namespaceName string) (result EventHubListResultIterator, err error) { + result.page, err = client.ListByNamespace(ctx, resourceGroupName, namespaceName) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/migrationconfigs.go b/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/migrationconfigs.go new file mode 100644 index 00000000..0849340f --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/migrationconfigs.go @@ -0,0 +1,548 @@ +package servicebus + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// 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 Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "net/http" +) + +// MigrationConfigsClient is the azure Service Bus client +type MigrationConfigsClient struct { + BaseClient +} + +// NewMigrationConfigsClient creates an instance of the MigrationConfigsClient client. +func NewMigrationConfigsClient(subscriptionID string) MigrationConfigsClient { + return NewMigrationConfigsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewMigrationConfigsClientWithBaseURI creates an instance of the MigrationConfigsClient client. +func NewMigrationConfigsClientWithBaseURI(baseURI string, subscriptionID string) MigrationConfigsClient { + return MigrationConfigsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CompleteMigration this operation Completes Migration of entities by pointing the connection strings to Premium +// namespace and any enties created after the operation will be under Premium Namespace. CompleteMigration operation +// will fail when entity migration is in-progress. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +func (client MigrationConfigsClient) CompleteMigration(ctx context.Context, resourceGroupName string, namespaceName string) (result autorest.Response, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.MigrationConfigsClient", "CompleteMigration", err.Error()) + } + + req, err := client.CompleteMigrationPreparer(ctx, resourceGroupName, namespaceName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.MigrationConfigsClient", "CompleteMigration", nil, "Failure preparing request") + return + } + + resp, err := client.CompleteMigrationSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "servicebus.MigrationConfigsClient", "CompleteMigration", resp, "Failure sending request") + return + } + + result, err = client.CompleteMigrationResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.MigrationConfigsClient", "CompleteMigration", resp, "Failure responding to request") + } + + return +} + +// CompleteMigrationPreparer prepares the CompleteMigration request. +func (client MigrationConfigsClient) CompleteMigrationPreparer(ctx context.Context, resourceGroupName string, namespaceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "configName": autorest.Encode("path", "$default"), + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/migrationConfigurations/{configName}/upgrade", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CompleteMigrationSender sends the CompleteMigration request. The method will close the +// http.Response Body if it receives an error. +func (client MigrationConfigsClient) CompleteMigrationSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// CompleteMigrationResponder handles the response to the CompleteMigration request. The method always +// closes the http.Response Body. +func (client MigrationConfigsClient) CompleteMigrationResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByClosing()) + result.Response = resp + return +} + +// CreateAndStartMigration creates Migration configuration and starts migration of enties from Standard to Premium +// namespace +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// parameters - parameters required to create Migration Configuration +func (client MigrationConfigsClient) CreateAndStartMigration(ctx context.Context, resourceGroupName string, namespaceName string, parameters MigrationConfigProperties) (result MigrationConfigsCreateAndStartMigrationFuture, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.MigrationConfigPropertiesProperties", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.MigrationConfigPropertiesProperties.TargetNamespace", Name: validation.Null, Rule: true, Chain: nil}, + {Target: "parameters.MigrationConfigPropertiesProperties.PostMigrationName", Name: validation.Null, Rule: true, Chain: nil}, + }}}}}); err != nil { + return result, validation.NewError("servicebus.MigrationConfigsClient", "CreateAndStartMigration", err.Error()) + } + + req, err := client.CreateAndStartMigrationPreparer(ctx, resourceGroupName, namespaceName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.MigrationConfigsClient", "CreateAndStartMigration", nil, "Failure preparing request") + return + } + + result, err = client.CreateAndStartMigrationSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.MigrationConfigsClient", "CreateAndStartMigration", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateAndStartMigrationPreparer prepares the CreateAndStartMigration request. +func (client MigrationConfigsClient) CreateAndStartMigrationPreparer(ctx context.Context, resourceGroupName string, namespaceName string, parameters MigrationConfigProperties) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "configName": autorest.Encode("path", "$default"), + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/migrationConfigurations/{configName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateAndStartMigrationSender sends the CreateAndStartMigration request. The method will close the +// http.Response Body if it receives an error. +func (client MigrationConfigsClient) CreateAndStartMigrationSender(req *http.Request) (future MigrationConfigsCreateAndStartMigrationFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// CreateAndStartMigrationResponder handles the response to the CreateAndStartMigration request. The method always +// closes the http.Response Body. +func (client MigrationConfigsClient) CreateAndStartMigrationResponder(resp *http.Response) (result MigrationConfigProperties, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes a MigrationConfiguration +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +func (client MigrationConfigsClient) Delete(ctx context.Context, resourceGroupName string, namespaceName string) (result autorest.Response, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.MigrationConfigsClient", "Delete", err.Error()) + } + + req, err := client.DeletePreparer(ctx, resourceGroupName, namespaceName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.MigrationConfigsClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "servicebus.MigrationConfigsClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.MigrationConfigsClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client MigrationConfigsClient) DeletePreparer(ctx context.Context, resourceGroupName string, namespaceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "configName": autorest.Encode("path", "$default"), + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/migrationConfigurations/{configName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client MigrationConfigsClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client MigrationConfigsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get retrieves Migration Config +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +func (client MigrationConfigsClient) Get(ctx context.Context, resourceGroupName string, namespaceName string) (result MigrationConfigProperties, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.MigrationConfigsClient", "Get", err.Error()) + } + + req, err := client.GetPreparer(ctx, resourceGroupName, namespaceName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.MigrationConfigsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.MigrationConfigsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.MigrationConfigsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client MigrationConfigsClient) GetPreparer(ctx context.Context, resourceGroupName string, namespaceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "configName": autorest.Encode("path", "$default"), + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/migrationConfigurations/{configName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client MigrationConfigsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client MigrationConfigsClient) GetResponder(resp *http.Response) (result MigrationConfigProperties, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List gets all migrationConfigurations +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +func (client MigrationConfigsClient) List(ctx context.Context, resourceGroupName string, namespaceName string) (result MigrationConfigListResultPage, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.MigrationConfigsClient", "List", err.Error()) + } + + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx, resourceGroupName, namespaceName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.MigrationConfigsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.mclr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.MigrationConfigsClient", "List", resp, "Failure sending request") + return + } + + result.mclr, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.MigrationConfigsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client MigrationConfigsClient) ListPreparer(ctx context.Context, resourceGroupName string, namespaceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/migrationConfigurations", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client MigrationConfigsClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client MigrationConfigsClient) ListResponder(resp *http.Response) (result MigrationConfigListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listNextResults retrieves the next set of results, if any. +func (client MigrationConfigsClient) listNextResults(lastResults MigrationConfigListResult) (result MigrationConfigListResult, err error) { + req, err := lastResults.migrationConfigListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "servicebus.MigrationConfigsClient", "listNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "servicebus.MigrationConfigsClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.MigrationConfigsClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client MigrationConfigsClient) ListComplete(ctx context.Context, resourceGroupName string, namespaceName string) (result MigrationConfigListResultIterator, err error) { + result.page, err = client.List(ctx, resourceGroupName, namespaceName) + return +} + +// Revert this operation reverts Migration +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +func (client MigrationConfigsClient) Revert(ctx context.Context, resourceGroupName string, namespaceName string) (result autorest.Response, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.MigrationConfigsClient", "Revert", err.Error()) + } + + req, err := client.RevertPreparer(ctx, resourceGroupName, namespaceName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.MigrationConfigsClient", "Revert", nil, "Failure preparing request") + return + } + + resp, err := client.RevertSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "servicebus.MigrationConfigsClient", "Revert", resp, "Failure sending request") + return + } + + result, err = client.RevertResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.MigrationConfigsClient", "Revert", resp, "Failure responding to request") + } + + return +} + +// RevertPreparer prepares the Revert request. +func (client MigrationConfigsClient) RevertPreparer(ctx context.Context, resourceGroupName string, namespaceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "configName": autorest.Encode("path", "$default"), + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/migrationConfigurations/{configName}/revert", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// RevertSender sends the Revert request. The method will close the +// http.Response Body if it receives an error. +func (client MigrationConfigsClient) RevertSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// RevertResponder handles the response to the Revert request. The method always +// closes the http.Response Body. +func (client MigrationConfigsClient) RevertResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByClosing()) + result.Response = resp + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/models.go b/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/models.go new file mode 100644 index 00000000..be823f3a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/models.go @@ -0,0 +1,2912 @@ +package servicebus + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// 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 Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "encoding/json" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/date" + "github.com/Azure/go-autorest/autorest/to" + "net/http" +) + +// AccessRights enumerates the values for access rights. +type AccessRights string + +const ( + // Listen ... + Listen AccessRights = "Listen" + // Manage ... + Manage AccessRights = "Manage" + // Send ... + Send AccessRights = "Send" +) + +// PossibleAccessRightsValues returns an array of possible values for the AccessRights const type. +func PossibleAccessRightsValues() []AccessRights { + return []AccessRights{Listen, Manage, Send} +} + +// EncodingCaptureDescription enumerates the values for encoding capture description. +type EncodingCaptureDescription string + +const ( + // Avro ... + Avro EncodingCaptureDescription = "Avro" + // AvroDeflate ... + AvroDeflate EncodingCaptureDescription = "AvroDeflate" +) + +// PossibleEncodingCaptureDescriptionValues returns an array of possible values for the EncodingCaptureDescription const type. +func PossibleEncodingCaptureDescriptionValues() []EncodingCaptureDescription { + return []EncodingCaptureDescription{Avro, AvroDeflate} +} + +// EntityStatus enumerates the values for entity status. +type EntityStatus string + +const ( + // Active ... + Active EntityStatus = "Active" + // Creating ... + Creating EntityStatus = "Creating" + // Deleting ... + Deleting EntityStatus = "Deleting" + // Disabled ... + Disabled EntityStatus = "Disabled" + // ReceiveDisabled ... + ReceiveDisabled EntityStatus = "ReceiveDisabled" + // Renaming ... + Renaming EntityStatus = "Renaming" + // Restoring ... + Restoring EntityStatus = "Restoring" + // SendDisabled ... + SendDisabled EntityStatus = "SendDisabled" + // Unknown ... + Unknown EntityStatus = "Unknown" +) + +// PossibleEntityStatusValues returns an array of possible values for the EntityStatus const type. +func PossibleEntityStatusValues() []EntityStatus { + return []EntityStatus{Active, Creating, Deleting, Disabled, ReceiveDisabled, Renaming, Restoring, SendDisabled, Unknown} +} + +// FilterType enumerates the values for filter type. +type FilterType string + +const ( + // FilterTypeCorrelationFilter ... + FilterTypeCorrelationFilter FilterType = "CorrelationFilter" + // FilterTypeSQLFilter ... + FilterTypeSQLFilter FilterType = "SqlFilter" +) + +// PossibleFilterTypeValues returns an array of possible values for the FilterType const type. +func PossibleFilterTypeValues() []FilterType { + return []FilterType{FilterTypeCorrelationFilter, FilterTypeSQLFilter} +} + +// KeyType enumerates the values for key type. +type KeyType string + +const ( + // PrimaryKey ... + PrimaryKey KeyType = "PrimaryKey" + // SecondaryKey ... + SecondaryKey KeyType = "SecondaryKey" +) + +// PossibleKeyTypeValues returns an array of possible values for the KeyType const type. +func PossibleKeyTypeValues() []KeyType { + return []KeyType{PrimaryKey, SecondaryKey} +} + +// ProvisioningStateDR enumerates the values for provisioning state dr. +type ProvisioningStateDR string + +const ( + // Accepted ... + Accepted ProvisioningStateDR = "Accepted" + // Failed ... + Failed ProvisioningStateDR = "Failed" + // Succeeded ... + Succeeded ProvisioningStateDR = "Succeeded" +) + +// PossibleProvisioningStateDRValues returns an array of possible values for the ProvisioningStateDR const type. +func PossibleProvisioningStateDRValues() []ProvisioningStateDR { + return []ProvisioningStateDR{Accepted, Failed, Succeeded} +} + +// RoleDisasterRecovery enumerates the values for role disaster recovery. +type RoleDisasterRecovery string + +const ( + // Primary ... + Primary RoleDisasterRecovery = "Primary" + // PrimaryNotReplicating ... + PrimaryNotReplicating RoleDisasterRecovery = "PrimaryNotReplicating" + // Secondary ... + Secondary RoleDisasterRecovery = "Secondary" +) + +// PossibleRoleDisasterRecoveryValues returns an array of possible values for the RoleDisasterRecovery const type. +func PossibleRoleDisasterRecoveryValues() []RoleDisasterRecovery { + return []RoleDisasterRecovery{Primary, PrimaryNotReplicating, Secondary} +} + +// SkuName enumerates the values for sku name. +type SkuName string + +const ( + // Basic ... + Basic SkuName = "Basic" + // Premium ... + Premium SkuName = "Premium" + // Standard ... + Standard SkuName = "Standard" +) + +// PossibleSkuNameValues returns an array of possible values for the SkuName const type. +func PossibleSkuNameValues() []SkuName { + return []SkuName{Basic, Premium, Standard} +} + +// SkuTier enumerates the values for sku tier. +type SkuTier string + +const ( + // SkuTierBasic ... + SkuTierBasic SkuTier = "Basic" + // SkuTierPremium ... + SkuTierPremium SkuTier = "Premium" + // SkuTierStandard ... + SkuTierStandard SkuTier = "Standard" +) + +// PossibleSkuTierValues returns an array of possible values for the SkuTier const type. +func PossibleSkuTierValues() []SkuTier { + return []SkuTier{SkuTierBasic, SkuTierPremium, SkuTierStandard} +} + +// UnavailableReason enumerates the values for unavailable reason. +type UnavailableReason string + +const ( + // InvalidName ... + InvalidName UnavailableReason = "InvalidName" + // NameInLockdown ... + NameInLockdown UnavailableReason = "NameInLockdown" + // NameInUse ... + NameInUse UnavailableReason = "NameInUse" + // None ... + None UnavailableReason = "None" + // SubscriptionIsDisabled ... + SubscriptionIsDisabled UnavailableReason = "SubscriptionIsDisabled" + // TooManyNamespaceInCurrentSubscription ... + TooManyNamespaceInCurrentSubscription UnavailableReason = "TooManyNamespaceInCurrentSubscription" +) + +// PossibleUnavailableReasonValues returns an array of possible values for the UnavailableReason const type. +func PossibleUnavailableReasonValues() []UnavailableReason { + return []UnavailableReason{InvalidName, NameInLockdown, NameInUse, None, SubscriptionIsDisabled, TooManyNamespaceInCurrentSubscription} +} + +// AccessKeys namespace/ServiceBus Connection String +type AccessKeys struct { + autorest.Response `json:"-"` + // PrimaryConnectionString - Primary connection string of the created namespace authorization rule. + PrimaryConnectionString *string `json:"primaryConnectionString,omitempty"` + // SecondaryConnectionString - Secondary connection string of the created namespace authorization rule. + SecondaryConnectionString *string `json:"secondaryConnectionString,omitempty"` + // AliasPrimaryConnectionString - Primary connection string of the alias if GEO DR is enabled + AliasPrimaryConnectionString *string `json:"aliasPrimaryConnectionString,omitempty"` + // AliasSecondaryConnectionString - Secondary connection string of the alias if GEO DR is enabled + AliasSecondaryConnectionString *string `json:"aliasSecondaryConnectionString,omitempty"` + // PrimaryKey - A base64-encoded 256-bit primary key for signing and validating the SAS token. + PrimaryKey *string `json:"primaryKey,omitempty"` + // SecondaryKey - A base64-encoded 256-bit primary key for signing and validating the SAS token. + SecondaryKey *string `json:"secondaryKey,omitempty"` + // KeyName - A string that describes the authorization rule. + KeyName *string `json:"keyName,omitempty"` +} + +// Action represents the filter actions which are allowed for the transformation of a message that have been +// matched by a filter expression. +type Action struct { + // SQLExpression - SQL expression. e.g. MyProperty='ABC' + SQLExpression *string `json:"sqlExpression,omitempty"` + // CompatibilityLevel - This property is reserved for future use. An integer value showing the compatibility level, currently hard-coded to 20. + CompatibilityLevel *int32 `json:"compatibilityLevel,omitempty"` + // RequiresPreprocessing - Value that indicates whether the rule action requires preprocessing. + RequiresPreprocessing *bool `json:"requiresPreprocessing,omitempty"` +} + +// ArmDisasterRecovery single item in List or Get Alias(Disaster Recovery configuration) operation +type ArmDisasterRecovery struct { + autorest.Response `json:"-"` + // ArmDisasterRecoveryProperties - Properties required to the Create Or Update Alias(Disaster Recovery configurations) + *ArmDisasterRecoveryProperties `json:"properties,omitempty"` + // ID - Resource Id + ID *string `json:"id,omitempty"` + // Name - Resource name + Name *string `json:"name,omitempty"` + // Type - Resource type + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for ArmDisasterRecovery. +func (adr ArmDisasterRecovery) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if adr.ArmDisasterRecoveryProperties != nil { + objectMap["properties"] = adr.ArmDisasterRecoveryProperties + } + if adr.ID != nil { + objectMap["id"] = adr.ID + } + if adr.Name != nil { + objectMap["name"] = adr.Name + } + if adr.Type != nil { + objectMap["type"] = adr.Type + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for ArmDisasterRecovery struct. +func (adr *ArmDisasterRecovery) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "properties": + if v != nil { + var armDisasterRecoveryProperties ArmDisasterRecoveryProperties + err = json.Unmarshal(*v, &armDisasterRecoveryProperties) + if err != nil { + return err + } + adr.ArmDisasterRecoveryProperties = &armDisasterRecoveryProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + adr.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + adr.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + adr.Type = &typeVar + } + } + } + + return nil +} + +// ArmDisasterRecoveryListResult the result of the List Alias(Disaster Recovery configuration) operation. +type ArmDisasterRecoveryListResult struct { + autorest.Response `json:"-"` + // Value - List of Alias(Disaster Recovery configurations) + Value *[]ArmDisasterRecovery `json:"value,omitempty"` + // NextLink - Link to the next set of results. Not empty if Value contains incomplete list of Alias(Disaster Recovery configuration) + NextLink *string `json:"nextLink,omitempty"` +} + +// ArmDisasterRecoveryListResultIterator provides access to a complete listing of ArmDisasterRecovery values. +type ArmDisasterRecoveryListResultIterator struct { + i int + page ArmDisasterRecoveryListResultPage +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *ArmDisasterRecoveryListResultIterator) Next() error { + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err := iter.page.Next() + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter ArmDisasterRecoveryListResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter ArmDisasterRecoveryListResultIterator) Response() ArmDisasterRecoveryListResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter ArmDisasterRecoveryListResultIterator) Value() ArmDisasterRecovery { + if !iter.page.NotDone() { + return ArmDisasterRecovery{} + } + return iter.page.Values()[iter.i] +} + +// IsEmpty returns true if the ListResult contains no values. +func (adrlr ArmDisasterRecoveryListResult) IsEmpty() bool { + return adrlr.Value == nil || len(*adrlr.Value) == 0 +} + +// armDisasterRecoveryListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (adrlr ArmDisasterRecoveryListResult) armDisasterRecoveryListResultPreparer() (*http.Request, error) { + if adrlr.NextLink == nil || len(to.String(adrlr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(adrlr.NextLink))) +} + +// ArmDisasterRecoveryListResultPage contains a page of ArmDisasterRecovery values. +type ArmDisasterRecoveryListResultPage struct { + fn func(ArmDisasterRecoveryListResult) (ArmDisasterRecoveryListResult, error) + adrlr ArmDisasterRecoveryListResult +} + +// 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. +func (page *ArmDisasterRecoveryListResultPage) Next() error { + next, err := page.fn(page.adrlr) + if err != nil { + return err + } + page.adrlr = next + return nil +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page ArmDisasterRecoveryListResultPage) NotDone() bool { + return !page.adrlr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page ArmDisasterRecoveryListResultPage) Response() ArmDisasterRecoveryListResult { + return page.adrlr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page ArmDisasterRecoveryListResultPage) Values() []ArmDisasterRecovery { + if page.adrlr.IsEmpty() { + return nil + } + return *page.adrlr.Value +} + +// ArmDisasterRecoveryProperties properties required to the Create Or Update Alias(Disaster Recovery +// configurations) +type ArmDisasterRecoveryProperties struct { + // ProvisioningState - Provisioning state of the Alias(Disaster Recovery configuration) - possible values 'Accepted' or 'Succeeded' or 'Failed'. Possible values include: 'Accepted', 'Succeeded', 'Failed' + ProvisioningState ProvisioningStateDR `json:"provisioningState,omitempty"` + // PendingReplicationOperationsCount - Number of entities pending to be replicated. + PendingReplicationOperationsCount *int64 `json:"pendingReplicationOperationsCount,omitempty"` + // PartnerNamespace - ARM Id of the Primary/Secondary eventhub namespace name, which is part of GEO DR pairning + PartnerNamespace *string `json:"partnerNamespace,omitempty"` + // AlternateName - Primary/Secondary eventhub namespace name, which is part of GEO DR pairning + AlternateName *string `json:"alternateName,omitempty"` + // Role - role of namespace in GEO DR - possible values 'Primary' or 'PrimaryNotReplicating' or 'Secondary'. Possible values include: 'Primary', 'PrimaryNotReplicating', 'Secondary' + Role RoleDisasterRecovery `json:"role,omitempty"` +} + +// AuthorizationRuleProperties authorizationRule properties. +type AuthorizationRuleProperties struct { + // Rights - The rights associated with the rule. + Rights *[]AccessRights `json:"rights,omitempty"` +} + +// CaptureDescription properties to configure capture description for eventhub +type CaptureDescription struct { + // Enabled - A value that indicates whether capture description is enabled. + Enabled *bool `json:"enabled,omitempty"` + // Encoding - Enumerates the possible values for the encoding format of capture description. Possible values include: 'Avro', 'AvroDeflate' + Encoding EncodingCaptureDescription `json:"encoding,omitempty"` + // IntervalInSeconds - The time window allows you to set the frequency with which the capture to Azure Blobs will happen, value should between 60 to 900 seconds + IntervalInSeconds *int32 `json:"intervalInSeconds,omitempty"` + // SizeLimitInBytes - The size window defines the amount of data built up in your Event Hub before an capture operation, value should be between 10485760 and 524288000 bytes + SizeLimitInBytes *int32 `json:"sizeLimitInBytes,omitempty"` + // Destination - Properties of Destination where capture will be stored. (Storage Account, Blob Names) + Destination *Destination `json:"destination,omitempty"` +} + +// CheckNameAvailability description of a Check Name availability request properties. +type CheckNameAvailability struct { + // Name - The Name to check the namespce name availability and The namespace name can contain only letters, numbers, and hyphens. The namespace must start with a letter, and it must end with a letter or number. + Name *string `json:"name,omitempty"` +} + +// CheckNameAvailabilityResult description of a Check Name availability request properties. +type CheckNameAvailabilityResult struct { + autorest.Response `json:"-"` + // Message - The detailed info regarding the reason associated with the namespace. + Message *string `json:"message,omitempty"` + // NameAvailable - Value indicating namespace is availability, true if the namespace is available; otherwise, false. + NameAvailable *bool `json:"nameAvailable,omitempty"` + // Reason - The reason for unavailability of a namespace. Possible values include: 'None', 'InvalidName', 'SubscriptionIsDisabled', 'NameInUse', 'NameInLockdown', 'TooManyNamespaceInCurrentSubscription' + Reason UnavailableReason `json:"reason,omitempty"` +} + +// CorrelationFilter represents the correlation filter expression. +type CorrelationFilter struct { + // Properties - dictionary object for custom filters + Properties map[string]*string `json:"properties"` + // CorrelationID - Identifier of the correlation. + CorrelationID *string `json:"correlationId,omitempty"` + // MessageID - Identifier of the message. + MessageID *string `json:"messageId,omitempty"` + // To - Address to send to. + To *string `json:"to,omitempty"` + // ReplyTo - Address of the queue to reply to. + ReplyTo *string `json:"replyTo,omitempty"` + // Label - Application specific label. + Label *string `json:"label,omitempty"` + // SessionID - Session identifier. + SessionID *string `json:"sessionId,omitempty"` + // ReplyToSessionID - Session identifier to reply to. + ReplyToSessionID *string `json:"replyToSessionId,omitempty"` + // ContentType - Content type of the message. + ContentType *string `json:"contentType,omitempty"` + // RequiresPreprocessing - Value that indicates whether the rule action requires preprocessing. + RequiresPreprocessing *bool `json:"requiresPreprocessing,omitempty"` +} + +// MarshalJSON is the custom marshaler for CorrelationFilter. +func (cf CorrelationFilter) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if cf.Properties != nil { + objectMap["properties"] = cf.Properties + } + if cf.CorrelationID != nil { + objectMap["correlationId"] = cf.CorrelationID + } + if cf.MessageID != nil { + objectMap["messageId"] = cf.MessageID + } + if cf.To != nil { + objectMap["to"] = cf.To + } + if cf.ReplyTo != nil { + objectMap["replyTo"] = cf.ReplyTo + } + if cf.Label != nil { + objectMap["label"] = cf.Label + } + if cf.SessionID != nil { + objectMap["sessionId"] = cf.SessionID + } + if cf.ReplyToSessionID != nil { + objectMap["replyToSessionId"] = cf.ReplyToSessionID + } + if cf.ContentType != nil { + objectMap["contentType"] = cf.ContentType + } + if cf.RequiresPreprocessing != nil { + objectMap["requiresPreprocessing"] = cf.RequiresPreprocessing + } + return json.Marshal(objectMap) +} + +// Destination capture storage details for capture description +type Destination struct { + // Name - Name for capture destination + Name *string `json:"name,omitempty"` + // DestinationProperties - Properties describing the storage account, blob container and acrchive name format for capture destination + *DestinationProperties `json:"properties,omitempty"` +} + +// MarshalJSON is the custom marshaler for Destination. +func (d Destination) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if d.Name != nil { + objectMap["name"] = d.Name + } + if d.DestinationProperties != nil { + objectMap["properties"] = d.DestinationProperties + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for Destination struct. +func (d *Destination) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + d.Name = &name + } + case "properties": + if v != nil { + var destinationProperties DestinationProperties + err = json.Unmarshal(*v, &destinationProperties) + if err != nil { + return err + } + d.DestinationProperties = &destinationProperties + } + } + } + + return nil +} + +// DestinationProperties properties describing the storage account, blob container and acrchive name format for +// capture destination +type DestinationProperties struct { + // StorageAccountResourceID - Resource id of the storage account to be used to create the blobs + StorageAccountResourceID *string `json:"storageAccountResourceId,omitempty"` + // BlobContainer - Blob container Name + BlobContainer *string `json:"blobContainer,omitempty"` + // ArchiveNameFormat - Blob naming convention for archive, e.g. {Namespace}/{EventHub}/{PartitionId}/{Year}/{Month}/{Day}/{Hour}/{Minute}/{Second}. Here all the parameters (Namespace,EventHub .. etc) are mandatory irrespective of order + ArchiveNameFormat *string `json:"archiveNameFormat,omitempty"` +} + +// ErrorResponse error reponse indicates ServiceBus service is not able to process the incoming request. The reason +// is provided in the error message. +type ErrorResponse struct { + // Code - Error code. + Code *string `json:"code,omitempty"` + // Message - Error message indicating why the operation failed. + Message *string `json:"message,omitempty"` +} + +// Eventhub single item in List or Get Event Hub operation +type Eventhub struct { + // EventhubProperties - Properties supplied to the Create Or Update Event Hub operation. + *EventhubProperties `json:"properties,omitempty"` + // ID - Resource Id + ID *string `json:"id,omitempty"` + // Name - Resource name + Name *string `json:"name,omitempty"` + // Type - Resource type + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for Eventhub. +func (e Eventhub) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if e.EventhubProperties != nil { + objectMap["properties"] = e.EventhubProperties + } + if e.ID != nil { + objectMap["id"] = e.ID + } + if e.Name != nil { + objectMap["name"] = e.Name + } + if e.Type != nil { + objectMap["type"] = e.Type + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for Eventhub struct. +func (e *Eventhub) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "properties": + if v != nil { + var eventhubProperties EventhubProperties + err = json.Unmarshal(*v, &eventhubProperties) + if err != nil { + return err + } + e.EventhubProperties = &eventhubProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + e.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + e.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + e.Type = &typeVar + } + } + } + + return nil +} + +// EventHubListResult the result of the List EventHubs operation. +type EventHubListResult struct { + autorest.Response `json:"-"` + // Value - Result of the List EventHubs operation. + Value *[]Eventhub `json:"value,omitempty"` + // NextLink - Link to the next set of results. Not empty if Value contains incomplete list of EventHubs. + NextLink *string `json:"nextLink,omitempty"` +} + +// EventHubListResultIterator provides access to a complete listing of Eventhub values. +type EventHubListResultIterator struct { + i int + page EventHubListResultPage +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *EventHubListResultIterator) Next() error { + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err := iter.page.Next() + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter EventHubListResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter EventHubListResultIterator) Response() EventHubListResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter EventHubListResultIterator) Value() Eventhub { + if !iter.page.NotDone() { + return Eventhub{} + } + return iter.page.Values()[iter.i] +} + +// IsEmpty returns true if the ListResult contains no values. +func (ehlr EventHubListResult) IsEmpty() bool { + return ehlr.Value == nil || len(*ehlr.Value) == 0 +} + +// eventHubListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (ehlr EventHubListResult) eventHubListResultPreparer() (*http.Request, error) { + if ehlr.NextLink == nil || len(to.String(ehlr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(ehlr.NextLink))) +} + +// EventHubListResultPage contains a page of Eventhub values. +type EventHubListResultPage struct { + fn func(EventHubListResult) (EventHubListResult, error) + ehlr EventHubListResult +} + +// 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. +func (page *EventHubListResultPage) Next() error { + next, err := page.fn(page.ehlr) + if err != nil { + return err + } + page.ehlr = next + return nil +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page EventHubListResultPage) NotDone() bool { + return !page.ehlr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page EventHubListResultPage) Response() EventHubListResult { + return page.ehlr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page EventHubListResultPage) Values() []Eventhub { + if page.ehlr.IsEmpty() { + return nil + } + return *page.ehlr.Value +} + +// EventhubProperties properties supplied to the Create Or Update Event Hub operation. +type EventhubProperties struct { + // PartitionIds - Current number of shards on the Event Hub. + PartitionIds *[]string `json:"partitionIds,omitempty"` + // CreatedAt - Exact time the Event Hub was created. + CreatedAt *date.Time `json:"createdAt,omitempty"` + // UpdatedAt - The exact time the message was updated. + UpdatedAt *date.Time `json:"updatedAt,omitempty"` + // MessageRetentionInDays - Number of days to retain the events for this Event Hub, value should be 1 to 7 days + MessageRetentionInDays *int64 `json:"messageRetentionInDays,omitempty"` + // PartitionCount - Number of partitions created for the Event Hub, allowed values are from 1 to 32 partitions. + PartitionCount *int64 `json:"partitionCount,omitempty"` + // Status - Enumerates the possible values for the status of the Event Hub. Possible values include: 'Active', 'Disabled', 'Restoring', 'SendDisabled', 'ReceiveDisabled', 'Creating', 'Deleting', 'Renaming', 'Unknown' + Status EntityStatus `json:"status,omitempty"` + // CaptureDescription - Properties of capture description + CaptureDescription *CaptureDescription `json:"captureDescription,omitempty"` +} + +// MessageCountDetails message Count Details. +type MessageCountDetails struct { + // ActiveMessageCount - Number of active messages in the queue, topic, or subscription. + ActiveMessageCount *int64 `json:"activeMessageCount,omitempty"` + // DeadLetterMessageCount - Number of messages that are dead lettered. + DeadLetterMessageCount *int64 `json:"deadLetterMessageCount,omitempty"` + // ScheduledMessageCount - Number of scheduled messages. + ScheduledMessageCount *int64 `json:"scheduledMessageCount,omitempty"` + // TransferMessageCount - Number of messages transferred to another queue, topic, or subscription. + TransferMessageCount *int64 `json:"transferMessageCount,omitempty"` + // TransferDeadLetterMessageCount - Number of messages transferred into dead letters. + TransferDeadLetterMessageCount *int64 `json:"transferDeadLetterMessageCount,omitempty"` +} + +// MigrationConfigListResult the result of the List migrationConfigurations operation. +type MigrationConfigListResult struct { + autorest.Response `json:"-"` + // Value - List of Migration Configs + Value *[]MigrationConfigProperties `json:"value,omitempty"` + // NextLink - Link to the next set of results. Not empty if Value contains incomplete list of migrationConfigurations + NextLink *string `json:"nextLink,omitempty"` +} + +// MigrationConfigListResultIterator provides access to a complete listing of MigrationConfigProperties values. +type MigrationConfigListResultIterator struct { + i int + page MigrationConfigListResultPage +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *MigrationConfigListResultIterator) Next() error { + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err := iter.page.Next() + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter MigrationConfigListResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter MigrationConfigListResultIterator) Response() MigrationConfigListResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter MigrationConfigListResultIterator) Value() MigrationConfigProperties { + if !iter.page.NotDone() { + return MigrationConfigProperties{} + } + return iter.page.Values()[iter.i] +} + +// IsEmpty returns true if the ListResult contains no values. +func (mclr MigrationConfigListResult) IsEmpty() bool { + return mclr.Value == nil || len(*mclr.Value) == 0 +} + +// migrationConfigListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (mclr MigrationConfigListResult) migrationConfigListResultPreparer() (*http.Request, error) { + if mclr.NextLink == nil || len(to.String(mclr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(mclr.NextLink))) +} + +// MigrationConfigListResultPage contains a page of MigrationConfigProperties values. +type MigrationConfigListResultPage struct { + fn func(MigrationConfigListResult) (MigrationConfigListResult, error) + mclr MigrationConfigListResult +} + +// 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. +func (page *MigrationConfigListResultPage) Next() error { + next, err := page.fn(page.mclr) + if err != nil { + return err + } + page.mclr = next + return nil +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page MigrationConfigListResultPage) NotDone() bool { + return !page.mclr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page MigrationConfigListResultPage) Response() MigrationConfigListResult { + return page.mclr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page MigrationConfigListResultPage) Values() []MigrationConfigProperties { + if page.mclr.IsEmpty() { + return nil + } + return *page.mclr.Value +} + +// MigrationConfigProperties single item in List or Get Migration Config operation +type MigrationConfigProperties struct { + autorest.Response `json:"-"` + // MigrationConfigPropertiesProperties - Properties required to the Create Migration Configuration + *MigrationConfigPropertiesProperties `json:"properties,omitempty"` + // ID - Resource Id + ID *string `json:"id,omitempty"` + // Name - Resource name + Name *string `json:"name,omitempty"` + // Type - Resource type + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for MigrationConfigProperties. +func (mcp MigrationConfigProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if mcp.MigrationConfigPropertiesProperties != nil { + objectMap["properties"] = mcp.MigrationConfigPropertiesProperties + } + if mcp.ID != nil { + objectMap["id"] = mcp.ID + } + if mcp.Name != nil { + objectMap["name"] = mcp.Name + } + if mcp.Type != nil { + objectMap["type"] = mcp.Type + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for MigrationConfigProperties struct. +func (mcp *MigrationConfigProperties) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "properties": + if v != nil { + var migrationConfigPropertiesProperties MigrationConfigPropertiesProperties + err = json.Unmarshal(*v, &migrationConfigPropertiesProperties) + if err != nil { + return err + } + mcp.MigrationConfigPropertiesProperties = &migrationConfigPropertiesProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + mcp.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + mcp.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + mcp.Type = &typeVar + } + } + } + + return nil +} + +// MigrationConfigPropertiesProperties properties required to the Create Migration Configuration +type MigrationConfigPropertiesProperties struct { + // ProvisioningState - Provisioning state of Migration Configuration + ProvisioningState *string `json:"provisioningState,omitempty"` + // PendingReplicationOperationsCount - Number of entities pending to be replicated. + PendingReplicationOperationsCount *int64 `json:"pendingReplicationOperationsCount,omitempty"` + // TargetNamespace - Existing premium Namespace ARM Id name which has no entities, will be used for migration + TargetNamespace *string `json:"targetNamespace,omitempty"` + // PostMigrationName - Name to access Standard Namespace after migration + PostMigrationName *string `json:"postMigrationName,omitempty"` +} + +// MigrationConfigsCreateAndStartMigrationFuture an abstraction for monitoring and retrieving the results of a +// long-running operation. +type MigrationConfigsCreateAndStartMigrationFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *MigrationConfigsCreateAndStartMigrationFuture) Result(client MigrationConfigsClient) (mcp MigrationConfigProperties, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.MigrationConfigsCreateAndStartMigrationFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("servicebus.MigrationConfigsCreateAndStartMigrationFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if mcp.Response.Response, err = future.GetResult(sender); err == nil && mcp.Response.Response.StatusCode != http.StatusNoContent { + mcp, err = client.CreateAndStartMigrationResponder(mcp.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.MigrationConfigsCreateAndStartMigrationFuture", "Result", mcp.Response.Response, "Failure responding to request") + } + } + return +} + +// NamespacesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running +// operation. +type NamespacesCreateOrUpdateFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *NamespacesCreateOrUpdateFuture) Result(client NamespacesClient) (sn SBNamespace, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.NamespacesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("servicebus.NamespacesCreateOrUpdateFuture") + return + } + sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) + if sn.Response.Response, err = future.GetResult(sender); err == nil && sn.Response.Response.StatusCode != http.StatusNoContent { + sn, err = client.CreateOrUpdateResponder(sn.Response.Response) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.NamespacesCreateOrUpdateFuture", "Result", sn.Response.Response, "Failure responding to request") + } + } + return +} + +// NamespacesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running operation. +type NamespacesDeleteFuture struct { + azure.Future +} + +// Result returns the result of the asynchronous operation. +// If the operation has not completed it will return an error. +func (future *NamespacesDeleteFuture) Result(client NamespacesClient) (ar autorest.Response, err error) { + var done bool + done, err = future.Done(client) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.NamespacesDeleteFuture", "Result", future.Response(), "Polling failure") + return + } + if !done { + err = azure.NewAsyncOpIncompleteError("servicebus.NamespacesDeleteFuture") + return + } + ar.Response = future.Response() + return +} + +// Operation a ServiceBus REST API operation +type Operation struct { + // Name - Operation name: {provider}/{resource}/{operation} + Name *string `json:"name,omitempty"` + // Display - The object that represents the operation. + Display *OperationDisplay `json:"display,omitempty"` +} + +// OperationDisplay the object that represents the operation. +type OperationDisplay struct { + // Provider - Service provider: Microsoft.ServiceBus + Provider *string `json:"provider,omitempty"` + // Resource - Resource on which the operation is performed: Invoice, etc. + Resource *string `json:"resource,omitempty"` + // Operation - Operation type: Read, write, delete, etc. + Operation *string `json:"operation,omitempty"` +} + +// OperationListResult result of the request to list ServiceBus operations. It contains a list of operations and a +// URL link to get the next set of results. +type OperationListResult struct { + autorest.Response `json:"-"` + // Value - List of ServiceBus operations supported by the Microsoft.ServiceBus resource provider. + Value *[]Operation `json:"value,omitempty"` + // NextLink - URL to get the next set of operation list results if there are any. + NextLink *string `json:"nextLink,omitempty"` +} + +// OperationListResultIterator provides access to a complete listing of Operation values. +type OperationListResultIterator struct { + i int + page OperationListResultPage +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *OperationListResultIterator) Next() error { + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err := iter.page.Next() + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter OperationListResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter OperationListResultIterator) Response() OperationListResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter OperationListResultIterator) Value() Operation { + if !iter.page.NotDone() { + return Operation{} + } + return iter.page.Values()[iter.i] +} + +// IsEmpty returns true if the ListResult contains no values. +func (olr OperationListResult) IsEmpty() bool { + return olr.Value == nil || len(*olr.Value) == 0 +} + +// operationListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (olr OperationListResult) operationListResultPreparer() (*http.Request, error) { + if olr.NextLink == nil || len(to.String(olr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(olr.NextLink))) +} + +// OperationListResultPage contains a page of Operation values. +type OperationListResultPage struct { + fn func(OperationListResult) (OperationListResult, error) + olr OperationListResult +} + +// 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. +func (page *OperationListResultPage) Next() error { + next, err := page.fn(page.olr) + if err != nil { + return err + } + page.olr = next + return nil +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page OperationListResultPage) NotDone() bool { + return !page.olr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page OperationListResultPage) Response() OperationListResult { + return page.olr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page OperationListResultPage) Values() []Operation { + if page.olr.IsEmpty() { + return nil + } + return *page.olr.Value +} + +// PremiumMessagingRegions premium Messaging Region +type PremiumMessagingRegions struct { + Properties *PremiumMessagingRegionsProperties `json:"properties,omitempty"` + // Location - Resource location + Location *string `json:"location,omitempty"` + // Tags - Resource tags + Tags map[string]*string `json:"tags"` + // ID - Resource Id + ID *string `json:"id,omitempty"` + // Name - Resource name + Name *string `json:"name,omitempty"` + // Type - Resource type + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for PremiumMessagingRegions. +func (pmr PremiumMessagingRegions) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if pmr.Properties != nil { + objectMap["properties"] = pmr.Properties + } + if pmr.Location != nil { + objectMap["location"] = pmr.Location + } + if pmr.Tags != nil { + objectMap["tags"] = pmr.Tags + } + if pmr.ID != nil { + objectMap["id"] = pmr.ID + } + if pmr.Name != nil { + objectMap["name"] = pmr.Name + } + if pmr.Type != nil { + objectMap["type"] = pmr.Type + } + return json.Marshal(objectMap) +} + +// PremiumMessagingRegionsListResult the response of the List PremiumMessagingRegions operation. +type PremiumMessagingRegionsListResult struct { + autorest.Response `json:"-"` + // Value - Result of the List PremiumMessagingRegions type. + Value *[]PremiumMessagingRegions `json:"value,omitempty"` + // NextLink - Link to the next set of results. Not empty if Value contains incomplete list of PremiumMessagingRegions. + NextLink *string `json:"nextLink,omitempty"` +} + +// PremiumMessagingRegionsListResultIterator provides access to a complete listing of PremiumMessagingRegions +// values. +type PremiumMessagingRegionsListResultIterator struct { + i int + page PremiumMessagingRegionsListResultPage +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *PremiumMessagingRegionsListResultIterator) Next() error { + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err := iter.page.Next() + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter PremiumMessagingRegionsListResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter PremiumMessagingRegionsListResultIterator) Response() PremiumMessagingRegionsListResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter PremiumMessagingRegionsListResultIterator) Value() PremiumMessagingRegions { + if !iter.page.NotDone() { + return PremiumMessagingRegions{} + } + return iter.page.Values()[iter.i] +} + +// IsEmpty returns true if the ListResult contains no values. +func (pmrlr PremiumMessagingRegionsListResult) IsEmpty() bool { + return pmrlr.Value == nil || len(*pmrlr.Value) == 0 +} + +// premiumMessagingRegionsListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (pmrlr PremiumMessagingRegionsListResult) premiumMessagingRegionsListResultPreparer() (*http.Request, error) { + if pmrlr.NextLink == nil || len(to.String(pmrlr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(pmrlr.NextLink))) +} + +// PremiumMessagingRegionsListResultPage contains a page of PremiumMessagingRegions values. +type PremiumMessagingRegionsListResultPage struct { + fn func(PremiumMessagingRegionsListResult) (PremiumMessagingRegionsListResult, error) + pmrlr PremiumMessagingRegionsListResult +} + +// 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. +func (page *PremiumMessagingRegionsListResultPage) Next() error { + next, err := page.fn(page.pmrlr) + if err != nil { + return err + } + page.pmrlr = next + return nil +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page PremiumMessagingRegionsListResultPage) NotDone() bool { + return !page.pmrlr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page PremiumMessagingRegionsListResultPage) Response() PremiumMessagingRegionsListResult { + return page.pmrlr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page PremiumMessagingRegionsListResultPage) Values() []PremiumMessagingRegions { + if page.pmrlr.IsEmpty() { + return nil + } + return *page.pmrlr.Value +} + +// PremiumMessagingRegionsProperties ... +type PremiumMessagingRegionsProperties struct { + // Code - Region code + Code *string `json:"code,omitempty"` + // FullName - Full name of the region + FullName *string `json:"fullName,omitempty"` +} + +// RegenerateAccessKeyParameters parameters supplied to the Regenerate Authorization Rule operation, specifies +// which key neeeds to be reset. +type RegenerateAccessKeyParameters struct { + // KeyType - The access key to regenerate. Possible values include: 'PrimaryKey', 'SecondaryKey' + KeyType KeyType `json:"keyType,omitempty"` + // Key - Optional, if the key value provided, is reset for KeyType value or autogenerate Key value set for keyType + Key *string `json:"key,omitempty"` +} + +// Resource the Resource definition for other than namespace. +type Resource struct { + // ID - Resource Id + ID *string `json:"id,omitempty"` + // Name - Resource name + Name *string `json:"name,omitempty"` + // Type - Resource type + Type *string `json:"type,omitempty"` +} + +// ResourceNamespacePatch the Resource definition. +type ResourceNamespacePatch struct { + // Location - Resource location + Location *string `json:"location,omitempty"` + // Tags - Resource tags + Tags map[string]*string `json:"tags"` + // ID - Resource Id + ID *string `json:"id,omitempty"` + // Name - Resource name + Name *string `json:"name,omitempty"` + // Type - Resource type + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for ResourceNamespacePatch. +func (rnp ResourceNamespacePatch) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if rnp.Location != nil { + objectMap["location"] = rnp.Location + } + if rnp.Tags != nil { + objectMap["tags"] = rnp.Tags + } + if rnp.ID != nil { + objectMap["id"] = rnp.ID + } + if rnp.Name != nil { + objectMap["name"] = rnp.Name + } + if rnp.Type != nil { + objectMap["type"] = rnp.Type + } + return json.Marshal(objectMap) +} + +// Rule description of Rule Resource. +type Rule struct { + autorest.Response `json:"-"` + // Ruleproperties - Properties of Rule resource + *Ruleproperties `json:"properties,omitempty"` + // ID - Resource Id + ID *string `json:"id,omitempty"` + // Name - Resource name + Name *string `json:"name,omitempty"` + // Type - Resource type + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for Rule. +func (r Rule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if r.Ruleproperties != nil { + objectMap["properties"] = r.Ruleproperties + } + if r.ID != nil { + objectMap["id"] = r.ID + } + if r.Name != nil { + objectMap["name"] = r.Name + } + if r.Type != nil { + objectMap["type"] = r.Type + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for Rule struct. +func (r *Rule) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "properties": + if v != nil { + var ruleproperties Ruleproperties + err = json.Unmarshal(*v, &ruleproperties) + if err != nil { + return err + } + r.Ruleproperties = &ruleproperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + r.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + r.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + r.Type = &typeVar + } + } + } + + return nil +} + +// RuleListResult the response of the List rule operation. +type RuleListResult struct { + autorest.Response `json:"-"` + // Value - Result of the List Rules operation. + Value *[]Rule `json:"value,omitempty"` + // NextLink - Link to the next set of results. Not empty if Value contains incomplete list of rules + NextLink *string `json:"nextLink,omitempty"` +} + +// RuleListResultIterator provides access to a complete listing of Rule values. +type RuleListResultIterator struct { + i int + page RuleListResultPage +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *RuleListResultIterator) Next() error { + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err := iter.page.Next() + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter RuleListResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter RuleListResultIterator) Response() RuleListResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter RuleListResultIterator) Value() Rule { + if !iter.page.NotDone() { + return Rule{} + } + return iter.page.Values()[iter.i] +} + +// IsEmpty returns true if the ListResult contains no values. +func (rlr RuleListResult) IsEmpty() bool { + return rlr.Value == nil || len(*rlr.Value) == 0 +} + +// ruleListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (rlr RuleListResult) ruleListResultPreparer() (*http.Request, error) { + if rlr.NextLink == nil || len(to.String(rlr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(rlr.NextLink))) +} + +// RuleListResultPage contains a page of Rule values. +type RuleListResultPage struct { + fn func(RuleListResult) (RuleListResult, error) + rlr RuleListResult +} + +// 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. +func (page *RuleListResultPage) Next() error { + next, err := page.fn(page.rlr) + if err != nil { + return err + } + page.rlr = next + return nil +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page RuleListResultPage) NotDone() bool { + return !page.rlr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page RuleListResultPage) Response() RuleListResult { + return page.rlr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page RuleListResultPage) Values() []Rule { + if page.rlr.IsEmpty() { + return nil + } + return *page.rlr.Value +} + +// Ruleproperties description of Rule Resource. +type Ruleproperties struct { + // Action - Represents the filter actions which are allowed for the transformation of a message that have been matched by a filter expression. + Action *Action `json:"action,omitempty"` + // FilterType - Filter type that is evaluated against a BrokeredMessage. Possible values include: 'FilterTypeSQLFilter', 'FilterTypeCorrelationFilter' + FilterType FilterType `json:"filterType,omitempty"` + // SQLFilter - Properties of sqlFilter + SQLFilter *SQLFilter `json:"sqlFilter,omitempty"` + // CorrelationFilter - Properties of correlationFilter + CorrelationFilter *CorrelationFilter `json:"correlationFilter,omitempty"` +} + +// SBAuthorizationRule description of a namespace authorization rule. +type SBAuthorizationRule struct { + autorest.Response `json:"-"` + // SBAuthorizationRuleProperties - AuthorizationRule properties. + *SBAuthorizationRuleProperties `json:"properties,omitempty"` + // ID - Resource Id + ID *string `json:"id,omitempty"` + // Name - Resource name + Name *string `json:"name,omitempty"` + // Type - Resource type + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for SBAuthorizationRule. +func (sar SBAuthorizationRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if sar.SBAuthorizationRuleProperties != nil { + objectMap["properties"] = sar.SBAuthorizationRuleProperties + } + if sar.ID != nil { + objectMap["id"] = sar.ID + } + if sar.Name != nil { + objectMap["name"] = sar.Name + } + if sar.Type != nil { + objectMap["type"] = sar.Type + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for SBAuthorizationRule struct. +func (sar *SBAuthorizationRule) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "properties": + if v != nil { + var sBAuthorizationRuleProperties SBAuthorizationRuleProperties + err = json.Unmarshal(*v, &sBAuthorizationRuleProperties) + if err != nil { + return err + } + sar.SBAuthorizationRuleProperties = &sBAuthorizationRuleProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + sar.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + sar.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + sar.Type = &typeVar + } + } + } + + return nil +} + +// SBAuthorizationRuleListResult the response to the List Namespace operation. +type SBAuthorizationRuleListResult struct { + autorest.Response `json:"-"` + // Value - Result of the List Authorization Rules operation. + Value *[]SBAuthorizationRule `json:"value,omitempty"` + // NextLink - Link to the next set of results. Not empty if Value contains incomplete list of Authorization Rules. + NextLink *string `json:"nextLink,omitempty"` +} + +// SBAuthorizationRuleListResultIterator provides access to a complete listing of SBAuthorizationRule values. +type SBAuthorizationRuleListResultIterator struct { + i int + page SBAuthorizationRuleListResultPage +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *SBAuthorizationRuleListResultIterator) Next() error { + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err := iter.page.Next() + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter SBAuthorizationRuleListResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter SBAuthorizationRuleListResultIterator) Response() SBAuthorizationRuleListResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter SBAuthorizationRuleListResultIterator) Value() SBAuthorizationRule { + if !iter.page.NotDone() { + return SBAuthorizationRule{} + } + return iter.page.Values()[iter.i] +} + +// IsEmpty returns true if the ListResult contains no values. +func (sarlr SBAuthorizationRuleListResult) IsEmpty() bool { + return sarlr.Value == nil || len(*sarlr.Value) == 0 +} + +// sBAuthorizationRuleListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (sarlr SBAuthorizationRuleListResult) sBAuthorizationRuleListResultPreparer() (*http.Request, error) { + if sarlr.NextLink == nil || len(to.String(sarlr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(sarlr.NextLink))) +} + +// SBAuthorizationRuleListResultPage contains a page of SBAuthorizationRule values. +type SBAuthorizationRuleListResultPage struct { + fn func(SBAuthorizationRuleListResult) (SBAuthorizationRuleListResult, error) + sarlr SBAuthorizationRuleListResult +} + +// 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. +func (page *SBAuthorizationRuleListResultPage) Next() error { + next, err := page.fn(page.sarlr) + if err != nil { + return err + } + page.sarlr = next + return nil +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page SBAuthorizationRuleListResultPage) NotDone() bool { + return !page.sarlr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page SBAuthorizationRuleListResultPage) Response() SBAuthorizationRuleListResult { + return page.sarlr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page SBAuthorizationRuleListResultPage) Values() []SBAuthorizationRule { + if page.sarlr.IsEmpty() { + return nil + } + return *page.sarlr.Value +} + +// SBAuthorizationRuleProperties authorizationRule properties. +type SBAuthorizationRuleProperties struct { + // Rights - The rights associated with the rule. + Rights *[]AccessRights `json:"rights,omitempty"` +} + +// SBNamespace description of a namespace resource. +type SBNamespace struct { + autorest.Response `json:"-"` + // Sku - Porperties of Sku + Sku *SBSku `json:"sku,omitempty"` + // SBNamespaceProperties - Properties of the namespace. + *SBNamespaceProperties `json:"properties,omitempty"` + // Location - The Geo-location where the resource lives + Location *string `json:"location,omitempty"` + // Tags - Resource tags + Tags map[string]*string `json:"tags"` + // ID - Resource Id + ID *string `json:"id,omitempty"` + // Name - Resource name + Name *string `json:"name,omitempty"` + // Type - Resource type + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for SBNamespace. +func (sn SBNamespace) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if sn.Sku != nil { + objectMap["sku"] = sn.Sku + } + if sn.SBNamespaceProperties != nil { + objectMap["properties"] = sn.SBNamespaceProperties + } + if sn.Location != nil { + objectMap["location"] = sn.Location + } + if sn.Tags != nil { + objectMap["tags"] = sn.Tags + } + if sn.ID != nil { + objectMap["id"] = sn.ID + } + if sn.Name != nil { + objectMap["name"] = sn.Name + } + if sn.Type != nil { + objectMap["type"] = sn.Type + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for SBNamespace struct. +func (sn *SBNamespace) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "sku": + if v != nil { + var sku SBSku + err = json.Unmarshal(*v, &sku) + if err != nil { + return err + } + sn.Sku = &sku + } + case "properties": + if v != nil { + var sBNamespaceProperties SBNamespaceProperties + err = json.Unmarshal(*v, &sBNamespaceProperties) + if err != nil { + return err + } + sn.SBNamespaceProperties = &sBNamespaceProperties + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + sn.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + sn.Tags = tags + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + sn.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + sn.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + sn.Type = &typeVar + } + } + } + + return nil +} + +// SBNamespaceListResult the response of the List Namespace operation. +type SBNamespaceListResult struct { + autorest.Response `json:"-"` + // Value - Result of the List Namespace operation. + Value *[]SBNamespace `json:"value,omitempty"` + // NextLink - Link to the next set of results. Not empty if Value contains incomplete list of Namespaces. + NextLink *string `json:"nextLink,omitempty"` +} + +// SBNamespaceListResultIterator provides access to a complete listing of SBNamespace values. +type SBNamespaceListResultIterator struct { + i int + page SBNamespaceListResultPage +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *SBNamespaceListResultIterator) Next() error { + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err := iter.page.Next() + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter SBNamespaceListResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter SBNamespaceListResultIterator) Response() SBNamespaceListResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter SBNamespaceListResultIterator) Value() SBNamespace { + if !iter.page.NotDone() { + return SBNamespace{} + } + return iter.page.Values()[iter.i] +} + +// IsEmpty returns true if the ListResult contains no values. +func (snlr SBNamespaceListResult) IsEmpty() bool { + return snlr.Value == nil || len(*snlr.Value) == 0 +} + +// sBNamespaceListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (snlr SBNamespaceListResult) sBNamespaceListResultPreparer() (*http.Request, error) { + if snlr.NextLink == nil || len(to.String(snlr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(snlr.NextLink))) +} + +// SBNamespaceListResultPage contains a page of SBNamespace values. +type SBNamespaceListResultPage struct { + fn func(SBNamespaceListResult) (SBNamespaceListResult, error) + snlr SBNamespaceListResult +} + +// 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. +func (page *SBNamespaceListResultPage) Next() error { + next, err := page.fn(page.snlr) + if err != nil { + return err + } + page.snlr = next + return nil +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page SBNamespaceListResultPage) NotDone() bool { + return !page.snlr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page SBNamespaceListResultPage) Response() SBNamespaceListResult { + return page.snlr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page SBNamespaceListResultPage) Values() []SBNamespace { + if page.snlr.IsEmpty() { + return nil + } + return *page.snlr.Value +} + +// SBNamespaceProperties properties of the namespace. +type SBNamespaceProperties struct { + // ProvisioningState - Provisioning state of the namespace. + ProvisioningState *string `json:"provisioningState,omitempty"` + // CreatedAt - The time the namespace was created. + CreatedAt *date.Time `json:"createdAt,omitempty"` + // UpdatedAt - The time the namespace was updated. + UpdatedAt *date.Time `json:"updatedAt,omitempty"` + // ServiceBusEndpoint - Endpoint you can use to perform Service Bus operations. + ServiceBusEndpoint *string `json:"serviceBusEndpoint,omitempty"` + // MetricID - Identifier for Azure Insights metrics + MetricID *string `json:"metricId,omitempty"` +} + +// SBNamespaceUpdateParameters description of a namespace resource. +type SBNamespaceUpdateParameters struct { + // Sku - Porperties of Sku + Sku *SBSku `json:"sku,omitempty"` + // SBNamespaceProperties - Properties of the namespace. + *SBNamespaceProperties `json:"properties,omitempty"` + // Location - Resource location + Location *string `json:"location,omitempty"` + // Tags - Resource tags + Tags map[string]*string `json:"tags"` + // ID - Resource Id + ID *string `json:"id,omitempty"` + // Name - Resource name + Name *string `json:"name,omitempty"` + // Type - Resource type + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for SBNamespaceUpdateParameters. +func (snup SBNamespaceUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if snup.Sku != nil { + objectMap["sku"] = snup.Sku + } + if snup.SBNamespaceProperties != nil { + objectMap["properties"] = snup.SBNamespaceProperties + } + if snup.Location != nil { + objectMap["location"] = snup.Location + } + if snup.Tags != nil { + objectMap["tags"] = snup.Tags + } + if snup.ID != nil { + objectMap["id"] = snup.ID + } + if snup.Name != nil { + objectMap["name"] = snup.Name + } + if snup.Type != nil { + objectMap["type"] = snup.Type + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for SBNamespaceUpdateParameters struct. +func (snup *SBNamespaceUpdateParameters) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "sku": + if v != nil { + var sku SBSku + err = json.Unmarshal(*v, &sku) + if err != nil { + return err + } + snup.Sku = &sku + } + case "properties": + if v != nil { + var sBNamespaceProperties SBNamespaceProperties + err = json.Unmarshal(*v, &sBNamespaceProperties) + if err != nil { + return err + } + snup.SBNamespaceProperties = &sBNamespaceProperties + } + case "location": + if v != nil { + var location string + err = json.Unmarshal(*v, &location) + if err != nil { + return err + } + snup.Location = &location + } + case "tags": + if v != nil { + var tags map[string]*string + err = json.Unmarshal(*v, &tags) + if err != nil { + return err + } + snup.Tags = tags + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + snup.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + snup.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + snup.Type = &typeVar + } + } + } + + return nil +} + +// SBQueue description of queue Resource. +type SBQueue struct { + autorest.Response `json:"-"` + // SBQueueProperties - Queue Properties + *SBQueueProperties `json:"properties,omitempty"` + // ID - Resource Id + ID *string `json:"id,omitempty"` + // Name - Resource name + Name *string `json:"name,omitempty"` + // Type - Resource type + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for SBQueue. +func (sq SBQueue) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if sq.SBQueueProperties != nil { + objectMap["properties"] = sq.SBQueueProperties + } + if sq.ID != nil { + objectMap["id"] = sq.ID + } + if sq.Name != nil { + objectMap["name"] = sq.Name + } + if sq.Type != nil { + objectMap["type"] = sq.Type + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for SBQueue struct. +func (sq *SBQueue) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "properties": + if v != nil { + var sBQueueProperties SBQueueProperties + err = json.Unmarshal(*v, &sBQueueProperties) + if err != nil { + return err + } + sq.SBQueueProperties = &sBQueueProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + sq.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + sq.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + sq.Type = &typeVar + } + } + } + + return nil +} + +// SBQueueListResult the response to the List Queues operation. +type SBQueueListResult struct { + autorest.Response `json:"-"` + // Value - Result of the List Queues operation. + Value *[]SBQueue `json:"value,omitempty"` + // NextLink - Link to the next set of results. Not empty if Value contains incomplete list of queues. + NextLink *string `json:"nextLink,omitempty"` +} + +// SBQueueListResultIterator provides access to a complete listing of SBQueue values. +type SBQueueListResultIterator struct { + i int + page SBQueueListResultPage +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *SBQueueListResultIterator) Next() error { + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err := iter.page.Next() + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter SBQueueListResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter SBQueueListResultIterator) Response() SBQueueListResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter SBQueueListResultIterator) Value() SBQueue { + if !iter.page.NotDone() { + return SBQueue{} + } + return iter.page.Values()[iter.i] +} + +// IsEmpty returns true if the ListResult contains no values. +func (sqlr SBQueueListResult) IsEmpty() bool { + return sqlr.Value == nil || len(*sqlr.Value) == 0 +} + +// sBQueueListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (sqlr SBQueueListResult) sBQueueListResultPreparer() (*http.Request, error) { + if sqlr.NextLink == nil || len(to.String(sqlr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(sqlr.NextLink))) +} + +// SBQueueListResultPage contains a page of SBQueue values. +type SBQueueListResultPage struct { + fn func(SBQueueListResult) (SBQueueListResult, error) + sqlr SBQueueListResult +} + +// 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. +func (page *SBQueueListResultPage) Next() error { + next, err := page.fn(page.sqlr) + if err != nil { + return err + } + page.sqlr = next + return nil +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page SBQueueListResultPage) NotDone() bool { + return !page.sqlr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page SBQueueListResultPage) Response() SBQueueListResult { + return page.sqlr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page SBQueueListResultPage) Values() []SBQueue { + if page.sqlr.IsEmpty() { + return nil + } + return *page.sqlr.Value +} + +// SBQueueProperties the Queue Properties definition. +type SBQueueProperties struct { + // CountDetails - Message Count Details. + CountDetails *MessageCountDetails `json:"countDetails,omitempty"` + // CreatedAt - The exact time the message was created. + CreatedAt *date.Time `json:"createdAt,omitempty"` + // UpdatedAt - The exact time the message was updated. + UpdatedAt *date.Time `json:"updatedAt,omitempty"` + // AccessedAt - Last time a message was sent, or the last time there was a receive request to this queue. + AccessedAt *date.Time `json:"accessedAt,omitempty"` + // SizeInBytes - The size of the queue, in bytes. + SizeInBytes *int64 `json:"sizeInBytes,omitempty"` + // MessageCount - The number of messages in the queue. + MessageCount *int64 `json:"messageCount,omitempty"` + // LockDuration - ISO 8601 timespan duration of a peek-lock; that is, the amount of time that the message is locked for other receivers. The maximum value for LockDuration is 5 minutes; the default value is 1 minute. + LockDuration *string `json:"lockDuration,omitempty"` + // MaxSizeInMegabytes - The maximum size of the queue in megabytes, which is the size of memory allocated for the queue. Default is 1024. + MaxSizeInMegabytes *int32 `json:"maxSizeInMegabytes,omitempty"` + // RequiresDuplicateDetection - A value indicating if this queue requires duplicate detection. + RequiresDuplicateDetection *bool `json:"requiresDuplicateDetection,omitempty"` + // RequiresSession - A value that indicates whether the queue supports the concept of sessions. + RequiresSession *bool `json:"requiresSession,omitempty"` + // DefaultMessageTimeToLive - ISO 8601 default message timespan to live value. This is the duration after which the message expires, starting from when the message is sent to Service Bus. This is the default value used when TimeToLive is not set on a message itself. + DefaultMessageTimeToLive *string `json:"defaultMessageTimeToLive,omitempty"` + // DeadLetteringOnMessageExpiration - A value that indicates whether this queue has dead letter support when a message expires. + DeadLetteringOnMessageExpiration *bool `json:"deadLetteringOnMessageExpiration,omitempty"` + // DuplicateDetectionHistoryTimeWindow - ISO 8601 timeSpan structure that defines the duration of the duplicate detection history. The default value is 10 minutes. + DuplicateDetectionHistoryTimeWindow *string `json:"duplicateDetectionHistoryTimeWindow,omitempty"` + // MaxDeliveryCount - The maximum delivery count. A message is automatically deadlettered after this number of deliveries. default value is 10. + MaxDeliveryCount *int32 `json:"maxDeliveryCount,omitempty"` + // Status - Enumerates the possible values for the status of a messaging entity. Possible values include: 'Active', 'Disabled', 'Restoring', 'SendDisabled', 'ReceiveDisabled', 'Creating', 'Deleting', 'Renaming', 'Unknown' + Status EntityStatus `json:"status,omitempty"` + // EnableBatchedOperations - Value that indicates whether server-side batched operations are enabled. + EnableBatchedOperations *bool `json:"enableBatchedOperations,omitempty"` + // AutoDeleteOnIdle - ISO 8061 timeSpan idle interval after which the queue is automatically deleted. The minimum duration is 5 minutes. + AutoDeleteOnIdle *string `json:"autoDeleteOnIdle,omitempty"` + // EnablePartitioning - A value that indicates whether the queue is to be partitioned across multiple message brokers. + EnablePartitioning *bool `json:"enablePartitioning,omitempty"` + // EnableExpress - A value that indicates whether Express Entities are enabled. An express queue holds a message in memory temporarily before writing it to persistent storage. + EnableExpress *bool `json:"enableExpress,omitempty"` + // ForwardTo - Queue/Topic name to forward the messages + ForwardTo *string `json:"forwardTo,omitempty"` + // ForwardDeadLetteredMessagesTo - Queue/Topic name to forward the Dead Letter message + ForwardDeadLetteredMessagesTo *string `json:"forwardDeadLetteredMessagesTo,omitempty"` +} + +// SBSku SKU of the namespace. +type SBSku struct { + // Name - Name of this SKU. Possible values include: 'Basic', 'Standard', 'Premium' + Name SkuName `json:"name,omitempty"` + // Tier - The billing tier of this particular SKU. Possible values include: 'SkuTierBasic', 'SkuTierStandard', 'SkuTierPremium' + Tier SkuTier `json:"tier,omitempty"` + // Capacity - The specified messaging units for the tier. For Premium tier, capacity are 1,2 and 4. + Capacity *int32 `json:"capacity,omitempty"` +} + +// SBSubscription description of subscription resource. +type SBSubscription struct { + autorest.Response `json:"-"` + // SBSubscriptionProperties - Properties of subscriptions resource. + *SBSubscriptionProperties `json:"properties,omitempty"` + // ID - Resource Id + ID *string `json:"id,omitempty"` + // Name - Resource name + Name *string `json:"name,omitempty"` + // Type - Resource type + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for SBSubscription. +func (ss SBSubscription) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if ss.SBSubscriptionProperties != nil { + objectMap["properties"] = ss.SBSubscriptionProperties + } + if ss.ID != nil { + objectMap["id"] = ss.ID + } + if ss.Name != nil { + objectMap["name"] = ss.Name + } + if ss.Type != nil { + objectMap["type"] = ss.Type + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for SBSubscription struct. +func (ss *SBSubscription) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "properties": + if v != nil { + var sBSubscriptionProperties SBSubscriptionProperties + err = json.Unmarshal(*v, &sBSubscriptionProperties) + if err != nil { + return err + } + ss.SBSubscriptionProperties = &sBSubscriptionProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + ss.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + ss.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + ss.Type = &typeVar + } + } + } + + return nil +} + +// SBSubscriptionListResult the response to the List Subscriptions operation. +type SBSubscriptionListResult struct { + autorest.Response `json:"-"` + // Value - Result of the List Subscriptions operation. + Value *[]SBSubscription `json:"value,omitempty"` + // NextLink - Link to the next set of results. Not empty if Value contains incomplete list of subscriptions. + NextLink *string `json:"nextLink,omitempty"` +} + +// SBSubscriptionListResultIterator provides access to a complete listing of SBSubscription values. +type SBSubscriptionListResultIterator struct { + i int + page SBSubscriptionListResultPage +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *SBSubscriptionListResultIterator) Next() error { + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err := iter.page.Next() + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter SBSubscriptionListResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter SBSubscriptionListResultIterator) Response() SBSubscriptionListResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter SBSubscriptionListResultIterator) Value() SBSubscription { + if !iter.page.NotDone() { + return SBSubscription{} + } + return iter.page.Values()[iter.i] +} + +// IsEmpty returns true if the ListResult contains no values. +func (sslr SBSubscriptionListResult) IsEmpty() bool { + return sslr.Value == nil || len(*sslr.Value) == 0 +} + +// sBSubscriptionListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (sslr SBSubscriptionListResult) sBSubscriptionListResultPreparer() (*http.Request, error) { + if sslr.NextLink == nil || len(to.String(sslr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(sslr.NextLink))) +} + +// SBSubscriptionListResultPage contains a page of SBSubscription values. +type SBSubscriptionListResultPage struct { + fn func(SBSubscriptionListResult) (SBSubscriptionListResult, error) + sslr SBSubscriptionListResult +} + +// 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. +func (page *SBSubscriptionListResultPage) Next() error { + next, err := page.fn(page.sslr) + if err != nil { + return err + } + page.sslr = next + return nil +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page SBSubscriptionListResultPage) NotDone() bool { + return !page.sslr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page SBSubscriptionListResultPage) Response() SBSubscriptionListResult { + return page.sslr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page SBSubscriptionListResultPage) Values() []SBSubscription { + if page.sslr.IsEmpty() { + return nil + } + return *page.sslr.Value +} + +// SBSubscriptionProperties description of Subscription Resource. +type SBSubscriptionProperties struct { + // MessageCount - Number of messages. + MessageCount *int64 `json:"messageCount,omitempty"` + // CreatedAt - Exact time the message was created. + CreatedAt *date.Time `json:"createdAt,omitempty"` + // AccessedAt - Last time there was a receive request to this subscription. + AccessedAt *date.Time `json:"accessedAt,omitempty"` + // UpdatedAt - The exact time the message was updated. + UpdatedAt *date.Time `json:"updatedAt,omitempty"` + // CountDetails - Message count details + CountDetails *MessageCountDetails `json:"countDetails,omitempty"` + // LockDuration - ISO 8061 lock duration timespan for the subscription. The default value is 1 minute. + LockDuration *string `json:"lockDuration,omitempty"` + // RequiresSession - Value indicating if a subscription supports the concept of sessions. + RequiresSession *bool `json:"requiresSession,omitempty"` + // DefaultMessageTimeToLive - ISO 8061 Default message timespan to live value. This is the duration after which the message expires, starting from when the message is sent to Service Bus. This is the default value used when TimeToLive is not set on a message itself. + DefaultMessageTimeToLive *string `json:"defaultMessageTimeToLive,omitempty"` + // DeadLetteringOnFilterEvaluationExceptions - Value that indicates whether a subscription has dead letter support on filter evaluation exceptions. + DeadLetteringOnFilterEvaluationExceptions *bool `json:"deadLetteringOnFilterEvaluationExceptions,omitempty"` + // DeadLetteringOnMessageExpiration - Value that indicates whether a subscription has dead letter support when a message expires. + DeadLetteringOnMessageExpiration *bool `json:"deadLetteringOnMessageExpiration,omitempty"` + // DuplicateDetectionHistoryTimeWindow - ISO 8601 timeSpan structure that defines the duration of the duplicate detection history. The default value is 10 minutes. + DuplicateDetectionHistoryTimeWindow *string `json:"duplicateDetectionHistoryTimeWindow,omitempty"` + // MaxDeliveryCount - Number of maximum deliveries. + MaxDeliveryCount *int32 `json:"maxDeliveryCount,omitempty"` + // Status - Enumerates the possible values for the status of a messaging entity. Possible values include: 'Active', 'Disabled', 'Restoring', 'SendDisabled', 'ReceiveDisabled', 'Creating', 'Deleting', 'Renaming', 'Unknown' + Status EntityStatus `json:"status,omitempty"` + // EnableBatchedOperations - Value that indicates whether server-side batched operations are enabled. + EnableBatchedOperations *bool `json:"enableBatchedOperations,omitempty"` + // AutoDeleteOnIdle - ISO 8061 timeSpan idle interval after which the topic is automatically deleted. The minimum duration is 5 minutes. + AutoDeleteOnIdle *string `json:"autoDeleteOnIdle,omitempty"` + // ForwardTo - Queue/Topic name to forward the messages + ForwardTo *string `json:"forwardTo,omitempty"` + // ForwardDeadLetteredMessagesTo - Queue/Topic name to forward the Dead Letter message + ForwardDeadLetteredMessagesTo *string `json:"forwardDeadLetteredMessagesTo,omitempty"` +} + +// SBTopic description of topic resource. +type SBTopic struct { + autorest.Response `json:"-"` + // SBTopicProperties - Properties of topic resource. + *SBTopicProperties `json:"properties,omitempty"` + // ID - Resource Id + ID *string `json:"id,omitempty"` + // Name - Resource name + Name *string `json:"name,omitempty"` + // Type - Resource type + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for SBTopic. +func (st SBTopic) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if st.SBTopicProperties != nil { + objectMap["properties"] = st.SBTopicProperties + } + if st.ID != nil { + objectMap["id"] = st.ID + } + if st.Name != nil { + objectMap["name"] = st.Name + } + if st.Type != nil { + objectMap["type"] = st.Type + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for SBTopic struct. +func (st *SBTopic) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "properties": + if v != nil { + var sBTopicProperties SBTopicProperties + err = json.Unmarshal(*v, &sBTopicProperties) + if err != nil { + return err + } + st.SBTopicProperties = &sBTopicProperties + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + st.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + st.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + st.Type = &typeVar + } + } + } + + return nil +} + +// SBTopicListResult the response to the List Topics operation. +type SBTopicListResult struct { + autorest.Response `json:"-"` + // Value - Result of the List Topics operation. + Value *[]SBTopic `json:"value,omitempty"` + // NextLink - Link to the next set of results. Not empty if Value contains incomplete list of topics. + NextLink *string `json:"nextLink,omitempty"` +} + +// SBTopicListResultIterator provides access to a complete listing of SBTopic values. +type SBTopicListResultIterator struct { + i int + page SBTopicListResultPage +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *SBTopicListResultIterator) Next() error { + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err := iter.page.Next() + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter SBTopicListResultIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter SBTopicListResultIterator) Response() SBTopicListResult { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter SBTopicListResultIterator) Value() SBTopic { + if !iter.page.NotDone() { + return SBTopic{} + } + return iter.page.Values()[iter.i] +} + +// IsEmpty returns true if the ListResult contains no values. +func (stlr SBTopicListResult) IsEmpty() bool { + return stlr.Value == nil || len(*stlr.Value) == 0 +} + +// sBTopicListResultPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (stlr SBTopicListResult) sBTopicListResultPreparer() (*http.Request, error) { + if stlr.NextLink == nil || len(to.String(stlr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(stlr.NextLink))) +} + +// SBTopicListResultPage contains a page of SBTopic values. +type SBTopicListResultPage struct { + fn func(SBTopicListResult) (SBTopicListResult, error) + stlr SBTopicListResult +} + +// 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. +func (page *SBTopicListResultPage) Next() error { + next, err := page.fn(page.stlr) + if err != nil { + return err + } + page.stlr = next + return nil +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page SBTopicListResultPage) NotDone() bool { + return !page.stlr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page SBTopicListResultPage) Response() SBTopicListResult { + return page.stlr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page SBTopicListResultPage) Values() []SBTopic { + if page.stlr.IsEmpty() { + return nil + } + return *page.stlr.Value +} + +// SBTopicProperties the Tpoic Properties definition. +type SBTopicProperties struct { + // SizeInBytes - Size of the topic, in bytes. + SizeInBytes *int64 `json:"sizeInBytes,omitempty"` + // CreatedAt - Exact time the message was created. + CreatedAt *date.Time `json:"createdAt,omitempty"` + // UpdatedAt - The exact time the message was updated. + UpdatedAt *date.Time `json:"updatedAt,omitempty"` + // AccessedAt - Last time the message was sent, or a request was received, for this topic. + AccessedAt *date.Time `json:"accessedAt,omitempty"` + // SubscriptionCount - Number of subscriptions. + SubscriptionCount *int32 `json:"subscriptionCount,omitempty"` + // CountDetails - Message count deatils + CountDetails *MessageCountDetails `json:"countDetails,omitempty"` + // DefaultMessageTimeToLive - ISO 8601 Default message timespan to live value. This is the duration after which the message expires, starting from when the message is sent to Service Bus. This is the default value used when TimeToLive is not set on a message itself. + DefaultMessageTimeToLive *string `json:"defaultMessageTimeToLive,omitempty"` + // MaxSizeInMegabytes - Maximum size of the topic in megabytes, which is the size of the memory allocated for the topic. Default is 1024. + MaxSizeInMegabytes *int32 `json:"maxSizeInMegabytes,omitempty"` + // RequiresDuplicateDetection - Value indicating if this topic requires duplicate detection. + RequiresDuplicateDetection *bool `json:"requiresDuplicateDetection,omitempty"` + // DuplicateDetectionHistoryTimeWindow - ISO8601 timespan structure that defines the duration of the duplicate detection history. The default value is 10 minutes. + DuplicateDetectionHistoryTimeWindow *string `json:"duplicateDetectionHistoryTimeWindow,omitempty"` + // EnableBatchedOperations - Value that indicates whether server-side batched operations are enabled. + EnableBatchedOperations *bool `json:"enableBatchedOperations,omitempty"` + // Status - Enumerates the possible values for the status of a messaging entity. Possible values include: 'Active', 'Disabled', 'Restoring', 'SendDisabled', 'ReceiveDisabled', 'Creating', 'Deleting', 'Renaming', 'Unknown' + Status EntityStatus `json:"status,omitempty"` + // SupportOrdering - Value that indicates whether the topic supports ordering. + SupportOrdering *bool `json:"supportOrdering,omitempty"` + // AutoDeleteOnIdle - ISO 8601 timespan idle interval after which the topic is automatically deleted. The minimum duration is 5 minutes. + AutoDeleteOnIdle *string `json:"autoDeleteOnIdle,omitempty"` + // EnablePartitioning - Value that indicates whether the topic to be partitioned across multiple message brokers is enabled. + EnablePartitioning *bool `json:"enablePartitioning,omitempty"` + // EnableExpress - Value that indicates whether Express Entities are enabled. An express topic holds a message in memory temporarily before writing it to persistent storage. + EnableExpress *bool `json:"enableExpress,omitempty"` +} + +// SQLFilter represents a filter which is a composition of an expression and an action that is executed in the +// pub/sub pipeline. +type SQLFilter struct { + // SQLExpression - The SQL expression. e.g. MyProperty='ABC' + SQLExpression *string `json:"sqlExpression,omitempty"` + // CompatibilityLevel - This property is reserved for future use. An integer value showing the compatibility level, currently hard-coded to 20. + CompatibilityLevel *int32 `json:"compatibilityLevel,omitempty"` + // RequiresPreprocessing - Value that indicates whether the rule action requires preprocessing. + RequiresPreprocessing *bool `json:"requiresPreprocessing,omitempty"` +} + +// SQLRuleAction represents set of actions written in SQL language-based syntax that is performed against a +// ServiceBus.Messaging.BrokeredMessage +type SQLRuleAction struct { + // SQLExpression - SQL expression. e.g. MyProperty='ABC' + SQLExpression *string `json:"sqlExpression,omitempty"` + // CompatibilityLevel - This property is reserved for future use. An integer value showing the compatibility level, currently hard-coded to 20. + CompatibilityLevel *int32 `json:"compatibilityLevel,omitempty"` + // RequiresPreprocessing - Value that indicates whether the rule action requires preprocessing. + RequiresPreprocessing *bool `json:"requiresPreprocessing,omitempty"` +} + +// TrackedResource the Resource definition. +type TrackedResource struct { + // Location - The Geo-location where the resource lives + Location *string `json:"location,omitempty"` + // Tags - Resource tags + Tags map[string]*string `json:"tags"` + // ID - Resource Id + ID *string `json:"id,omitempty"` + // Name - Resource name + Name *string `json:"name,omitempty"` + // Type - Resource type + Type *string `json:"type,omitempty"` +} + +// MarshalJSON is the custom marshaler for TrackedResource. +func (tr TrackedResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if tr.Location != nil { + objectMap["location"] = tr.Location + } + if tr.Tags != nil { + objectMap["tags"] = tr.Tags + } + if tr.ID != nil { + objectMap["id"] = tr.ID + } + if tr.Name != nil { + objectMap["name"] = tr.Name + } + if tr.Type != nil { + objectMap["type"] = tr.Type + } + return json.Marshal(objectMap) +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/namespaces.go b/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/namespaces.go new file mode 100644 index 00000000..1bbefa9b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/namespaces.go @@ -0,0 +1,1146 @@ +package servicebus + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// 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 Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "net/http" +) + +// NamespacesClient is the azure Service Bus client +type NamespacesClient struct { + BaseClient +} + +// NewNamespacesClient creates an instance of the NamespacesClient client. +func NewNamespacesClient(subscriptionID string) NamespacesClient { + return NewNamespacesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewNamespacesClientWithBaseURI creates an instance of the NamespacesClient client. +func NewNamespacesClientWithBaseURI(baseURI string, subscriptionID string) NamespacesClient { + return NamespacesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CheckNameAvailabilityMethod check the give namespace name availability. +// Parameters: +// parameters - parameters to check availability of the given namespace name +func (client NamespacesClient) CheckNameAvailabilityMethod(ctx context.Context, parameters CheckNameAvailability) (result CheckNameAvailabilityResult, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.Name", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.NamespacesClient", "CheckNameAvailabilityMethod", err.Error()) + } + + req, err := client.CheckNameAvailabilityMethodPreparer(ctx, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "CheckNameAvailabilityMethod", nil, "Failure preparing request") + return + } + + resp, err := client.CheckNameAvailabilityMethodSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "CheckNameAvailabilityMethod", resp, "Failure sending request") + return + } + + result, err = client.CheckNameAvailabilityMethodResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "CheckNameAvailabilityMethod", resp, "Failure responding to request") + } + + return +} + +// CheckNameAvailabilityMethodPreparer prepares the CheckNameAvailabilityMethod request. +func (client NamespacesClient) CheckNameAvailabilityMethodPreparer(ctx context.Context, parameters CheckNameAvailability) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.ServiceBus/CheckNameAvailability", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CheckNameAvailabilityMethodSender sends the CheckNameAvailabilityMethod request. The method will close the +// http.Response Body if it receives an error. +func (client NamespacesClient) CheckNameAvailabilityMethodSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// CheckNameAvailabilityMethodResponder handles the response to the CheckNameAvailabilityMethod request. The method always +// closes the http.Response Body. +func (client NamespacesClient) CheckNameAvailabilityMethodResponder(resp *http.Response) (result CheckNameAvailabilityResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// CreateOrUpdate creates or updates a service namespace. Once created, this namespace's resource manifest is +// immutable. This operation is idempotent. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name. +// parameters - parameters supplied to create a namespace resource. +func (client NamespacesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, namespaceName string, parameters SBNamespace) (result NamespacesCreateOrUpdateFuture, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.NamespacesClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, namespaceName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + result, err = client.CreateOrUpdateSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "CreateOrUpdate", result.Response(), "Failure sending request") + return + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client NamespacesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, namespaceName string, parameters SBNamespace) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client NamespacesClient) CreateOrUpdateSender(req *http.Request) (future NamespacesCreateOrUpdateFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client NamespacesClient) CreateOrUpdateResponder(resp *http.Response) (result SBNamespace, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// CreateOrUpdateAuthorizationRule creates or updates an authorization rule for a namespace. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// authorizationRuleName - the authorizationrule name. +// parameters - the shared access authorization rule. +func (client NamespacesClient) CreateOrUpdateAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, authorizationRuleName string, parameters SBAuthorizationRule) (result SBAuthorizationRule, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: authorizationRuleName, + Constraints: []validation.Constraint{{Target: "authorizationRuleName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "authorizationRuleName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.SBAuthorizationRuleProperties", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.SBAuthorizationRuleProperties.Rights", Name: validation.Null, Rule: true, Chain: nil}}}}}}); err != nil { + return result, validation.NewError("servicebus.NamespacesClient", "CreateOrUpdateAuthorizationRule", err.Error()) + } + + req, err := client.CreateOrUpdateAuthorizationRulePreparer(ctx, resourceGroupName, namespaceName, authorizationRuleName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "CreateOrUpdateAuthorizationRule", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateAuthorizationRuleSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "CreateOrUpdateAuthorizationRule", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateAuthorizationRuleResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "CreateOrUpdateAuthorizationRule", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdateAuthorizationRulePreparer prepares the CreateOrUpdateAuthorizationRule request. +func (client NamespacesClient) CreateOrUpdateAuthorizationRulePreparer(ctx context.Context, resourceGroupName string, namespaceName string, authorizationRuleName string, parameters SBAuthorizationRule) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "authorizationRuleName": autorest.Encode("path", authorizationRuleName), + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateOrUpdateAuthorizationRuleSender sends the CreateOrUpdateAuthorizationRule request. The method will close the +// http.Response Body if it receives an error. +func (client NamespacesClient) CreateOrUpdateAuthorizationRuleSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// CreateOrUpdateAuthorizationRuleResponder handles the response to the CreateOrUpdateAuthorizationRule request. The method always +// closes the http.Response Body. +func (client NamespacesClient) CreateOrUpdateAuthorizationRuleResponder(resp *http.Response) (result SBAuthorizationRule, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes an existing namespace. This operation also removes all associated resources under the namespace. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +func (client NamespacesClient) Delete(ctx context.Context, resourceGroupName string, namespaceName string) (result NamespacesDeleteFuture, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.NamespacesClient", "Delete", err.Error()) + } + + req, err := client.DeletePreparer(ctx, resourceGroupName, namespaceName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "Delete", nil, "Failure preparing request") + return + } + + result, err = client.DeleteSender(req) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "Delete", result.Response(), "Failure sending request") + return + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client NamespacesClient) DeletePreparer(ctx context.Context, resourceGroupName string, namespaceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client NamespacesClient) DeleteSender(req *http.Request) (future NamespacesDeleteFuture, err error) { + var resp *http.Response + resp, err = autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) + if err != nil { + return + } + err = autorest.Respond(resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent)) + if err != nil { + return + } + future.Future, err = azure.NewFutureFromResponse(resp) + return +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client NamespacesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// DeleteAuthorizationRule deletes a namespace authorization rule. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// authorizationRuleName - the authorizationrule name. +func (client NamespacesClient) DeleteAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, authorizationRuleName string) (result autorest.Response, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: authorizationRuleName, + Constraints: []validation.Constraint{{Target: "authorizationRuleName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "authorizationRuleName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.NamespacesClient", "DeleteAuthorizationRule", err.Error()) + } + + req, err := client.DeleteAuthorizationRulePreparer(ctx, resourceGroupName, namespaceName, authorizationRuleName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "DeleteAuthorizationRule", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteAuthorizationRuleSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "DeleteAuthorizationRule", resp, "Failure sending request") + return + } + + result, err = client.DeleteAuthorizationRuleResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "DeleteAuthorizationRule", resp, "Failure responding to request") + } + + return +} + +// DeleteAuthorizationRulePreparer prepares the DeleteAuthorizationRule request. +func (client NamespacesClient) DeleteAuthorizationRulePreparer(ctx context.Context, resourceGroupName string, namespaceName string, authorizationRuleName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "authorizationRuleName": autorest.Encode("path", authorizationRuleName), + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DeleteAuthorizationRuleSender sends the DeleteAuthorizationRule request. The method will close the +// http.Response Body if it receives an error. +func (client NamespacesClient) DeleteAuthorizationRuleSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// DeleteAuthorizationRuleResponder handles the response to the DeleteAuthorizationRule request. The method always +// closes the http.Response Body. +func (client NamespacesClient) DeleteAuthorizationRuleResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get gets a description for the specified namespace. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +func (client NamespacesClient) Get(ctx context.Context, resourceGroupName string, namespaceName string) (result SBNamespace, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.NamespacesClient", "Get", err.Error()) + } + + req, err := client.GetPreparer(ctx, resourceGroupName, namespaceName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client NamespacesClient) GetPreparer(ctx context.Context, resourceGroupName string, namespaceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client NamespacesClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client NamespacesClient) GetResponder(resp *http.Response) (result SBNamespace, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetAuthorizationRule gets an authorization rule for a namespace by rule name. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// authorizationRuleName - the authorizationrule name. +func (client NamespacesClient) GetAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, authorizationRuleName string) (result SBAuthorizationRule, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: authorizationRuleName, + Constraints: []validation.Constraint{{Target: "authorizationRuleName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "authorizationRuleName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.NamespacesClient", "GetAuthorizationRule", err.Error()) + } + + req, err := client.GetAuthorizationRulePreparer(ctx, resourceGroupName, namespaceName, authorizationRuleName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "GetAuthorizationRule", nil, "Failure preparing request") + return + } + + resp, err := client.GetAuthorizationRuleSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "GetAuthorizationRule", resp, "Failure sending request") + return + } + + result, err = client.GetAuthorizationRuleResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "GetAuthorizationRule", resp, "Failure responding to request") + } + + return +} + +// GetAuthorizationRulePreparer prepares the GetAuthorizationRule request. +func (client NamespacesClient) GetAuthorizationRulePreparer(ctx context.Context, resourceGroupName string, namespaceName string, authorizationRuleName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "authorizationRuleName": autorest.Encode("path", authorizationRuleName), + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetAuthorizationRuleSender sends the GetAuthorizationRule request. The method will close the +// http.Response Body if it receives an error. +func (client NamespacesClient) GetAuthorizationRuleSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetAuthorizationRuleResponder handles the response to the GetAuthorizationRule request. The method always +// closes the http.Response Body. +func (client NamespacesClient) GetAuthorizationRuleResponder(resp *http.Response) (result SBAuthorizationRule, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// List gets all the available namespaces within the subscription, irrespective of the resource groups. +func (client NamespacesClient) List(ctx context.Context) (result SBNamespaceListResultPage, err error) { + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.snlr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "List", resp, "Failure sending request") + return + } + + result.snlr, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client NamespacesClient) ListPreparer(ctx context.Context) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.ServiceBus/namespaces", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client NamespacesClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client NamespacesClient) ListResponder(resp *http.Response) (result SBNamespaceListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listNextResults retrieves the next set of results, if any. +func (client NamespacesClient) listNextResults(lastResults SBNamespaceListResult) (result SBNamespaceListResult, err error) { + req, err := lastResults.sBNamespaceListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "listNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client NamespacesClient) ListComplete(ctx context.Context) (result SBNamespaceListResultIterator, err error) { + result.page, err = client.List(ctx) + return +} + +// ListAuthorizationRules gets the authorization rules for a namespace. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +func (client NamespacesClient) ListAuthorizationRules(ctx context.Context, resourceGroupName string, namespaceName string) (result SBAuthorizationRuleListResultPage, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.NamespacesClient", "ListAuthorizationRules", err.Error()) + } + + result.fn = client.listAuthorizationRulesNextResults + req, err := client.ListAuthorizationRulesPreparer(ctx, resourceGroupName, namespaceName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "ListAuthorizationRules", nil, "Failure preparing request") + return + } + + resp, err := client.ListAuthorizationRulesSender(req) + if err != nil { + result.sarlr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "ListAuthorizationRules", resp, "Failure sending request") + return + } + + result.sarlr, err = client.ListAuthorizationRulesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "ListAuthorizationRules", resp, "Failure responding to request") + } + + return +} + +// ListAuthorizationRulesPreparer prepares the ListAuthorizationRules request. +func (client NamespacesClient) ListAuthorizationRulesPreparer(ctx context.Context, resourceGroupName string, namespaceName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/AuthorizationRules", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListAuthorizationRulesSender sends the ListAuthorizationRules request. The method will close the +// http.Response Body if it receives an error. +func (client NamespacesClient) ListAuthorizationRulesSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListAuthorizationRulesResponder handles the response to the ListAuthorizationRules request. The method always +// closes the http.Response Body. +func (client NamespacesClient) ListAuthorizationRulesResponder(resp *http.Response) (result SBAuthorizationRuleListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listAuthorizationRulesNextResults retrieves the next set of results, if any. +func (client NamespacesClient) listAuthorizationRulesNextResults(lastResults SBAuthorizationRuleListResult) (result SBAuthorizationRuleListResult, err error) { + req, err := lastResults.sBAuthorizationRuleListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "listAuthorizationRulesNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListAuthorizationRulesSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "listAuthorizationRulesNextResults", resp, "Failure sending next results request") + } + result, err = client.ListAuthorizationRulesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "listAuthorizationRulesNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListAuthorizationRulesComplete enumerates all values, automatically crossing page boundaries as required. +func (client NamespacesClient) ListAuthorizationRulesComplete(ctx context.Context, resourceGroupName string, namespaceName string) (result SBAuthorizationRuleListResultIterator, err error) { + result.page, err = client.ListAuthorizationRules(ctx, resourceGroupName, namespaceName) + return +} + +// ListByResourceGroup gets the available namespaces within a resource group. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +func (client NamespacesClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result SBNamespaceListResultPage, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.NamespacesClient", "ListByResourceGroup", err.Error()) + } + + result.fn = client.listByResourceGroupNextResults + req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "ListByResourceGroup", nil, "Failure preparing request") + return + } + + resp, err := client.ListByResourceGroupSender(req) + if err != nil { + result.snlr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "ListByResourceGroup", resp, "Failure sending request") + return + } + + result.snlr, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "ListByResourceGroup", resp, "Failure responding to request") + } + + return +} + +// ListByResourceGroupPreparer prepares the ListByResourceGroup request. +func (client NamespacesClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the +// http.Response Body if it receives an error. +func (client NamespacesClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always +// closes the http.Response Body. +func (client NamespacesClient) ListByResourceGroupResponder(resp *http.Response) (result SBNamespaceListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listByResourceGroupNextResults retrieves the next set of results, if any. +func (client NamespacesClient) listByResourceGroupNextResults(lastResults SBNamespaceListResult) (result SBNamespaceListResult, err error) { + req, err := lastResults.sBNamespaceListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListByResourceGroupSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. +func (client NamespacesClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result SBNamespaceListResultIterator, err error) { + result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) + return +} + +// ListKeys gets the primary and secondary connection strings for the namespace. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// authorizationRuleName - the authorizationrule name. +func (client NamespacesClient) ListKeys(ctx context.Context, resourceGroupName string, namespaceName string, authorizationRuleName string) (result AccessKeys, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: authorizationRuleName, + Constraints: []validation.Constraint{{Target: "authorizationRuleName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "authorizationRuleName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.NamespacesClient", "ListKeys", err.Error()) + } + + req, err := client.ListKeysPreparer(ctx, resourceGroupName, namespaceName, authorizationRuleName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "ListKeys", nil, "Failure preparing request") + return + } + + resp, err := client.ListKeysSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "ListKeys", resp, "Failure sending request") + return + } + + result, err = client.ListKeysResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "ListKeys", resp, "Failure responding to request") + } + + return +} + +// ListKeysPreparer prepares the ListKeys request. +func (client NamespacesClient) ListKeysPreparer(ctx context.Context, resourceGroupName string, namespaceName string, authorizationRuleName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "authorizationRuleName": autorest.Encode("path", authorizationRuleName), + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}/listKeys", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListKeysSender sends the ListKeys request. The method will close the +// http.Response Body if it receives an error. +func (client NamespacesClient) ListKeysSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListKeysResponder handles the response to the ListKeys request. The method always +// closes the http.Response Body. +func (client NamespacesClient) ListKeysResponder(resp *http.Response) (result AccessKeys, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// RegenerateKeys regenerates the primary or secondary connection strings for the namespace. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// authorizationRuleName - the authorizationrule name. +// parameters - parameters supplied to regenerate the authorization rule. +func (client NamespacesClient) RegenerateKeys(ctx context.Context, resourceGroupName string, namespaceName string, authorizationRuleName string, parameters RegenerateAccessKeyParameters) (result AccessKeys, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: authorizationRuleName, + Constraints: []validation.Constraint{{Target: "authorizationRuleName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "authorizationRuleName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.NamespacesClient", "RegenerateKeys", err.Error()) + } + + req, err := client.RegenerateKeysPreparer(ctx, resourceGroupName, namespaceName, authorizationRuleName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "RegenerateKeys", nil, "Failure preparing request") + return + } + + resp, err := client.RegenerateKeysSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "RegenerateKeys", resp, "Failure sending request") + return + } + + result, err = client.RegenerateKeysResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "RegenerateKeys", resp, "Failure responding to request") + } + + return +} + +// RegenerateKeysPreparer prepares the RegenerateKeys request. +func (client NamespacesClient) RegenerateKeysPreparer(ctx context.Context, resourceGroupName string, namespaceName string, authorizationRuleName string, parameters RegenerateAccessKeyParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "authorizationRuleName": autorest.Encode("path", authorizationRuleName), + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}/regenerateKeys", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// RegenerateKeysSender sends the RegenerateKeys request. The method will close the +// http.Response Body if it receives an error. +func (client NamespacesClient) RegenerateKeysSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// RegenerateKeysResponder handles the response to the RegenerateKeys request. The method always +// closes the http.Response Body. +func (client NamespacesClient) RegenerateKeysResponder(resp *http.Response) (result AccessKeys, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Update updates a service namespace. Once created, this namespace's resource manifest is immutable. This operation is +// idempotent. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// parameters - parameters supplied to update a namespace resource. +func (client NamespacesClient) Update(ctx context.Context, resourceGroupName string, namespaceName string, parameters SBNamespaceUpdateParameters) (result SBNamespace, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.NamespacesClient", "Update", err.Error()) + } + + req, err := client.UpdatePreparer(ctx, resourceGroupName, namespaceName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "Update", nil, "Failure preparing request") + return + } + + resp, err := client.UpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "Update", resp, "Failure sending request") + return + } + + result, err = client.UpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.NamespacesClient", "Update", resp, "Failure responding to request") + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client NamespacesClient) UpdatePreparer(ctx context.Context, resourceGroupName string, namespaceName string, parameters SBNamespaceUpdateParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// UpdateSender sends the Update request. The method will close the +// http.Response Body if it receives an error. +func (client NamespacesClient) UpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client NamespacesClient) UpdateResponder(resp *http.Response) (result SBNamespace, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/operations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/operations.go new file mode 100644 index 00000000..3de1195f --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/operations.go @@ -0,0 +1,126 @@ +package servicebus + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// 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 Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// OperationsClient is the azure Service Bus client +type OperationsClient struct { + BaseClient +} + +// NewOperationsClient creates an instance of the OperationsClient client. +func NewOperationsClient(subscriptionID string) OperationsClient { + return NewOperationsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewOperationsClientWithBaseURI creates an instance of the OperationsClient client. +func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient { + return OperationsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// List lists all of the available ServiceBus REST API operations. +func (client OperationsClient) List(ctx context.Context) (result OperationListResultPage, err error) { + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.OperationsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.olr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.OperationsClient", "List", resp, "Failure sending request") + return + } + + result.olr, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.OperationsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client OperationsClient) ListPreparer(ctx context.Context) (*http.Request, error) { + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPath("/providers/Microsoft.ServiceBus/operations"), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client OperationsClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client OperationsClient) ListResponder(resp *http.Response) (result OperationListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listNextResults retrieves the next set of results, if any. +func (client OperationsClient) listNextResults(lastResults OperationListResult) (result OperationListResult, err error) { + req, err := lastResults.operationListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "servicebus.OperationsClient", "listNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "servicebus.OperationsClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.OperationsClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client OperationsClient) ListComplete(ctx context.Context) (result OperationListResultIterator, err error) { + result.page, err = client.List(ctx) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/premiummessagingregions.go b/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/premiummessagingregions.go new file mode 100644 index 00000000..d7c02676 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/premiummessagingregions.go @@ -0,0 +1,130 @@ +package servicebus + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// 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 Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// PremiumMessagingRegionsClient is the azure Service Bus client +type PremiumMessagingRegionsClient struct { + BaseClient +} + +// NewPremiumMessagingRegionsClient creates an instance of the PremiumMessagingRegionsClient client. +func NewPremiumMessagingRegionsClient(subscriptionID string) PremiumMessagingRegionsClient { + return NewPremiumMessagingRegionsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewPremiumMessagingRegionsClientWithBaseURI creates an instance of the PremiumMessagingRegionsClient client. +func NewPremiumMessagingRegionsClientWithBaseURI(baseURI string, subscriptionID string) PremiumMessagingRegionsClient { + return PremiumMessagingRegionsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// List gets the available premium messaging regions for servicebus +func (client PremiumMessagingRegionsClient) List(ctx context.Context) (result PremiumMessagingRegionsListResultPage, err error) { + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.PremiumMessagingRegionsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.pmrlr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.PremiumMessagingRegionsClient", "List", resp, "Failure sending request") + return + } + + result.pmrlr, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.PremiumMessagingRegionsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client PremiumMessagingRegionsClient) ListPreparer(ctx context.Context) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.ServiceBus/premiumMessagingRegions", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client PremiumMessagingRegionsClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client PremiumMessagingRegionsClient) ListResponder(resp *http.Response) (result PremiumMessagingRegionsListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listNextResults retrieves the next set of results, if any. +func (client PremiumMessagingRegionsClient) listNextResults(lastResults PremiumMessagingRegionsListResult) (result PremiumMessagingRegionsListResult, err error) { + req, err := lastResults.premiumMessagingRegionsListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "servicebus.PremiumMessagingRegionsClient", "listNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "servicebus.PremiumMessagingRegionsClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.PremiumMessagingRegionsClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client PremiumMessagingRegionsClient) ListComplete(ctx context.Context) (result PremiumMessagingRegionsListResultIterator, err error) { + result.page, err = client.List(ctx) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/queues.go b/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/queues.go new file mode 100644 index 00000000..78843ee9 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/queues.go @@ -0,0 +1,958 @@ +package servicebus + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// 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 Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "net/http" +) + +// QueuesClient is the azure Service Bus client +type QueuesClient struct { + BaseClient +} + +// NewQueuesClient creates an instance of the QueuesClient client. +func NewQueuesClient(subscriptionID string) QueuesClient { + return NewQueuesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewQueuesClientWithBaseURI creates an instance of the QueuesClient client. +func NewQueuesClientWithBaseURI(baseURI string, subscriptionID string) QueuesClient { + return QueuesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate creates or updates a Service Bus queue. This operation is idempotent. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// queueName - the queue name. +// parameters - parameters supplied to create or update a queue resource. +func (client QueuesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, parameters SBQueue) (result SBQueue, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: queueName, + Constraints: []validation.Constraint{{Target: "queueName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.QueuesClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, namespaceName, queueName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client QueuesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, parameters SBQueue) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "namespaceName": autorest.Encode("path", namespaceName), + "queueName": autorest.Encode("path", queueName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/queues/{queueName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client QueuesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client QueuesClient) CreateOrUpdateResponder(resp *http.Response) (result SBQueue, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// CreateOrUpdateAuthorizationRule creates an authorization rule for a queue. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// queueName - the queue name. +// authorizationRuleName - the authorizationrule name. +// parameters - the shared access authorization rule. +func (client QueuesClient) CreateOrUpdateAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, authorizationRuleName string, parameters SBAuthorizationRule) (result SBAuthorizationRule, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: queueName, + Constraints: []validation.Constraint{{Target: "queueName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: authorizationRuleName, + Constraints: []validation.Constraint{{Target: "authorizationRuleName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "authorizationRuleName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.SBAuthorizationRuleProperties", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.SBAuthorizationRuleProperties.Rights", Name: validation.Null, Rule: true, Chain: nil}}}}}}); err != nil { + return result, validation.NewError("servicebus.QueuesClient", "CreateOrUpdateAuthorizationRule", err.Error()) + } + + req, err := client.CreateOrUpdateAuthorizationRulePreparer(ctx, resourceGroupName, namespaceName, queueName, authorizationRuleName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "CreateOrUpdateAuthorizationRule", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateAuthorizationRuleSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "CreateOrUpdateAuthorizationRule", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateAuthorizationRuleResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "CreateOrUpdateAuthorizationRule", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdateAuthorizationRulePreparer prepares the CreateOrUpdateAuthorizationRule request. +func (client QueuesClient) CreateOrUpdateAuthorizationRulePreparer(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, authorizationRuleName string, parameters SBAuthorizationRule) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "authorizationRuleName": autorest.Encode("path", authorizationRuleName), + "namespaceName": autorest.Encode("path", namespaceName), + "queueName": autorest.Encode("path", queueName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/queues/{queueName}/authorizationRules/{authorizationRuleName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateOrUpdateAuthorizationRuleSender sends the CreateOrUpdateAuthorizationRule request. The method will close the +// http.Response Body if it receives an error. +func (client QueuesClient) CreateOrUpdateAuthorizationRuleSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// CreateOrUpdateAuthorizationRuleResponder handles the response to the CreateOrUpdateAuthorizationRule request. The method always +// closes the http.Response Body. +func (client QueuesClient) CreateOrUpdateAuthorizationRuleResponder(resp *http.Response) (result SBAuthorizationRule, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes a queue from the specified namespace in a resource group. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// queueName - the queue name. +func (client QueuesClient) Delete(ctx context.Context, resourceGroupName string, namespaceName string, queueName string) (result autorest.Response, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: queueName, + Constraints: []validation.Constraint{{Target: "queueName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.QueuesClient", "Delete", err.Error()) + } + + req, err := client.DeletePreparer(ctx, resourceGroupName, namespaceName, queueName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client QueuesClient) DeletePreparer(ctx context.Context, resourceGroupName string, namespaceName string, queueName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "namespaceName": autorest.Encode("path", namespaceName), + "queueName": autorest.Encode("path", queueName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/queues/{queueName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client QueuesClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client QueuesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// DeleteAuthorizationRule deletes a queue authorization rule. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// queueName - the queue name. +// authorizationRuleName - the authorizationrule name. +func (client QueuesClient) DeleteAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, authorizationRuleName string) (result autorest.Response, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: queueName, + Constraints: []validation.Constraint{{Target: "queueName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: authorizationRuleName, + Constraints: []validation.Constraint{{Target: "authorizationRuleName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "authorizationRuleName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.QueuesClient", "DeleteAuthorizationRule", err.Error()) + } + + req, err := client.DeleteAuthorizationRulePreparer(ctx, resourceGroupName, namespaceName, queueName, authorizationRuleName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "DeleteAuthorizationRule", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteAuthorizationRuleSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "DeleteAuthorizationRule", resp, "Failure sending request") + return + } + + result, err = client.DeleteAuthorizationRuleResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "DeleteAuthorizationRule", resp, "Failure responding to request") + } + + return +} + +// DeleteAuthorizationRulePreparer prepares the DeleteAuthorizationRule request. +func (client QueuesClient) DeleteAuthorizationRulePreparer(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, authorizationRuleName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "authorizationRuleName": autorest.Encode("path", authorizationRuleName), + "namespaceName": autorest.Encode("path", namespaceName), + "queueName": autorest.Encode("path", queueName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/queues/{queueName}/authorizationRules/{authorizationRuleName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DeleteAuthorizationRuleSender sends the DeleteAuthorizationRule request. The method will close the +// http.Response Body if it receives an error. +func (client QueuesClient) DeleteAuthorizationRuleSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// DeleteAuthorizationRuleResponder handles the response to the DeleteAuthorizationRule request. The method always +// closes the http.Response Body. +func (client QueuesClient) DeleteAuthorizationRuleResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get returns a description for the specified queue. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// queueName - the queue name. +func (client QueuesClient) Get(ctx context.Context, resourceGroupName string, namespaceName string, queueName string) (result SBQueue, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: queueName, + Constraints: []validation.Constraint{{Target: "queueName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.QueuesClient", "Get", err.Error()) + } + + req, err := client.GetPreparer(ctx, resourceGroupName, namespaceName, queueName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client QueuesClient) GetPreparer(ctx context.Context, resourceGroupName string, namespaceName string, queueName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "namespaceName": autorest.Encode("path", namespaceName), + "queueName": autorest.Encode("path", queueName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/queues/{queueName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client QueuesClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client QueuesClient) GetResponder(resp *http.Response) (result SBQueue, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetAuthorizationRule gets an authorization rule for a queue by rule name. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// queueName - the queue name. +// authorizationRuleName - the authorizationrule name. +func (client QueuesClient) GetAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, authorizationRuleName string) (result SBAuthorizationRule, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: queueName, + Constraints: []validation.Constraint{{Target: "queueName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: authorizationRuleName, + Constraints: []validation.Constraint{{Target: "authorizationRuleName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "authorizationRuleName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.QueuesClient", "GetAuthorizationRule", err.Error()) + } + + req, err := client.GetAuthorizationRulePreparer(ctx, resourceGroupName, namespaceName, queueName, authorizationRuleName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "GetAuthorizationRule", nil, "Failure preparing request") + return + } + + resp, err := client.GetAuthorizationRuleSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "GetAuthorizationRule", resp, "Failure sending request") + return + } + + result, err = client.GetAuthorizationRuleResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "GetAuthorizationRule", resp, "Failure responding to request") + } + + return +} + +// GetAuthorizationRulePreparer prepares the GetAuthorizationRule request. +func (client QueuesClient) GetAuthorizationRulePreparer(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, authorizationRuleName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "authorizationRuleName": autorest.Encode("path", authorizationRuleName), + "namespaceName": autorest.Encode("path", namespaceName), + "queueName": autorest.Encode("path", queueName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/queues/{queueName}/authorizationRules/{authorizationRuleName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetAuthorizationRuleSender sends the GetAuthorizationRule request. The method will close the +// http.Response Body if it receives an error. +func (client QueuesClient) GetAuthorizationRuleSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetAuthorizationRuleResponder handles the response to the GetAuthorizationRule request. The method always +// closes the http.Response Body. +func (client QueuesClient) GetAuthorizationRuleResponder(resp *http.Response) (result SBAuthorizationRule, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListAuthorizationRules gets all authorization rules for a queue. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// queueName - the queue name. +func (client QueuesClient) ListAuthorizationRules(ctx context.Context, resourceGroupName string, namespaceName string, queueName string) (result SBAuthorizationRuleListResultPage, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: queueName, + Constraints: []validation.Constraint{{Target: "queueName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.QueuesClient", "ListAuthorizationRules", err.Error()) + } + + result.fn = client.listAuthorizationRulesNextResults + req, err := client.ListAuthorizationRulesPreparer(ctx, resourceGroupName, namespaceName, queueName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "ListAuthorizationRules", nil, "Failure preparing request") + return + } + + resp, err := client.ListAuthorizationRulesSender(req) + if err != nil { + result.sarlr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "ListAuthorizationRules", resp, "Failure sending request") + return + } + + result.sarlr, err = client.ListAuthorizationRulesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "ListAuthorizationRules", resp, "Failure responding to request") + } + + return +} + +// ListAuthorizationRulesPreparer prepares the ListAuthorizationRules request. +func (client QueuesClient) ListAuthorizationRulesPreparer(ctx context.Context, resourceGroupName string, namespaceName string, queueName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "namespaceName": autorest.Encode("path", namespaceName), + "queueName": autorest.Encode("path", queueName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/queues/{queueName}/authorizationRules", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListAuthorizationRulesSender sends the ListAuthorizationRules request. The method will close the +// http.Response Body if it receives an error. +func (client QueuesClient) ListAuthorizationRulesSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListAuthorizationRulesResponder handles the response to the ListAuthorizationRules request. The method always +// closes the http.Response Body. +func (client QueuesClient) ListAuthorizationRulesResponder(resp *http.Response) (result SBAuthorizationRuleListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listAuthorizationRulesNextResults retrieves the next set of results, if any. +func (client QueuesClient) listAuthorizationRulesNextResults(lastResults SBAuthorizationRuleListResult) (result SBAuthorizationRuleListResult, err error) { + req, err := lastResults.sBAuthorizationRuleListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "servicebus.QueuesClient", "listAuthorizationRulesNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListAuthorizationRulesSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "servicebus.QueuesClient", "listAuthorizationRulesNextResults", resp, "Failure sending next results request") + } + result, err = client.ListAuthorizationRulesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "listAuthorizationRulesNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListAuthorizationRulesComplete enumerates all values, automatically crossing page boundaries as required. +func (client QueuesClient) ListAuthorizationRulesComplete(ctx context.Context, resourceGroupName string, namespaceName string, queueName string) (result SBAuthorizationRuleListResultIterator, err error) { + result.page, err = client.ListAuthorizationRules(ctx, resourceGroupName, namespaceName, queueName) + return +} + +// ListByNamespace gets the queues within a namespace. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// skip - skip is only used if a previous operation returned a partial result. If a previous response contains +// a nextLink element, the value of the nextLink element will include a skip parameter that specifies a +// starting point to use for subsequent calls. +// top - may be used to limit the number of results to the most recent N usageDetails. +func (client QueuesClient) ListByNamespace(ctx context.Context, resourceGroupName string, namespaceName string, skip *int32, top *int32) (result SBQueueListResultPage, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: skip, + Constraints: []validation.Constraint{{Target: "skip", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "skip", Name: validation.InclusiveMaximum, Rule: int64(1000), Chain: nil}, + {Target: "skip", Name: validation.InclusiveMinimum, Rule: 0, Chain: nil}, + }}}}, + {TargetValue: top, + Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMaximum, Rule: int64(1000), Chain: nil}, + {Target: "top", Name: validation.InclusiveMinimum, Rule: 1, Chain: nil}, + }}}}}); err != nil { + return result, validation.NewError("servicebus.QueuesClient", "ListByNamespace", err.Error()) + } + + result.fn = client.listByNamespaceNextResults + req, err := client.ListByNamespacePreparer(ctx, resourceGroupName, namespaceName, skip, top) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "ListByNamespace", nil, "Failure preparing request") + return + } + + resp, err := client.ListByNamespaceSender(req) + if err != nil { + result.sqlr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "ListByNamespace", resp, "Failure sending request") + return + } + + result.sqlr, err = client.ListByNamespaceResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "ListByNamespace", resp, "Failure responding to request") + } + + return +} + +// ListByNamespacePreparer prepares the ListByNamespace request. +func (client QueuesClient) ListByNamespacePreparer(ctx context.Context, resourceGroupName string, namespaceName string, skip *int32, top *int32) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if skip != nil { + queryParameters["$skip"] = autorest.Encode("query", *skip) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/queues", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByNamespaceSender sends the ListByNamespace request. The method will close the +// http.Response Body if it receives an error. +func (client QueuesClient) ListByNamespaceSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListByNamespaceResponder handles the response to the ListByNamespace request. The method always +// closes the http.Response Body. +func (client QueuesClient) ListByNamespaceResponder(resp *http.Response) (result SBQueueListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listByNamespaceNextResults retrieves the next set of results, if any. +func (client QueuesClient) listByNamespaceNextResults(lastResults SBQueueListResult) (result SBQueueListResult, err error) { + req, err := lastResults.sBQueueListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "servicebus.QueuesClient", "listByNamespaceNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListByNamespaceSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "servicebus.QueuesClient", "listByNamespaceNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByNamespaceResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "listByNamespaceNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByNamespaceComplete enumerates all values, automatically crossing page boundaries as required. +func (client QueuesClient) ListByNamespaceComplete(ctx context.Context, resourceGroupName string, namespaceName string, skip *int32, top *int32) (result SBQueueListResultIterator, err error) { + result.page, err = client.ListByNamespace(ctx, resourceGroupName, namespaceName, skip, top) + return +} + +// ListKeys primary and secondary connection strings to the queue. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// queueName - the queue name. +// authorizationRuleName - the authorizationrule name. +func (client QueuesClient) ListKeys(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, authorizationRuleName string) (result AccessKeys, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: queueName, + Constraints: []validation.Constraint{{Target: "queueName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: authorizationRuleName, + Constraints: []validation.Constraint{{Target: "authorizationRuleName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "authorizationRuleName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.QueuesClient", "ListKeys", err.Error()) + } + + req, err := client.ListKeysPreparer(ctx, resourceGroupName, namespaceName, queueName, authorizationRuleName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "ListKeys", nil, "Failure preparing request") + return + } + + resp, err := client.ListKeysSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "ListKeys", resp, "Failure sending request") + return + } + + result, err = client.ListKeysResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "ListKeys", resp, "Failure responding to request") + } + + return +} + +// ListKeysPreparer prepares the ListKeys request. +func (client QueuesClient) ListKeysPreparer(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, authorizationRuleName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "authorizationRuleName": autorest.Encode("path", authorizationRuleName), + "namespaceName": autorest.Encode("path", namespaceName), + "queueName": autorest.Encode("path", queueName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/queues/{queueName}/authorizationRules/{authorizationRuleName}/ListKeys", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListKeysSender sends the ListKeys request. The method will close the +// http.Response Body if it receives an error. +func (client QueuesClient) ListKeysSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListKeysResponder handles the response to the ListKeys request. The method always +// closes the http.Response Body. +func (client QueuesClient) ListKeysResponder(resp *http.Response) (result AccessKeys, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// RegenerateKeys regenerates the primary or secondary connection strings to the queue. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// queueName - the queue name. +// authorizationRuleName - the authorizationrule name. +// parameters - parameters supplied to regenerate the authorization rule. +func (client QueuesClient) RegenerateKeys(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, authorizationRuleName string, parameters RegenerateAccessKeyParameters) (result AccessKeys, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: queueName, + Constraints: []validation.Constraint{{Target: "queueName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: authorizationRuleName, + Constraints: []validation.Constraint{{Target: "authorizationRuleName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "authorizationRuleName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.QueuesClient", "RegenerateKeys", err.Error()) + } + + req, err := client.RegenerateKeysPreparer(ctx, resourceGroupName, namespaceName, queueName, authorizationRuleName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "RegenerateKeys", nil, "Failure preparing request") + return + } + + resp, err := client.RegenerateKeysSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "RegenerateKeys", resp, "Failure sending request") + return + } + + result, err = client.RegenerateKeysResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.QueuesClient", "RegenerateKeys", resp, "Failure responding to request") + } + + return +} + +// RegenerateKeysPreparer prepares the RegenerateKeys request. +func (client QueuesClient) RegenerateKeysPreparer(ctx context.Context, resourceGroupName string, namespaceName string, queueName string, authorizationRuleName string, parameters RegenerateAccessKeyParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "authorizationRuleName": autorest.Encode("path", authorizationRuleName), + "namespaceName": autorest.Encode("path", namespaceName), + "queueName": autorest.Encode("path", queueName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/queues/{queueName}/authorizationRules/{authorizationRuleName}/regenerateKeys", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// RegenerateKeysSender sends the RegenerateKeys request. The method will close the +// http.Response Body if it receives an error. +func (client QueuesClient) RegenerateKeysSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// RegenerateKeysResponder handles the response to the RegenerateKeys request. The method always +// closes the http.Response Body. +func (client QueuesClient) RegenerateKeysResponder(resp *http.Response) (result AccessKeys, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/regions.go b/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/regions.go new file mode 100644 index 00000000..ac86b2c6 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/regions.go @@ -0,0 +1,141 @@ +package servicebus + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// 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 Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "net/http" +) + +// RegionsClient is the azure Service Bus client +type RegionsClient struct { + BaseClient +} + +// NewRegionsClient creates an instance of the RegionsClient client. +func NewRegionsClient(subscriptionID string) RegionsClient { + return NewRegionsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewRegionsClientWithBaseURI creates an instance of the RegionsClient client. +func NewRegionsClientWithBaseURI(baseURI string, subscriptionID string) RegionsClient { + return RegionsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// ListBySku gets the available Regions for a given sku +// Parameters: +// sku - the sku type. +func (client RegionsClient) ListBySku(ctx context.Context, sku string) (result PremiumMessagingRegionsListResultPage, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: sku, + Constraints: []validation.Constraint{{Target: "sku", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "sku", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.RegionsClient", "ListBySku", err.Error()) + } + + result.fn = client.listBySkuNextResults + req, err := client.ListBySkuPreparer(ctx, sku) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.RegionsClient", "ListBySku", nil, "Failure preparing request") + return + } + + resp, err := client.ListBySkuSender(req) + if err != nil { + result.pmrlr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.RegionsClient", "ListBySku", resp, "Failure sending request") + return + } + + result.pmrlr, err = client.ListBySkuResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.RegionsClient", "ListBySku", resp, "Failure responding to request") + } + + return +} + +// ListBySkuPreparer prepares the ListBySku request. +func (client RegionsClient) ListBySkuPreparer(ctx context.Context, sku string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "sku": autorest.Encode("path", sku), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.ServiceBus/sku/{sku}/regions", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListBySkuSender sends the ListBySku request. The method will close the +// http.Response Body if it receives an error. +func (client RegionsClient) ListBySkuSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListBySkuResponder handles the response to the ListBySku request. The method always +// closes the http.Response Body. +func (client RegionsClient) ListBySkuResponder(resp *http.Response) (result PremiumMessagingRegionsListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listBySkuNextResults retrieves the next set of results, if any. +func (client RegionsClient) listBySkuNextResults(lastResults PremiumMessagingRegionsListResult) (result PremiumMessagingRegionsListResult, err error) { + req, err := lastResults.premiumMessagingRegionsListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "servicebus.RegionsClient", "listBySkuNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListBySkuSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "servicebus.RegionsClient", "listBySkuNextResults", resp, "Failure sending next results request") + } + result, err = client.ListBySkuResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.RegionsClient", "listBySkuNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListBySkuComplete enumerates all values, automatically crossing page boundaries as required. +func (client RegionsClient) ListBySkuComplete(ctx context.Context, sku string) (result PremiumMessagingRegionsListResultIterator, err error) { + result.page, err = client.ListBySku(ctx, sku) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/rules.go b/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/rules.go new file mode 100644 index 00000000..4cbe705f --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/rules.go @@ -0,0 +1,450 @@ +package servicebus + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// 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 Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "net/http" +) + +// RulesClient is the azure Service Bus client +type RulesClient struct { + BaseClient +} + +// NewRulesClient creates an instance of the RulesClient client. +func NewRulesClient(subscriptionID string) RulesClient { + return NewRulesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewRulesClientWithBaseURI creates an instance of the RulesClient client. +func NewRulesClientWithBaseURI(baseURI string, subscriptionID string) RulesClient { + return RulesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate creates a new rule and updates an existing rule +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// topicName - the topic name. +// subscriptionName - the subscription name. +// ruleName - the rule name. +// parameters - parameters supplied to create a rule. +func (client RulesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, namespaceName string, topicName string, subscriptionName string, ruleName string, parameters Rule) (result Rule, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: topicName, + Constraints: []validation.Constraint{{Target: "topicName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: subscriptionName, + Constraints: []validation.Constraint{{Target: "subscriptionName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "subscriptionName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: ruleName, + Constraints: []validation.Constraint{{Target: "ruleName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "ruleName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.RulesClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, namespaceName, topicName, subscriptionName, ruleName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.RulesClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.RulesClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.RulesClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client RulesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, namespaceName string, topicName string, subscriptionName string, ruleName string, parameters Rule) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "ruleName": autorest.Encode("path", ruleName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "subscriptionName": autorest.Encode("path", subscriptionName), + "topicName": autorest.Encode("path", topicName), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}/subscriptions/{subscriptionName}/rules/{ruleName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client RulesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client RulesClient) CreateOrUpdateResponder(resp *http.Response) (result Rule, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes an existing rule. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// topicName - the topic name. +// subscriptionName - the subscription name. +// ruleName - the rule name. +func (client RulesClient) Delete(ctx context.Context, resourceGroupName string, namespaceName string, topicName string, subscriptionName string, ruleName string) (result autorest.Response, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: topicName, + Constraints: []validation.Constraint{{Target: "topicName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: subscriptionName, + Constraints: []validation.Constraint{{Target: "subscriptionName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "subscriptionName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: ruleName, + Constraints: []validation.Constraint{{Target: "ruleName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "ruleName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.RulesClient", "Delete", err.Error()) + } + + req, err := client.DeletePreparer(ctx, resourceGroupName, namespaceName, topicName, subscriptionName, ruleName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.RulesClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "servicebus.RulesClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.RulesClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client RulesClient) DeletePreparer(ctx context.Context, resourceGroupName string, namespaceName string, topicName string, subscriptionName string, ruleName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "ruleName": autorest.Encode("path", ruleName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "subscriptionName": autorest.Encode("path", subscriptionName), + "topicName": autorest.Encode("path", topicName), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}/subscriptions/{subscriptionName}/rules/{ruleName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client RulesClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client RulesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get retrieves the description for the specified rule. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// topicName - the topic name. +// subscriptionName - the subscription name. +// ruleName - the rule name. +func (client RulesClient) Get(ctx context.Context, resourceGroupName string, namespaceName string, topicName string, subscriptionName string, ruleName string) (result Rule, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: topicName, + Constraints: []validation.Constraint{{Target: "topicName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: subscriptionName, + Constraints: []validation.Constraint{{Target: "subscriptionName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "subscriptionName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: ruleName, + Constraints: []validation.Constraint{{Target: "ruleName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "ruleName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.RulesClient", "Get", err.Error()) + } + + req, err := client.GetPreparer(ctx, resourceGroupName, namespaceName, topicName, subscriptionName, ruleName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.RulesClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.RulesClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.RulesClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client RulesClient) GetPreparer(ctx context.Context, resourceGroupName string, namespaceName string, topicName string, subscriptionName string, ruleName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "ruleName": autorest.Encode("path", ruleName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "subscriptionName": autorest.Encode("path", subscriptionName), + "topicName": autorest.Encode("path", topicName), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}/subscriptions/{subscriptionName}/rules/{ruleName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client RulesClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client RulesClient) GetResponder(resp *http.Response) (result Rule, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListBySubscriptions list all the rules within given topic-subscription +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// topicName - the topic name. +// subscriptionName - the subscription name. +// skip - skip is only used if a previous operation returned a partial result. If a previous response contains +// a nextLink element, the value of the nextLink element will include a skip parameter that specifies a +// starting point to use for subsequent calls. +// top - may be used to limit the number of results to the most recent N usageDetails. +func (client RulesClient) ListBySubscriptions(ctx context.Context, resourceGroupName string, namespaceName string, topicName string, subscriptionName string, skip *int32, top *int32) (result RuleListResultPage, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: topicName, + Constraints: []validation.Constraint{{Target: "topicName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: subscriptionName, + Constraints: []validation.Constraint{{Target: "subscriptionName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "subscriptionName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: skip, + Constraints: []validation.Constraint{{Target: "skip", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "skip", Name: validation.InclusiveMaximum, Rule: int64(1000), Chain: nil}, + {Target: "skip", Name: validation.InclusiveMinimum, Rule: 0, Chain: nil}, + }}}}, + {TargetValue: top, + Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMaximum, Rule: int64(1000), Chain: nil}, + {Target: "top", Name: validation.InclusiveMinimum, Rule: 1, Chain: nil}, + }}}}}); err != nil { + return result, validation.NewError("servicebus.RulesClient", "ListBySubscriptions", err.Error()) + } + + result.fn = client.listBySubscriptionsNextResults + req, err := client.ListBySubscriptionsPreparer(ctx, resourceGroupName, namespaceName, topicName, subscriptionName, skip, top) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.RulesClient", "ListBySubscriptions", nil, "Failure preparing request") + return + } + + resp, err := client.ListBySubscriptionsSender(req) + if err != nil { + result.rlr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.RulesClient", "ListBySubscriptions", resp, "Failure sending request") + return + } + + result.rlr, err = client.ListBySubscriptionsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.RulesClient", "ListBySubscriptions", resp, "Failure responding to request") + } + + return +} + +// ListBySubscriptionsPreparer prepares the ListBySubscriptions request. +func (client RulesClient) ListBySubscriptionsPreparer(ctx context.Context, resourceGroupName string, namespaceName string, topicName string, subscriptionName string, skip *int32, top *int32) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "subscriptionName": autorest.Encode("path", subscriptionName), + "topicName": autorest.Encode("path", topicName), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if skip != nil { + queryParameters["$skip"] = autorest.Encode("query", *skip) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}/subscriptions/{subscriptionName}/rules", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListBySubscriptionsSender sends the ListBySubscriptions request. The method will close the +// http.Response Body if it receives an error. +func (client RulesClient) ListBySubscriptionsSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListBySubscriptionsResponder handles the response to the ListBySubscriptions request. The method always +// closes the http.Response Body. +func (client RulesClient) ListBySubscriptionsResponder(resp *http.Response) (result RuleListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listBySubscriptionsNextResults retrieves the next set of results, if any. +func (client RulesClient) listBySubscriptionsNextResults(lastResults RuleListResult) (result RuleListResult, err error) { + req, err := lastResults.ruleListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "servicebus.RulesClient", "listBySubscriptionsNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListBySubscriptionsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "servicebus.RulesClient", "listBySubscriptionsNextResults", resp, "Failure sending next results request") + } + result, err = client.ListBySubscriptionsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.RulesClient", "listBySubscriptionsNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListBySubscriptionsComplete enumerates all values, automatically crossing page boundaries as required. +func (client RulesClient) ListBySubscriptionsComplete(ctx context.Context, resourceGroupName string, namespaceName string, topicName string, subscriptionName string, skip *int32, top *int32) (result RuleListResultIterator, err error) { + result.page, err = client.ListBySubscriptions(ctx, resourceGroupName, namespaceName, topicName, subscriptionName, skip, top) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/subscriptions.go b/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/subscriptions.go new file mode 100644 index 00000000..1a087cb8 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/subscriptions.go @@ -0,0 +1,430 @@ +package servicebus + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// 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 Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "net/http" +) + +// SubscriptionsClient is the azure Service Bus client +type SubscriptionsClient struct { + BaseClient +} + +// NewSubscriptionsClient creates an instance of the SubscriptionsClient client. +func NewSubscriptionsClient(subscriptionID string) SubscriptionsClient { + return NewSubscriptionsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewSubscriptionsClientWithBaseURI creates an instance of the SubscriptionsClient client. +func NewSubscriptionsClientWithBaseURI(baseURI string, subscriptionID string) SubscriptionsClient { + return SubscriptionsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate creates a topic subscription. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// topicName - the topic name. +// subscriptionName - the subscription name. +// parameters - parameters supplied to create a subscription resource. +func (client SubscriptionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, namespaceName string, topicName string, subscriptionName string, parameters SBSubscription) (result SBSubscription, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: topicName, + Constraints: []validation.Constraint{{Target: "topicName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: subscriptionName, + Constraints: []validation.Constraint{{Target: "subscriptionName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "subscriptionName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.SubscriptionsClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, namespaceName, topicName, subscriptionName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.SubscriptionsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.SubscriptionsClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.SubscriptionsClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client SubscriptionsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, namespaceName string, topicName string, subscriptionName string, parameters SBSubscription) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "subscriptionName": autorest.Encode("path", subscriptionName), + "topicName": autorest.Encode("path", topicName), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}/subscriptions/{subscriptionName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client SubscriptionsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client SubscriptionsClient) CreateOrUpdateResponder(resp *http.Response) (result SBSubscription, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes a subscription from the specified topic. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// topicName - the topic name. +// subscriptionName - the subscription name. +func (client SubscriptionsClient) Delete(ctx context.Context, resourceGroupName string, namespaceName string, topicName string, subscriptionName string) (result autorest.Response, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: topicName, + Constraints: []validation.Constraint{{Target: "topicName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: subscriptionName, + Constraints: []validation.Constraint{{Target: "subscriptionName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "subscriptionName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.SubscriptionsClient", "Delete", err.Error()) + } + + req, err := client.DeletePreparer(ctx, resourceGroupName, namespaceName, topicName, subscriptionName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.SubscriptionsClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "servicebus.SubscriptionsClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.SubscriptionsClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client SubscriptionsClient) DeletePreparer(ctx context.Context, resourceGroupName string, namespaceName string, topicName string, subscriptionName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "subscriptionName": autorest.Encode("path", subscriptionName), + "topicName": autorest.Encode("path", topicName), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}/subscriptions/{subscriptionName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client SubscriptionsClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client SubscriptionsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get returns a subscription description for the specified topic. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// topicName - the topic name. +// subscriptionName - the subscription name. +func (client SubscriptionsClient) Get(ctx context.Context, resourceGroupName string, namespaceName string, topicName string, subscriptionName string) (result SBSubscription, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: topicName, + Constraints: []validation.Constraint{{Target: "topicName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: subscriptionName, + Constraints: []validation.Constraint{{Target: "subscriptionName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "subscriptionName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.SubscriptionsClient", "Get", err.Error()) + } + + req, err := client.GetPreparer(ctx, resourceGroupName, namespaceName, topicName, subscriptionName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.SubscriptionsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.SubscriptionsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.SubscriptionsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client SubscriptionsClient) GetPreparer(ctx context.Context, resourceGroupName string, namespaceName string, topicName string, subscriptionName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "subscriptionName": autorest.Encode("path", subscriptionName), + "topicName": autorest.Encode("path", topicName), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}/subscriptions/{subscriptionName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client SubscriptionsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client SubscriptionsClient) GetResponder(resp *http.Response) (result SBSubscription, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByTopic list all the subscriptions under a specified topic. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// topicName - the topic name. +// skip - skip is only used if a previous operation returned a partial result. If a previous response contains +// a nextLink element, the value of the nextLink element will include a skip parameter that specifies a +// starting point to use for subsequent calls. +// top - may be used to limit the number of results to the most recent N usageDetails. +func (client SubscriptionsClient) ListByTopic(ctx context.Context, resourceGroupName string, namespaceName string, topicName string, skip *int32, top *int32) (result SBSubscriptionListResultPage, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: topicName, + Constraints: []validation.Constraint{{Target: "topicName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: skip, + Constraints: []validation.Constraint{{Target: "skip", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "skip", Name: validation.InclusiveMaximum, Rule: int64(1000), Chain: nil}, + {Target: "skip", Name: validation.InclusiveMinimum, Rule: 0, Chain: nil}, + }}}}, + {TargetValue: top, + Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMaximum, Rule: int64(1000), Chain: nil}, + {Target: "top", Name: validation.InclusiveMinimum, Rule: 1, Chain: nil}, + }}}}}); err != nil { + return result, validation.NewError("servicebus.SubscriptionsClient", "ListByTopic", err.Error()) + } + + result.fn = client.listByTopicNextResults + req, err := client.ListByTopicPreparer(ctx, resourceGroupName, namespaceName, topicName, skip, top) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.SubscriptionsClient", "ListByTopic", nil, "Failure preparing request") + return + } + + resp, err := client.ListByTopicSender(req) + if err != nil { + result.sslr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.SubscriptionsClient", "ListByTopic", resp, "Failure sending request") + return + } + + result.sslr, err = client.ListByTopicResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.SubscriptionsClient", "ListByTopic", resp, "Failure responding to request") + } + + return +} + +// ListByTopicPreparer prepares the ListByTopic request. +func (client SubscriptionsClient) ListByTopicPreparer(ctx context.Context, resourceGroupName string, namespaceName string, topicName string, skip *int32, top *int32) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "topicName": autorest.Encode("path", topicName), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if skip != nil { + queryParameters["$skip"] = autorest.Encode("query", *skip) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}/subscriptions", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByTopicSender sends the ListByTopic request. The method will close the +// http.Response Body if it receives an error. +func (client SubscriptionsClient) ListByTopicSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListByTopicResponder handles the response to the ListByTopic request. The method always +// closes the http.Response Body. +func (client SubscriptionsClient) ListByTopicResponder(resp *http.Response) (result SBSubscriptionListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listByTopicNextResults retrieves the next set of results, if any. +func (client SubscriptionsClient) listByTopicNextResults(lastResults SBSubscriptionListResult) (result SBSubscriptionListResult, err error) { + req, err := lastResults.sBSubscriptionListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "servicebus.SubscriptionsClient", "listByTopicNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListByTopicSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "servicebus.SubscriptionsClient", "listByTopicNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByTopicResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.SubscriptionsClient", "listByTopicNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByTopicComplete enumerates all values, automatically crossing page boundaries as required. +func (client SubscriptionsClient) ListByTopicComplete(ctx context.Context, resourceGroupName string, namespaceName string, topicName string, skip *int32, top *int32) (result SBSubscriptionListResultIterator, err error) { + result.page, err = client.ListByTopic(ctx, resourceGroupName, namespaceName, topicName, skip, top) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/topics.go b/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/topics.go new file mode 100644 index 00000000..ce8b0c1a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/topics.go @@ -0,0 +1,958 @@ +package servicebus + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// 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 Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "github.com/Azure/go-autorest/autorest/validation" + "net/http" +) + +// TopicsClient is the azure Service Bus client +type TopicsClient struct { + BaseClient +} + +// NewTopicsClient creates an instance of the TopicsClient client. +func NewTopicsClient(subscriptionID string) TopicsClient { + return NewTopicsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewTopicsClientWithBaseURI creates an instance of the TopicsClient client. +func NewTopicsClientWithBaseURI(baseURI string, subscriptionID string) TopicsClient { + return TopicsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate creates a topic in the specified namespace. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// topicName - the topic name. +// parameters - parameters supplied to create a topic resource. +func (client TopicsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, namespaceName string, topicName string, parameters SBTopic) (result SBTopic, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: topicName, + Constraints: []validation.Constraint{{Target: "topicName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.TopicsClient", "CreateOrUpdate", err.Error()) + } + + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, namespaceName, topicName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.TopicsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.TopicsClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.TopicsClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client TopicsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, namespaceName string, topicName string, parameters SBTopic) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "topicName": autorest.Encode("path", topicName), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client TopicsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client TopicsClient) CreateOrUpdateResponder(resp *http.Response) (result SBTopic, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// CreateOrUpdateAuthorizationRule creates an authorizatio rule for the specified topic. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// topicName - the topic name. +// authorizationRuleName - the authorizationrule name. +// parameters - the shared access authorization rule. +func (client TopicsClient) CreateOrUpdateAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, topicName string, authorizationRuleName string, parameters SBAuthorizationRule) (result SBAuthorizationRule, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: topicName, + Constraints: []validation.Constraint{{Target: "topicName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: authorizationRuleName, + Constraints: []validation.Constraint{{Target: "authorizationRuleName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "authorizationRuleName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: parameters, + Constraints: []validation.Constraint{{Target: "parameters.SBAuthorizationRuleProperties", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "parameters.SBAuthorizationRuleProperties.Rights", Name: validation.Null, Rule: true, Chain: nil}}}}}}); err != nil { + return result, validation.NewError("servicebus.TopicsClient", "CreateOrUpdateAuthorizationRule", err.Error()) + } + + req, err := client.CreateOrUpdateAuthorizationRulePreparer(ctx, resourceGroupName, namespaceName, topicName, authorizationRuleName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.TopicsClient", "CreateOrUpdateAuthorizationRule", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateAuthorizationRuleSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.TopicsClient", "CreateOrUpdateAuthorizationRule", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateAuthorizationRuleResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.TopicsClient", "CreateOrUpdateAuthorizationRule", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdateAuthorizationRulePreparer prepares the CreateOrUpdateAuthorizationRule request. +func (client TopicsClient) CreateOrUpdateAuthorizationRulePreparer(ctx context.Context, resourceGroupName string, namespaceName string, topicName string, authorizationRuleName string, parameters SBAuthorizationRule) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "authorizationRuleName": autorest.Encode("path", authorizationRuleName), + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "topicName": autorest.Encode("path", topicName), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}/authorizationRules/{authorizationRuleName}", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateOrUpdateAuthorizationRuleSender sends the CreateOrUpdateAuthorizationRule request. The method will close the +// http.Response Body if it receives an error. +func (client TopicsClient) CreateOrUpdateAuthorizationRuleSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// CreateOrUpdateAuthorizationRuleResponder handles the response to the CreateOrUpdateAuthorizationRule request. The method always +// closes the http.Response Body. +func (client TopicsClient) CreateOrUpdateAuthorizationRuleResponder(resp *http.Response) (result SBAuthorizationRule, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes a topic from the specified namespace and resource group. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// topicName - the topic name. +func (client TopicsClient) Delete(ctx context.Context, resourceGroupName string, namespaceName string, topicName string) (result autorest.Response, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: topicName, + Constraints: []validation.Constraint{{Target: "topicName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.TopicsClient", "Delete", err.Error()) + } + + req, err := client.DeletePreparer(ctx, resourceGroupName, namespaceName, topicName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.TopicsClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "servicebus.TopicsClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.TopicsClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client TopicsClient) DeletePreparer(ctx context.Context, resourceGroupName string, namespaceName string, topicName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "topicName": autorest.Encode("path", topicName), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client TopicsClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client TopicsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// DeleteAuthorizationRule deletes a topic authorization rule. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// topicName - the topic name. +// authorizationRuleName - the authorizationrule name. +func (client TopicsClient) DeleteAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, topicName string, authorizationRuleName string) (result autorest.Response, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: topicName, + Constraints: []validation.Constraint{{Target: "topicName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: authorizationRuleName, + Constraints: []validation.Constraint{{Target: "authorizationRuleName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "authorizationRuleName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.TopicsClient", "DeleteAuthorizationRule", err.Error()) + } + + req, err := client.DeleteAuthorizationRulePreparer(ctx, resourceGroupName, namespaceName, topicName, authorizationRuleName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.TopicsClient", "DeleteAuthorizationRule", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteAuthorizationRuleSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "servicebus.TopicsClient", "DeleteAuthorizationRule", resp, "Failure sending request") + return + } + + result, err = client.DeleteAuthorizationRuleResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.TopicsClient", "DeleteAuthorizationRule", resp, "Failure responding to request") + } + + return +} + +// DeleteAuthorizationRulePreparer prepares the DeleteAuthorizationRule request. +func (client TopicsClient) DeleteAuthorizationRulePreparer(ctx context.Context, resourceGroupName string, namespaceName string, topicName string, authorizationRuleName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "authorizationRuleName": autorest.Encode("path", authorizationRuleName), + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "topicName": autorest.Encode("path", topicName), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}/authorizationRules/{authorizationRuleName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DeleteAuthorizationRuleSender sends the DeleteAuthorizationRule request. The method will close the +// http.Response Body if it receives an error. +func (client TopicsClient) DeleteAuthorizationRuleSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// DeleteAuthorizationRuleResponder handles the response to the DeleteAuthorizationRule request. The method always +// closes the http.Response Body. +func (client TopicsClient) DeleteAuthorizationRuleResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get returns a description for the specified topic. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// topicName - the topic name. +func (client TopicsClient) Get(ctx context.Context, resourceGroupName string, namespaceName string, topicName string) (result SBTopic, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: topicName, + Constraints: []validation.Constraint{{Target: "topicName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.TopicsClient", "Get", err.Error()) + } + + req, err := client.GetPreparer(ctx, resourceGroupName, namespaceName, topicName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.TopicsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.TopicsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.TopicsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client TopicsClient) GetPreparer(ctx context.Context, resourceGroupName string, namespaceName string, topicName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "topicName": autorest.Encode("path", topicName), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client TopicsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client TopicsClient) GetResponder(resp *http.Response) (result SBTopic, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// GetAuthorizationRule returns the specified authorization rule. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// topicName - the topic name. +// authorizationRuleName - the authorizationrule name. +func (client TopicsClient) GetAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, topicName string, authorizationRuleName string) (result SBAuthorizationRule, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: topicName, + Constraints: []validation.Constraint{{Target: "topicName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: authorizationRuleName, + Constraints: []validation.Constraint{{Target: "authorizationRuleName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "authorizationRuleName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.TopicsClient", "GetAuthorizationRule", err.Error()) + } + + req, err := client.GetAuthorizationRulePreparer(ctx, resourceGroupName, namespaceName, topicName, authorizationRuleName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.TopicsClient", "GetAuthorizationRule", nil, "Failure preparing request") + return + } + + resp, err := client.GetAuthorizationRuleSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.TopicsClient", "GetAuthorizationRule", resp, "Failure sending request") + return + } + + result, err = client.GetAuthorizationRuleResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.TopicsClient", "GetAuthorizationRule", resp, "Failure responding to request") + } + + return +} + +// GetAuthorizationRulePreparer prepares the GetAuthorizationRule request. +func (client TopicsClient) GetAuthorizationRulePreparer(ctx context.Context, resourceGroupName string, namespaceName string, topicName string, authorizationRuleName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "authorizationRuleName": autorest.Encode("path", authorizationRuleName), + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "topicName": autorest.Encode("path", topicName), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}/authorizationRules/{authorizationRuleName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetAuthorizationRuleSender sends the GetAuthorizationRule request. The method will close the +// http.Response Body if it receives an error. +func (client TopicsClient) GetAuthorizationRuleSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetAuthorizationRuleResponder handles the response to the GetAuthorizationRule request. The method always +// closes the http.Response Body. +func (client TopicsClient) GetAuthorizationRuleResponder(resp *http.Response) (result SBAuthorizationRule, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListAuthorizationRules gets authorization rules for a topic. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// topicName - the topic name. +func (client TopicsClient) ListAuthorizationRules(ctx context.Context, resourceGroupName string, namespaceName string, topicName string) (result SBAuthorizationRuleListResultPage, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: topicName, + Constraints: []validation.Constraint{{Target: "topicName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.TopicsClient", "ListAuthorizationRules", err.Error()) + } + + result.fn = client.listAuthorizationRulesNextResults + req, err := client.ListAuthorizationRulesPreparer(ctx, resourceGroupName, namespaceName, topicName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.TopicsClient", "ListAuthorizationRules", nil, "Failure preparing request") + return + } + + resp, err := client.ListAuthorizationRulesSender(req) + if err != nil { + result.sarlr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.TopicsClient", "ListAuthorizationRules", resp, "Failure sending request") + return + } + + result.sarlr, err = client.ListAuthorizationRulesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.TopicsClient", "ListAuthorizationRules", resp, "Failure responding to request") + } + + return +} + +// ListAuthorizationRulesPreparer prepares the ListAuthorizationRules request. +func (client TopicsClient) ListAuthorizationRulesPreparer(ctx context.Context, resourceGroupName string, namespaceName string, topicName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "topicName": autorest.Encode("path", topicName), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}/authorizationRules", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListAuthorizationRulesSender sends the ListAuthorizationRules request. The method will close the +// http.Response Body if it receives an error. +func (client TopicsClient) ListAuthorizationRulesSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListAuthorizationRulesResponder handles the response to the ListAuthorizationRules request. The method always +// closes the http.Response Body. +func (client TopicsClient) ListAuthorizationRulesResponder(resp *http.Response) (result SBAuthorizationRuleListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listAuthorizationRulesNextResults retrieves the next set of results, if any. +func (client TopicsClient) listAuthorizationRulesNextResults(lastResults SBAuthorizationRuleListResult) (result SBAuthorizationRuleListResult, err error) { + req, err := lastResults.sBAuthorizationRuleListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "servicebus.TopicsClient", "listAuthorizationRulesNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListAuthorizationRulesSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "servicebus.TopicsClient", "listAuthorizationRulesNextResults", resp, "Failure sending next results request") + } + result, err = client.ListAuthorizationRulesResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.TopicsClient", "listAuthorizationRulesNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListAuthorizationRulesComplete enumerates all values, automatically crossing page boundaries as required. +func (client TopicsClient) ListAuthorizationRulesComplete(ctx context.Context, resourceGroupName string, namespaceName string, topicName string) (result SBAuthorizationRuleListResultIterator, err error) { + result.page, err = client.ListAuthorizationRules(ctx, resourceGroupName, namespaceName, topicName) + return +} + +// ListByNamespace gets all the topics in a namespace. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// skip - skip is only used if a previous operation returned a partial result. If a previous response contains +// a nextLink element, the value of the nextLink element will include a skip parameter that specifies a +// starting point to use for subsequent calls. +// top - may be used to limit the number of results to the most recent N usageDetails. +func (client TopicsClient) ListByNamespace(ctx context.Context, resourceGroupName string, namespaceName string, skip *int32, top *int32) (result SBTopicListResultPage, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: skip, + Constraints: []validation.Constraint{{Target: "skip", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "skip", Name: validation.InclusiveMaximum, Rule: int64(1000), Chain: nil}, + {Target: "skip", Name: validation.InclusiveMinimum, Rule: 0, Chain: nil}, + }}}}, + {TargetValue: top, + Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, + Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMaximum, Rule: int64(1000), Chain: nil}, + {Target: "top", Name: validation.InclusiveMinimum, Rule: 1, Chain: nil}, + }}}}}); err != nil { + return result, validation.NewError("servicebus.TopicsClient", "ListByNamespace", err.Error()) + } + + result.fn = client.listByNamespaceNextResults + req, err := client.ListByNamespacePreparer(ctx, resourceGroupName, namespaceName, skip, top) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.TopicsClient", "ListByNamespace", nil, "Failure preparing request") + return + } + + resp, err := client.ListByNamespaceSender(req) + if err != nil { + result.stlr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.TopicsClient", "ListByNamespace", resp, "Failure sending request") + return + } + + result.stlr, err = client.ListByNamespaceResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.TopicsClient", "ListByNamespace", resp, "Failure responding to request") + } + + return +} + +// ListByNamespacePreparer prepares the ListByNamespace request. +func (client TopicsClient) ListByNamespacePreparer(ctx context.Context, resourceGroupName string, namespaceName string, skip *int32, top *int32) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + if skip != nil { + queryParameters["$skip"] = autorest.Encode("query", *skip) + } + if top != nil { + queryParameters["$top"] = autorest.Encode("query", *top) + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByNamespaceSender sends the ListByNamespace request. The method will close the +// http.Response Body if it receives an error. +func (client TopicsClient) ListByNamespaceSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListByNamespaceResponder handles the response to the ListByNamespace request. The method always +// closes the http.Response Body. +func (client TopicsClient) ListByNamespaceResponder(resp *http.Response) (result SBTopicListResult, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listByNamespaceNextResults retrieves the next set of results, if any. +func (client TopicsClient) listByNamespaceNextResults(lastResults SBTopicListResult) (result SBTopicListResult, err error) { + req, err := lastResults.sBTopicListResultPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "servicebus.TopicsClient", "listByNamespaceNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListByNamespaceSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "servicebus.TopicsClient", "listByNamespaceNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByNamespaceResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.TopicsClient", "listByNamespaceNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByNamespaceComplete enumerates all values, automatically crossing page boundaries as required. +func (client TopicsClient) ListByNamespaceComplete(ctx context.Context, resourceGroupName string, namespaceName string, skip *int32, top *int32) (result SBTopicListResultIterator, err error) { + result.page, err = client.ListByNamespace(ctx, resourceGroupName, namespaceName, skip, top) + return +} + +// ListKeys gets the primary and secondary connection strings for the topic. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// topicName - the topic name. +// authorizationRuleName - the authorizationrule name. +func (client TopicsClient) ListKeys(ctx context.Context, resourceGroupName string, namespaceName string, topicName string, authorizationRuleName string) (result AccessKeys, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: topicName, + Constraints: []validation.Constraint{{Target: "topicName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: authorizationRuleName, + Constraints: []validation.Constraint{{Target: "authorizationRuleName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "authorizationRuleName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.TopicsClient", "ListKeys", err.Error()) + } + + req, err := client.ListKeysPreparer(ctx, resourceGroupName, namespaceName, topicName, authorizationRuleName) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.TopicsClient", "ListKeys", nil, "Failure preparing request") + return + } + + resp, err := client.ListKeysSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.TopicsClient", "ListKeys", resp, "Failure sending request") + return + } + + result, err = client.ListKeysResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.TopicsClient", "ListKeys", resp, "Failure responding to request") + } + + return +} + +// ListKeysPreparer prepares the ListKeys request. +func (client TopicsClient) ListKeysPreparer(ctx context.Context, resourceGroupName string, namespaceName string, topicName string, authorizationRuleName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "authorizationRuleName": autorest.Encode("path", authorizationRuleName), + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "topicName": autorest.Encode("path", topicName), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}/authorizationRules/{authorizationRuleName}/ListKeys", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListKeysSender sends the ListKeys request. The method will close the +// http.Response Body if it receives an error. +func (client TopicsClient) ListKeysSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListKeysResponder handles the response to the ListKeys request. The method always +// closes the http.Response Body. +func (client TopicsClient) ListKeysResponder(resp *http.Response) (result AccessKeys, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// RegenerateKeys regenerates primary or secondary connection strings for the topic. +// Parameters: +// resourceGroupName - name of the Resource group within the Azure subscription. +// namespaceName - the namespace name +// topicName - the topic name. +// authorizationRuleName - the authorizationrule name. +// parameters - parameters supplied to regenerate the authorization rule. +func (client TopicsClient) RegenerateKeys(ctx context.Context, resourceGroupName string, namespaceName string, topicName string, authorizationRuleName string, parameters RegenerateAccessKeyParameters) (result AccessKeys, err error) { + if err := validation.Validate([]validation.Validation{ + {TargetValue: resourceGroupName, + Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, + {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: namespaceName, + Constraints: []validation.Constraint{{Target: "namespaceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "namespaceName", Name: validation.MinLength, Rule: 6, Chain: nil}}}, + {TargetValue: topicName, + Constraints: []validation.Constraint{{Target: "topicName", Name: validation.MinLength, Rule: 1, Chain: nil}}}, + {TargetValue: authorizationRuleName, + Constraints: []validation.Constraint{{Target: "authorizationRuleName", Name: validation.MaxLength, Rule: 50, Chain: nil}, + {Target: "authorizationRuleName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { + return result, validation.NewError("servicebus.TopicsClient", "RegenerateKeys", err.Error()) + } + + req, err := client.RegenerateKeysPreparer(ctx, resourceGroupName, namespaceName, topicName, authorizationRuleName, parameters) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.TopicsClient", "RegenerateKeys", nil, "Failure preparing request") + return + } + + resp, err := client.RegenerateKeysSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "servicebus.TopicsClient", "RegenerateKeys", resp, "Failure sending request") + return + } + + result, err = client.RegenerateKeysResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "servicebus.TopicsClient", "RegenerateKeys", resp, "Failure responding to request") + } + + return +} + +// RegenerateKeysPreparer prepares the RegenerateKeys request. +func (client TopicsClient) RegenerateKeysPreparer(ctx context.Context, resourceGroupName string, namespaceName string, topicName string, authorizationRuleName string, parameters RegenerateAccessKeyParameters) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "authorizationRuleName": autorest.Encode("path", authorizationRuleName), + "namespaceName": autorest.Encode("path", namespaceName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "topicName": autorest.Encode("path", topicName), + } + + const APIVersion = "2017-04-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPost(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}/authorizationRules/{authorizationRuleName}/regenerateKeys", pathParameters), + autorest.WithJSON(parameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// RegenerateKeysSender sends the RegenerateKeys request. The method will close the +// http.Response Body if it receives an error. +func (client TopicsClient) RegenerateKeysSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// RegenerateKeysResponder handles the response to the RegenerateKeys request. The method always +// closes the http.Response Body. +func (client TopicsClient) RegenerateKeysResponder(resp *http.Response) (result AccessKeys, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/version.go b/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/version.go new file mode 100644 index 00000000..f9c6735b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus/version.go @@ -0,0 +1,30 @@ +package servicebus + +import "github.com/Azure/azure-sdk-for-go/version" + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// 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 Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +// UserAgent returns the UserAgent string to use when sending http.Requests. +func UserAgent() string { + return "Azure-SDK-For-Go/" + version.Number + " servicebus/2017-04-01" +} + +// Version returns the semantic version (see http://semver.org) of the client. +func Version() string { + return version.Number +} From ecb3954d4ba853f0d839377cf0c2fff9cf486122 Mon Sep 17 00:00:00 2001 From: Marc Sensenich Date: Sun, 18 Nov 2018 13:03:35 +0000 Subject: [PATCH 03/23] fixup! [GH-42] Add vendor packages for Service Bus --- Gopkg.lock | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Gopkg.lock b/Gopkg.lock index 07dc5dc2..159cc855 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -10,11 +10,12 @@ revision = "75cd24fc2f2c2a2088577d12123ddee5f54e0675" [[projects]] - digest = "1:beb1ef131d100d1c6926743673a0f248cffb5741cc68858a18602076f12173dd" + digest = "1:7798129b37c4132f5b1d87964f070b120124eedfc7d670719805e644796251f5" name = "github.com/Azure/azure-sdk-for-go" packages = [ "services/appinsights/v1/insights", "services/preview/monitor/mgmt/2018-03-01/insights", + "services/servicebus/mgmt/2017-04-01/servicebus", "version", ] pruneopts = "UT" @@ -1036,6 +1037,7 @@ input-imports = [ "github.com/Azure/azure-sdk-for-go/services/appinsights/v1/insights", "github.com/Azure/azure-sdk-for-go/services/preview/monitor/mgmt/2018-03-01/insights", + "github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus", "github.com/Azure/go-autorest/autorest/azure/auth", "github.com/golang/glog", "github.com/kubernetes-incubator/custom-metrics-apiserver/pkg/cmd", From 29eec1d0cad1cf74a252041c858d622541517b28 Mon Sep 17 00:00:00 2001 From: Marc Sensenich Date: Sun, 18 Nov 2018 13:10:59 +0000 Subject: [PATCH 04/23] [GH-42] Add the Service Bus Client to the Provider --- main.go | 8 ++++---- pkg/provider/provider.go | 36 ++++++++++++++++++------------------ 2 files changed, 22 insertions(+), 22 deletions(-) diff --git a/main.go b/main.go index 01ffeacc..6f262104 100755 --- a/main.go +++ b/main.go @@ -12,14 +12,13 @@ import ( "time" "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/appinsights" - "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/instancemetadata" "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/monitor" - "github.com/Azure/azure-k8s-metrics-adapter/pkg/metriccache" - + "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/servicebus" clientset "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned" informers "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/informers/externalversions" "github.com/Azure/azure-k8s-metrics-adapter/pkg/controller" + "github.com/Azure/azure-k8s-metrics-adapter/pkg/metriccache" azureprovider "github.com/Azure/azure-k8s-metrics-adapter/pkg/provider" "github.com/golang/glog" basecmd "github.com/kubernetes-incubator/custom-metrics-apiserver/pkg/cmd" @@ -67,10 +66,11 @@ func setupAzureProvider(cmd *basecmd.AdapterBase, metricsCache *metriccache.Metr } defaultSubscriptionID := getDefaultSubscriptionID() + serviceBusSubscriptionClient := servicebus.NewClient(defaultSubscriptionID) monitorClient := monitor.NewClient(defaultSubscriptionID) appinsightsClient := appinsights.NewClient() - azureProvider := azureprovider.NewAzureProvider(defaultSubscriptionID, mapper, dynamicClient, appinsightsClient, monitorClient, metricsCache) + azureProvider := azureprovider.NewAzureProvider(defaultSubscriptionID, mapper, dynamicClient, appinsightsClient, monitorClient, serviceBusSubscriptionClient, metricsCache) cmd.WithCustomMetrics(azureProvider) cmd.WithExternalMetrics(azureProvider) } diff --git a/pkg/provider/provider.go b/pkg/provider/provider.go index 2a6dd184..400872e0 100755 --- a/pkg/provider/provider.go +++ b/pkg/provider/provider.go @@ -4,32 +4,32 @@ package provider import ( "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/appinsights" - "github.com/Azure/azure-k8s-metrics-adapter/pkg/metriccache" - "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/monitor" - + "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/servicebus" + "github.com/Azure/azure-k8s-metrics-adapter/pkg/metriccache" + "github.com/kubernetes-incubator/custom-metrics-apiserver/pkg/provider" apimeta "k8s.io/apimachinery/pkg/api/meta" "k8s.io/client-go/dynamic" - - "github.com/kubernetes-incubator/custom-metrics-apiserver/pkg/provider" ) type AzureProvider struct { - appinsightsClient appinsights.AzureAppInsightsClient - mapper apimeta.RESTMapper - kubeClient dynamic.Interface - monitorClient monitor.AzureMonitorClient - metricCache *metriccache.MetricCache - defaultSubscriptionID string + appinsightsClient appinsights.AzureAppInsightsClient + mapper apimeta.RESTMapper + kubeClient dynamic.Interface + monitorClient monitor.AzureMonitorClient + metricCache *metriccache.MetricCache + serviceBusSubscriptionClient servicebus.AzureServiceBusSubscriptionClient + defaultSubscriptionID string } -func NewAzureProvider(defaultSubscriptionID string, mapper apimeta.RESTMapper, kubeClient dynamic.Interface, appinsightsClient appinsights.AzureAppInsightsClient, monitorClient monitor.AzureMonitorClient, metricCache *metriccache.MetricCache) provider.MetricsProvider { +func NewAzureProvider(defaultSubscriptionID string, mapper apimeta.RESTMapper, kubeClient dynamic.Interface, appinsightsClient appinsights.AzureAppInsightsClient, monitorClient monitor.AzureMonitorClient, serviceBusSubscriptionClient servicebus.AzureServiceBusSubscriptionClient, metricCache *metriccache.MetricCache) provider.MetricsProvider { return &AzureProvider{ - defaultSubscriptionID: defaultSubscriptionID, - mapper: mapper, - kubeClient: kubeClient, - appinsightsClient: appinsightsClient, - monitorClient: monitorClient, - metricCache: metricCache, + defaultSubscriptionID: defaultSubscriptionID, + mapper: mapper, + kubeClient: kubeClient, + appinsightsClient: appinsightsClient, + monitorClient: monitorClient, + metricCache: metricCache, + serviceBusSubscriptionClient: serviceBusSubscriptionClient, } } From 1512afa372b9e98cc854dac7146874c70bf9558e Mon Sep 17 00:00:00 2001 From: Marc Sensenich Date: Sun, 18 Nov 2018 16:25:56 +0000 Subject: [PATCH 05/23] [GH-42] Create Azure External Metric Types Generic Allows for providers of External Metrics to implement a shared interface --- pkg/azure/external_metric_types/client.go | 9 ++ .../metricrequest.go | 78 +++++++--- pkg/azure/external_metric_types/providers.go | 8 + pkg/azure/servicebus/metricrequest_test.go | 146 ------------------ .../servicebus/subscription_count_client.go | 19 +-- .../subscription_count_client_test.go | 13 +- 6 files changed, 90 insertions(+), 183 deletions(-) create mode 100644 pkg/azure/external_metric_types/client.go rename pkg/azure/{servicebus => external_metric_types}/metricrequest.go (53%) create mode 100644 pkg/azure/external_metric_types/providers.go delete mode 100644 pkg/azure/servicebus/metricrequest_test.go diff --git a/pkg/azure/external_metric_types/client.go b/pkg/azure/external_metric_types/client.go new file mode 100644 index 00000000..985200d6 --- /dev/null +++ b/pkg/azure/external_metric_types/client.go @@ -0,0 +1,9 @@ +package externalmetrictypes + +type AzureExternalMetricResponse struct { + Total int64 +} + +type AzureExternalMetricClient interface { + GetAzureMetric(azMetricRequest AzureExternalMetricRequest) (AzureExternalMetricResponse, error) +} diff --git a/pkg/azure/servicebus/metricrequest.go b/pkg/azure/external_metric_types/metricrequest.go similarity index 53% rename from pkg/azure/servicebus/metricrequest.go rename to pkg/azure/external_metric_types/metricrequest.go index 42f42598..b9fa4c0b 100644 --- a/pkg/azure/servicebus/metricrequest.go +++ b/pkg/azure/external_metric_types/metricrequest.go @@ -1,29 +1,38 @@ -package servicebus +package externalmetrictypes import ( "errors" "fmt" + "strings" + "time" "github.com/golang/glog" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/selection" ) -type AzureMetricRequest struct { - MetricName string - ResourceGroup string - Namespace string - Topic string - Subscription string - SubscriptionID string +type AzureExternalMetricRequest struct { + MetricName string + SubscriptionID string + Type string + ResourceName string + ResourceProviderNamespace string + ResourceType string + Aggregation string + Timespan string + Filter string + ResourceGroup string + Namespace string + Topic string + Subscription string } -func ParseAzureMetric(metricSelector labels.Selector, defaultSubscriptionID string) (AzureMetricRequest, error) { +func ParseAzureMetric(metricSelector labels.Selector, defaultSubscriptionID string) (AzureExternalMetricRequest, error) { glog.V(4).Infof("Parsing a received AzureMetric") glog.V(6).Infof("%v", metricSelector) if metricSelector == nil { - return AzureMetricRequest{}, fmt.Errorf("metricSelector cannot be nil") + return AzureExternalMetricRequest{}, fmt.Errorf("metricSelector cannot be nil") } // Using selectors to pass required values thorugh @@ -32,24 +41,52 @@ func ParseAzureMetric(metricSelector labels.Selector, defaultSubscriptionID stri // There is are restrictions so using some conversion // restrictions here // note: requirement values are already validated by apiserver - merticReq := AzureMetricRequest{ + merticReq := AzureExternalMetricRequest{ + Timespan: TimeSpan(), SubscriptionID: defaultSubscriptionID, } + requirements, _ := metricSelector.Requirements() for _, request := range requirements { if request.Operator() != selection.Equals { - return AzureMetricRequest{}, errors.New("selector type not supported. only equals is supported at this time") + return AzureExternalMetricRequest{}, errors.New("selector type not supported. only equals is supported at this time") } value := request.Values().List()[0] switch request.Key() { + // Shared case "metricName": glog.V(4).Infof("AzureMetric metricName: %s", value) merticReq.MetricName = value case "resourceGroup": glog.V(4).Infof("AzureMetric resourceGroup: %s", value) merticReq.ResourceGroup = value + case "subscriptionID": + // if sub id is passed via label selectors then it takes precedence + glog.V(4).Infof("AzureMetric override azure subscription id with : %s", value) + merticReq.SubscriptionID = value + // Monitor + case "resourceName": + glog.V(2).Infof("resourceName: %s", value) + merticReq.ResourceName = value + case "resourceProviderNamespace": + glog.V(2).Infof("resourceProviderNamespace: %s", value) + merticReq.ResourceProviderNamespace = value + case "resourceType": + glog.V(2).Infof("resourceType: %s", value) + merticReq.ResourceType = value + case "aggregation": + glog.V(2).Infof("aggregation: %s", value) + merticReq.Aggregation = value + case "filter": + // TODO: Should handle filters by converting equality and setbased label selectors + // to oData syntax: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors + glog.V(2).Infof("filter: %s", value) + filterStrings := strings.Split(value, "_") + merticReq.Filter = fmt.Sprintf("%s %s '%s'", filterStrings[0], filterStrings[1], filterStrings[2]) + glog.V(2).Infof("filter formatted: %s", merticReq.Filter) + // Service Bus case "namespace": glog.V(4).Infof("AzureMetric namespace: %s", value) merticReq.Namespace = value @@ -59,12 +96,8 @@ func ParseAzureMetric(metricSelector labels.Selector, defaultSubscriptionID stri case "subscription": glog.V(4).Infof("AzureMetric subscription: %s", value) merticReq.Subscription = value - case "subscriptionID": - // if sub id is passed via label selectors then it takes precedence - glog.V(4).Infof("AzureMetric override azure subscription id with : %s", value) - merticReq.SubscriptionID = value default: - return AzureMetricRequest{}, fmt.Errorf("selector label '%s' not supported", request.Key()) + return AzureExternalMetricRequest{}, fmt.Errorf("selector label '%s' not supported", request.Key()) } } @@ -88,7 +121,7 @@ func IsInvalidMetricRequestError(err error) bool { return false } -func (amr AzureMetricRequest) Validate() error { +func (amr AzureExternalMetricRequest) Validate() error { if amr.MetricName == "" { return InvalidMetricRequestError{err: "metricName is required"} } @@ -111,3 +144,12 @@ func (amr AzureMetricRequest) Validate() error { // if here then valid! return nil } + +// TimeSpan sets the default time to aggregate a metric +func TimeSpan() string { + // defaults to last five minutes. + // TODO support configuration via config + endtime := time.Now().UTC().Format(time.RFC3339) + starttime := time.Now().Add(-(5 * time.Minute)).UTC().Format(time.RFC3339) + return fmt.Sprintf("%s/%s", starttime, endtime) +} diff --git a/pkg/azure/external_metric_types/providers.go b/pkg/azure/external_metric_types/providers.go new file mode 100644 index 00000000..f33657a8 --- /dev/null +++ b/pkg/azure/external_metric_types/providers.go @@ -0,0 +1,8 @@ +package externalmetrictypes + +type AzureExternalMetricProvider string + +const ( + Monitor AzureExternalMetricProvider = "monitor" + ServiceBusSubscription AzureExternalMetricProvider = "servicebussubscription" +) diff --git a/pkg/azure/servicebus/metricrequest_test.go b/pkg/azure/servicebus/metricrequest_test.go deleted file mode 100644 index e66e85a3..00000000 --- a/pkg/azure/servicebus/metricrequest_test.go +++ /dev/null @@ -1,146 +0,0 @@ -package servicebus - -import ( - "fmt" - "reflect" - "testing" - - "k8s.io/apimachinery/pkg/labels" -) - -const subscription = "test-sub" -const topic = "test-topic" -const namespace = "test-namespace" -const resourceGroup = "test-resource-group" -const metricName = "metric-name" -const subscriptionID = "1234-5678" - -var validLabelSelector = fmt.Sprintf("subscription=%s,topic=%s,namespace=%s,resourceGroup=%s,metricName=%s", subscription, topic, namespace, resourceGroup, metricName) - -type testArguments struct { - metricSelector string - defaultSubscriptionID string -} - -// List of test cases that will be run for validating the parsing of metric configuration -var testCases = []struct { - name string - args testArguments - want AzureMetricRequest - wantErr bool - validate bool -}{ - // Begin test cases - { - name: "Test if metricSelector is nil do not fail", - args: testArguments{ - defaultSubscriptionID: "", - metricSelector: "", - }, - want: AzureMetricRequest{}, - wantErr: true, - validate: false, - }, - { - name: "Test insufficient data expect an error", - args: testArguments{ - defaultSubscriptionID: "", - metricSelector: "namespace=testing", - }, - want: AzureMetricRequest{}, - wantErr: true, - validate: true, - }, - { - name: "Test valid case with overriding subscription ID passed in", - args: testArguments{ - defaultSubscriptionID: subscriptionID, - metricSelector: validLabelSelector, - }, - want: AzureMetricRequest{ - Namespace: namespace, - Subscription: subscription, - Topic: topic, - MetricName: metricName, - ResourceGroup: resourceGroup, - SubscriptionID: subscriptionID, - }, - wantErr: false, - validate: true, - }, - { - name: "Test valid case with overriding subscription ID in selector", - args: testArguments{ - defaultSubscriptionID: subscriptionID, - metricSelector: fmt.Sprintf("%s,subscriptionID=%s", validLabelSelector, subscriptionID), - }, - want: AzureMetricRequest{ - Namespace: namespace, - Subscription: subscription, - Topic: topic, - MetricName: metricName, - ResourceGroup: resourceGroup, - SubscriptionID: subscriptionID, - }, - wantErr: false, - validate: true, - }, - { - name: "Test valid case with overriding subscription ID in selector", - args: testArguments{ - defaultSubscriptionID: subscriptionID, - metricSelector: fmt.Sprintf("%s,subscriptionID=%s", validLabelSelector, subscriptionID), - }, - want: AzureMetricRequest{ - Namespace: namespace, - Subscription: subscription, - Topic: topic, - MetricName: metricName, - ResourceGroup: resourceGroup, - SubscriptionID: subscriptionID, - }, - wantErr: false, - validate: true, - }, -} - -// Test the parsing of the External Metric Configuration that is expected from -// the Custom Resource Definition for the External Metric Provider -func TestParsingAzureExternalMetricConfiguration(t *testing.T) { - // Run through the test cases and valid expected outcomes - for _, tt := range testCases { - t.Run(tt.name, func(t *testing.T) { - metricSelector, err := labels.Parse(tt.args.metricSelector) - if err != nil { - t.Errorf("ParseAzureMetric() error parsing metricSelector %s", metricSelector) - } - - if len(tt.args.metricSelector) == 0 { - metricSelector = nil - } - - got, parseErr := ParseAzureMetric(metricSelector, tt.args.defaultSubscriptionID) - - if tt.validate { - err = got.Validate() - if (err != nil) != tt.wantErr { - t.Errorf("ParseAzureMetric() validation error = %v", err) - } - } - - if err != nil { - return - } - - if (parseErr != nil) != tt.wantErr { - t.Errorf("ParseAzureMetric() error = %v, wantErr %v", parseErr, tt.wantErr) - return - } - - if !reflect.DeepEqual(got, tt.want) { - t.Errorf("ParseAzureMetric() = %v, want %v", got, tt.want) - return - } - }) - } -} diff --git a/pkg/azure/servicebus/subscription_count_client.go b/pkg/azure/servicebus/subscription_count_client.go index 244e7e24..9e76f0d7 100644 --- a/pkg/azure/servicebus/subscription_count_client.go +++ b/pkg/azure/servicebus/subscription_count_client.go @@ -3,19 +3,12 @@ package servicebus import ( "context" + "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/external_metric_types" "github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus" "github.com/Azure/go-autorest/autorest/azure/auth" "github.com/golang/glog" ) -type AzureMetricResponse struct { - Total int64 -} - -type AzureServiceBusSubscriptionClient interface { - GetAzureMetric(azMetricRequest AzureMetricRequest) (AzureMetricResponse, error) -} - type servicebusSubscriptionsClient interface { Get(ctx context.Context, resourceGroupName string, namespaceName string, topicName string, subscriptionName string) (result servicebus.SBSubscription, err error) } @@ -25,7 +18,7 @@ type servicebusClient struct { DefaultSubscriptionID string } -func NewClient(defaultSubscriptionID string) AzureServiceBusSubscriptionClient { +func NewClient(defaultSubscriptionID string) externalmetrictypes.AzureExternalMetricClient { glog.V(2).Info("Creating a new Azure Service Bus Subscriptions client") client := servicebus.NewSubscriptionsClient(defaultSubscriptionID) authorizer, err := auth.NewAuthorizerFromEnvironment() @@ -46,11 +39,11 @@ func newClient(defaultsubscriptionID string, client servicebusSubscriptionsClien } } -func (c *servicebusClient) GetAzureMetric(azMetricRequest AzureMetricRequest) (AzureMetricResponse, error) { +func (c *servicebusClient) GetAzureMetric(azMetricRequest externalmetrictypes.AzureExternalMetricRequest) (externalmetrictypes.AzureExternalMetricResponse, error) { glog.V(6).Infof("Received metric request:\n%v", azMetricRequest) err := azMetricRequest.Validate() if err != nil { - return AzureMetricResponse{}, err + return externalmetrictypes.AzureExternalMetricResponse{}, err } glog.V(2).Infof("Requesting Service Bus Subscription %s to topic %s in namespace %s from resource group %s", azMetricRequest.Subscription, azMetricRequest.Topic, azMetricRequest.Namespace, azMetricRequest.ResourceGroup) @@ -62,7 +55,7 @@ func (c *servicebusClient) GetAzureMetric(azMetricRequest AzureMetricRequest) (A azMetricRequest.Subscription, ) if err != nil { - return AzureMetricResponse{}, err + return externalmetrictypes.AzureExternalMetricResponse{}, err } glog.V(2).Infof("Successfully retrieved Service Bus Subscription %s to topic %s in namespace %s from resource group %s", azMetricRequest.Subscription, azMetricRequest.Topic, azMetricRequest.Namespace, azMetricRequest.ResourceGroup) @@ -73,7 +66,7 @@ func (c *servicebusClient) GetAzureMetric(azMetricRequest AzureMetricRequest) (A glog.V(4).Infof("Service Bus Subscription active message count: %d", activeMessageCount) // TODO set Value based on aggregations type - return AzureMetricResponse{ + return externalmetrictypes.AzureExternalMetricResponse{ Total: activeMessageCount, }, nil } diff --git a/pkg/azure/servicebus/subscription_count_client_test.go b/pkg/azure/servicebus/subscription_count_client_test.go index 2fdd24f4..1e283484 100644 --- a/pkg/azure/servicebus/subscription_count_client_test.go +++ b/pkg/azure/servicebus/subscription_count_client_test.go @@ -5,22 +5,23 @@ import ( "errors" "testing" + "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/external_metric_types" "github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus" ) func TestIfEmptyRequestGetError(t *testing.T) { - monitorClient := newFakeServicebusClient(servicebus.SBSubscription{}, nil) + servicebusClient := newFakeServicebusClient(servicebus.SBSubscription{}, nil) - client := newClient("", monitorClient) + client := newClient("", servicebusClient) - request := AzureMetricRequest{} + request := externalmetrictypes.AzureExternalMetricRequest{} _, err := client.GetAzureMetric(request) if err == nil { t.Errorf("no error after processing got: %v, want error", nil) } - if !IsInvalidMetricRequestError(err) { + if !externalmetrictypes.IsInvalidMetricRequestError(err) { t.Errorf("should be InvalidMetricRequest error got %v, want InvalidMetricRequestError", err) } } @@ -77,8 +78,8 @@ func makeResponse(value int64) servicebus.SBSubscription { return response } -func newMetricRequest() AzureMetricRequest { - return AzureMetricRequest{ +func newMetricRequest() externalmetrictypes.AzureExternalMetricRequest { + return externalmetrictypes.AzureExternalMetricRequest{ ResourceGroup: "ResourceGroup", SubscriptionID: "SubscriptionID", MetricName: "MetricName", From 99dd44bc0fb76d4b51a05f832d7879cbc558ce45 Mon Sep 17 00:00:00 2001 From: Marc Sensenich Date: Sun, 18 Nov 2018 16:31:48 +0000 Subject: [PATCH 06/23] fixup! [GH-42] Create Azure External Metric Types Generic --- pkg/provider/provider.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pkg/provider/provider.go b/pkg/provider/provider.go index 400872e0..a15c67d6 100755 --- a/pkg/provider/provider.go +++ b/pkg/provider/provider.go @@ -4,8 +4,8 @@ package provider import ( "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/appinsights" + "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/external_metric_types" "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/monitor" - "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/servicebus" "github.com/Azure/azure-k8s-metrics-adapter/pkg/metriccache" "github.com/kubernetes-incubator/custom-metrics-apiserver/pkg/provider" apimeta "k8s.io/apimachinery/pkg/api/meta" @@ -18,11 +18,11 @@ type AzureProvider struct { kubeClient dynamic.Interface monitorClient monitor.AzureMonitorClient metricCache *metriccache.MetricCache - serviceBusSubscriptionClient servicebus.AzureServiceBusSubscriptionClient + serviceBusSubscriptionClient externalmetrictypes.AzureExternalMetricClient defaultSubscriptionID string } -func NewAzureProvider(defaultSubscriptionID string, mapper apimeta.RESTMapper, kubeClient dynamic.Interface, appinsightsClient appinsights.AzureAppInsightsClient, monitorClient monitor.AzureMonitorClient, serviceBusSubscriptionClient servicebus.AzureServiceBusSubscriptionClient, metricCache *metriccache.MetricCache) provider.MetricsProvider { +func NewAzureProvider(defaultSubscriptionID string, mapper apimeta.RESTMapper, kubeClient dynamic.Interface, appinsightsClient appinsights.AzureAppInsightsClient, monitorClient monitor.AzureMonitorClient, serviceBusSubscriptionClient externalmetrictypes.AzureExternalMetricClient, metricCache *metriccache.MetricCache) provider.MetricsProvider { return &AzureProvider{ defaultSubscriptionID: defaultSubscriptionID, mapper: mapper, From 417f91585c4a6a75368b85ada4006c1a567ef615 Mon Sep 17 00:00:00 2001 From: Marc Sensenich Date: Sun, 18 Nov 2018 16:35:21 +0000 Subject: [PATCH 07/23] [GH-42] Generate v1alpha2 with Service Bus Config --- hack/update-codegen.sh | 2 +- pkg/apis/metrics/v1alpha2/custommetric.go | 44 ++++ pkg/apis/metrics/v1alpha2/doc.go | 4 + pkg/apis/metrics/v1alpha2/externalmetric.go | 63 +++++ pkg/apis/metrics/v1alpha2/register.go | 39 +++ .../metrics/v1alpha2/zz_generated.deepcopy.go | 228 ++++++++++++++++++ pkg/client/clientset/versioned/clientset.go | 14 ++ .../versioned/fake/clientset_generated.go | 7 + .../clientset/versioned/fake/register.go | 2 + .../clientset/versioned/scheme/register.go | 2 + .../typed/metrics/v1alpha1/custommetric.go | 17 ++ .../typed/metrics/v1alpha1/externalmetric.go | 17 ++ .../typed/metrics/v1alpha2/custommetric.go | 158 ++++++++++++ .../versioned/typed/metrics/v1alpha2/doc.go | 20 ++ .../typed/metrics/v1alpha2/externalmetric.go | 158 ++++++++++++ .../typed/metrics/v1alpha2/fake/doc.go | 20 ++ .../v1alpha2/fake/fake_custommetric.go | 116 +++++++++ .../v1alpha2/fake/fake_externalmetric.go | 116 +++++++++ .../v1alpha2/fake/fake_metrics_client.go | 44 ++++ .../metrics/v1alpha2/generated_expansion.go | 23 ++ .../typed/metrics/v1alpha2/metrics_client.go | 95 ++++++++ .../informers/externalversions/generic.go | 7 + .../internalinterfaces/factory_interfaces.go | 2 + .../externalversions/metrics/interface.go | 8 + .../metrics/v1alpha2/custommetric.go | 89 +++++++ .../metrics/v1alpha2/externalmetric.go | 89 +++++++ .../metrics/v1alpha2/interface.go | 52 ++++ .../listers/metrics/v1alpha2/custommetric.go | 94 ++++++++ .../metrics/v1alpha2/expansion_generated.go | 35 +++ .../metrics/v1alpha2/externalmetric.go | 94 ++++++++ 30 files changed, 1658 insertions(+), 1 deletion(-) create mode 100755 pkg/apis/metrics/v1alpha2/custommetric.go create mode 100644 pkg/apis/metrics/v1alpha2/doc.go create mode 100644 pkg/apis/metrics/v1alpha2/externalmetric.go create mode 100644 pkg/apis/metrics/v1alpha2/register.go create mode 100644 pkg/apis/metrics/v1alpha2/zz_generated.deepcopy.go create mode 100644 pkg/client/clientset/versioned/typed/metrics/v1alpha2/custommetric.go create mode 100644 pkg/client/clientset/versioned/typed/metrics/v1alpha2/doc.go create mode 100644 pkg/client/clientset/versioned/typed/metrics/v1alpha2/externalmetric.go create mode 100644 pkg/client/clientset/versioned/typed/metrics/v1alpha2/fake/doc.go create mode 100644 pkg/client/clientset/versioned/typed/metrics/v1alpha2/fake/fake_custommetric.go create mode 100644 pkg/client/clientset/versioned/typed/metrics/v1alpha2/fake/fake_externalmetric.go create mode 100644 pkg/client/clientset/versioned/typed/metrics/v1alpha2/fake/fake_metrics_client.go create mode 100644 pkg/client/clientset/versioned/typed/metrics/v1alpha2/generated_expansion.go create mode 100644 pkg/client/clientset/versioned/typed/metrics/v1alpha2/metrics_client.go create mode 100644 pkg/client/informers/externalversions/metrics/v1alpha2/custommetric.go create mode 100644 pkg/client/informers/externalversions/metrics/v1alpha2/externalmetric.go create mode 100644 pkg/client/informers/externalversions/metrics/v1alpha2/interface.go create mode 100644 pkg/client/listers/metrics/v1alpha2/custommetric.go create mode 100644 pkg/client/listers/metrics/v1alpha2/expansion_generated.go create mode 100644 pkg/client/listers/metrics/v1alpha2/externalmetric.go diff --git a/hack/update-codegen.sh b/hack/update-codegen.sh index 4d2cb9bc..e6c13f3b 100755 --- a/hack/update-codegen.sh +++ b/hack/update-codegen.sh @@ -7,4 +7,4 @@ set -o pipefail $GOPATH/src/k8s.io/code-generator/generate-groups.sh all \ github.com/Azure/azure-k8s-metrics-adapter/pkg/client \ github.com/Azure/azure-k8s-metrics-adapter/pkg/apis \ - metrics:v1alpha1 + metrics:v1alpha1,v1alpha2 diff --git a/pkg/apis/metrics/v1alpha2/custommetric.go b/pkg/apis/metrics/v1alpha2/custommetric.go new file mode 100755 index 00000000..0db627ca --- /dev/null +++ b/pkg/apis/metrics/v1alpha2/custommetric.go @@ -0,0 +1,44 @@ +package v1alpha2 + +import ( + meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// +genclient +// +genclient:noStatus +// +genclient:skipVerbs=patch +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// CustomMetric describes a configuration for Application insights +type CustomMetric struct { + // TypeMeta is the metadata for the resource, like kind and apiversion + meta_v1.TypeMeta `json:",inline"` + + // ObjectMeta contains the metadata for the particular object (name, namespace, self link, labels, etc) + meta_v1.ObjectMeta `json:"metadata,omitempty"` + + // Spec is the custom resource spec + Spec CustomMetricSpec `json:"spec"` +} + +// CustomMetricSpec is the spec for a CustomMetric resource +type CustomMetricSpec struct { + MetricConfig CustomMetricConfig `json:"metric"` +} + +// CustomMetricConfig holds app insights configuration +type CustomMetricConfig struct { + MetricName string `json:"metricName"` + ApplicationID string `json:"applicationID"` + Query string `json:"query"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// CustomMetricList is a list of CustomMetric resources +type CustomMetricList struct { + meta_v1.TypeMeta `json:",inline"` + meta_v1.ListMeta `json:"metadata"` + + Items []CustomMetric `json:"items"` +} diff --git a/pkg/apis/metrics/v1alpha2/doc.go b/pkg/apis/metrics/v1alpha2/doc.go new file mode 100644 index 00000000..237d624b --- /dev/null +++ b/pkg/apis/metrics/v1alpha2/doc.go @@ -0,0 +1,4 @@ +// +k8s:deepcopy-gen=package +// +groupName=azure.com + +package v1alpha2 diff --git a/pkg/apis/metrics/v1alpha2/externalmetric.go b/pkg/apis/metrics/v1alpha2/externalmetric.go new file mode 100644 index 00000000..d04aeb17 --- /dev/null +++ b/pkg/apis/metrics/v1alpha2/externalmetric.go @@ -0,0 +1,63 @@ +package v1alpha2 + +import ( + meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// +genclient +// +genclient:noStatus +// +genclient:skipVerbs=patch +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// ExternalMetric describes a ExternalMetric resource +type ExternalMetric struct { + // TypeMeta is the metadata for the resource, like kind and apiversion + meta_v1.TypeMeta `json:",inline"` + + // ObjectMeta contains the metadata for the particular object (name, namespace, self link, labels, etc) + meta_v1.ObjectMeta `json:"metadata,omitempty"` + + // Spec is the custom resource spec + Spec ExternalMetricSpec `json:"spec"` +} + +// ExternalMetricSpec is the spec for a ExternalMetric resource +type ExternalMetricSpec struct { + MetricConfig ExternalMetricConfig `json:"metric"` + AzureConfig AzureConfig `json:"azure"` + Type string `json:"type,omitempty"` +} + +// ExternalMetricConfig holds azure monitor metric configuration +type ExternalMetricConfig struct { + // Shared + MetricName string `json:"metricName,omitempty"` + // Azure Monitor + Aggregation string `json:"aggregation,omitempty"` + Filter string `json:"filter,omitempty"` +} + +// AzureConfig holds Azure configuration for an External Metric +type AzureConfig struct { + // Shared + ResourceGroup string `json:"resourceGroup"` + SubscriptionID string `json:"subscriptionID"` + // Azure Monitor + ResourceName string `json:"resourceName,omitempty"` + ResourceProviderNamespace string `json:"resourceProviderNamespace,omitempty"` + ResourceType string `json:"resourceType,omitempty"` + // Azure Service Bus Topic Subscription + ServiceBusNamespace string `json:"serviceBusNamespace,omitempty"` + ServiceBusTopic string `json:"serviceBusTopic,omitempty"` + ServiceBusSubscription string `json:"serviceBusSubscription,omitempty"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +// ExternalMetricList is a list of ExternalMetric resources +type ExternalMetricList struct { + meta_v1.TypeMeta `json:",inline"` + meta_v1.ListMeta `json:"metadata"` + + Items []ExternalMetric `json:"items"` +} diff --git a/pkg/apis/metrics/v1alpha2/register.go b/pkg/apis/metrics/v1alpha2/register.go new file mode 100644 index 00000000..333afce9 --- /dev/null +++ b/pkg/apis/metrics/v1alpha2/register.go @@ -0,0 +1,39 @@ +package v1alpha2 + +import ( + "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics" + meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" +) + +// GroupVersion is the identifier for the API which includes +// the name of the group and the version of the API +var SchemeGroupVersion = schema.GroupVersion{ + Group: externalmetric.GroupName, + Version: "v1alpha2", +} + +var ( + SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) + AddToScheme = SchemeBuilder.AddToScheme +) + +func Resource(resource string) schema.GroupResource { + return SchemeGroupVersion.WithResource(resource).GroupResource() +} + +// addKnownTypes adds our types to the API scheme by registering +func addKnownTypes(scheme *runtime.Scheme) error { + scheme.AddKnownTypes( + SchemeGroupVersion, + &ExternalMetric{}, + &ExternalMetricList{}, + &CustomMetric{}, + &CustomMetricList{}, + ) + + // register the type in the scheme + meta_v1.AddToGroupVersion(scheme, SchemeGroupVersion) + return nil +} diff --git a/pkg/apis/metrics/v1alpha2/zz_generated.deepcopy.go b/pkg/apis/metrics/v1alpha2/zz_generated.deepcopy.go new file mode 100644 index 00000000..5e2a862a --- /dev/null +++ b/pkg/apis/metrics/v1alpha2/zz_generated.deepcopy.go @@ -0,0 +1,228 @@ +// +build !ignore_autogenerated + +/* +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 deepcopy-gen. DO NOT EDIT. + +package v1alpha2 + +import ( + runtime "k8s.io/apimachinery/pkg/runtime" +) + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *AzureConfig) DeepCopyInto(out *AzureConfig) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AzureConfig. +func (in *AzureConfig) DeepCopy() *AzureConfig { + if in == nil { + return nil + } + out := new(AzureConfig) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CustomMetric) DeepCopyInto(out *CustomMetric) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + out.Spec = in.Spec + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomMetric. +func (in *CustomMetric) DeepCopy() *CustomMetric { + if in == nil { + return nil + } + out := new(CustomMetric) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *CustomMetric) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CustomMetricConfig) DeepCopyInto(out *CustomMetricConfig) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomMetricConfig. +func (in *CustomMetricConfig) DeepCopy() *CustomMetricConfig { + if in == nil { + return nil + } + out := new(CustomMetricConfig) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CustomMetricList) DeepCopyInto(out *CustomMetricList) { + *out = *in + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]CustomMetric, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomMetricList. +func (in *CustomMetricList) DeepCopy() *CustomMetricList { + if in == nil { + return nil + } + out := new(CustomMetricList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *CustomMetricList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CustomMetricSpec) DeepCopyInto(out *CustomMetricSpec) { + *out = *in + out.MetricConfig = in.MetricConfig + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomMetricSpec. +func (in *CustomMetricSpec) DeepCopy() *CustomMetricSpec { + if in == nil { + return nil + } + out := new(CustomMetricSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ExternalMetric) DeepCopyInto(out *ExternalMetric) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + out.Spec = in.Spec + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExternalMetric. +func (in *ExternalMetric) DeepCopy() *ExternalMetric { + if in == nil { + return nil + } + out := new(ExternalMetric) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ExternalMetric) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ExternalMetricConfig) DeepCopyInto(out *ExternalMetricConfig) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExternalMetricConfig. +func (in *ExternalMetricConfig) DeepCopy() *ExternalMetricConfig { + if in == nil { + return nil + } + out := new(ExternalMetricConfig) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ExternalMetricList) DeepCopyInto(out *ExternalMetricList) { + *out = *in + out.TypeMeta = in.TypeMeta + out.ListMeta = in.ListMeta + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ExternalMetric, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExternalMetricList. +func (in *ExternalMetricList) DeepCopy() *ExternalMetricList { + if in == nil { + return nil + } + out := new(ExternalMetricList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ExternalMetricList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ExternalMetricSpec) DeepCopyInto(out *ExternalMetricSpec) { + *out = *in + out.MetricConfig = in.MetricConfig + out.AzureConfig = in.AzureConfig + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExternalMetricSpec. +func (in *ExternalMetricSpec) DeepCopy() *ExternalMetricSpec { + if in == nil { + return nil + } + out := new(ExternalMetricSpec) + in.DeepCopyInto(out) + return out +} diff --git a/pkg/client/clientset/versioned/clientset.go b/pkg/client/clientset/versioned/clientset.go index c08ca14e..3c662b29 100644 --- a/pkg/client/clientset/versioned/clientset.go +++ b/pkg/client/clientset/versioned/clientset.go @@ -20,6 +20,7 @@ package versioned import ( azurev1alpha1 "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned/typed/metrics/v1alpha1" + azurev1alpha2 "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned/typed/metrics/v1alpha2" discovery "k8s.io/client-go/discovery" rest "k8s.io/client-go/rest" flowcontrol "k8s.io/client-go/util/flowcontrol" @@ -30,6 +31,7 @@ type Interface interface { AzureV1alpha1() azurev1alpha1.AzureV1alpha1Interface // Deprecated: please explicitly pick a version if possible. Azure() azurev1alpha1.AzureV1alpha1Interface + AzureV1alpha2() azurev1alpha2.AzureV1alpha2Interface } // Clientset contains the clients for groups. Each group has exactly one @@ -37,6 +39,7 @@ type Interface interface { type Clientset struct { *discovery.DiscoveryClient azureV1alpha1 *azurev1alpha1.AzureV1alpha1Client + azureV1alpha2 *azurev1alpha2.AzureV1alpha2Client } // AzureV1alpha1 retrieves the AzureV1alpha1Client @@ -50,6 +53,11 @@ func (c *Clientset) Azure() azurev1alpha1.AzureV1alpha1Interface { return c.azureV1alpha1 } +// AzureV1alpha2 retrieves the AzureV1alpha2Client +func (c *Clientset) AzureV1alpha2() azurev1alpha2.AzureV1alpha2Interface { + return c.azureV1alpha2 +} + // Discovery retrieves the DiscoveryClient func (c *Clientset) Discovery() discovery.DiscoveryInterface { if c == nil { @@ -70,6 +78,10 @@ func NewForConfig(c *rest.Config) (*Clientset, error) { if err != nil { return nil, err } + cs.azureV1alpha2, err = azurev1alpha2.NewForConfig(&configShallowCopy) + if err != nil { + return nil, err + } cs.DiscoveryClient, err = discovery.NewDiscoveryClientForConfig(&configShallowCopy) if err != nil { @@ -83,6 +95,7 @@ func NewForConfig(c *rest.Config) (*Clientset, error) { func NewForConfigOrDie(c *rest.Config) *Clientset { var cs Clientset cs.azureV1alpha1 = azurev1alpha1.NewForConfigOrDie(c) + cs.azureV1alpha2 = azurev1alpha2.NewForConfigOrDie(c) cs.DiscoveryClient = discovery.NewDiscoveryClientForConfigOrDie(c) return &cs @@ -92,6 +105,7 @@ func NewForConfigOrDie(c *rest.Config) *Clientset { func New(c rest.Interface) *Clientset { var cs Clientset cs.azureV1alpha1 = azurev1alpha1.New(c) + cs.azureV1alpha2 = azurev1alpha2.New(c) cs.DiscoveryClient = discovery.NewDiscoveryClient(c) return &cs diff --git a/pkg/client/clientset/versioned/fake/clientset_generated.go b/pkg/client/clientset/versioned/fake/clientset_generated.go index 325f004e..387285cb 100644 --- a/pkg/client/clientset/versioned/fake/clientset_generated.go +++ b/pkg/client/clientset/versioned/fake/clientset_generated.go @@ -22,6 +22,8 @@ import ( clientset "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned" azurev1alpha1 "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned/typed/metrics/v1alpha1" fakeazurev1alpha1 "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned/typed/metrics/v1alpha1/fake" + azurev1alpha2 "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned/typed/metrics/v1alpha2" + fakeazurev1alpha2 "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned/typed/metrics/v1alpha2/fake" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/discovery" @@ -80,3 +82,8 @@ func (c *Clientset) AzureV1alpha1() azurev1alpha1.AzureV1alpha1Interface { func (c *Clientset) Azure() azurev1alpha1.AzureV1alpha1Interface { return &fakeazurev1alpha1.FakeAzureV1alpha1{Fake: &c.Fake} } + +// AzureV1alpha2 retrieves the AzureV1alpha2Client +func (c *Clientset) AzureV1alpha2() azurev1alpha2.AzureV1alpha2Interface { + return &fakeazurev1alpha2.FakeAzureV1alpha2{Fake: &c.Fake} +} diff --git a/pkg/client/clientset/versioned/fake/register.go b/pkg/client/clientset/versioned/fake/register.go index 421818ca..6d840f81 100644 --- a/pkg/client/clientset/versioned/fake/register.go +++ b/pkg/client/clientset/versioned/fake/register.go @@ -20,6 +20,7 @@ package fake import ( azurev1alpha1 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha1" + azurev1alpha2 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha2" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" schema "k8s.io/apimachinery/pkg/runtime/schema" @@ -32,6 +33,7 @@ var codecs = serializer.NewCodecFactory(scheme) var parameterCodec = runtime.NewParameterCodec(scheme) var localSchemeBuilder = runtime.SchemeBuilder{ azurev1alpha1.AddToScheme, + azurev1alpha2.AddToScheme, } // AddToScheme adds all types of this clientset into the given scheme. This allows composition diff --git a/pkg/client/clientset/versioned/scheme/register.go b/pkg/client/clientset/versioned/scheme/register.go index 0ec83da6..012df9b8 100644 --- a/pkg/client/clientset/versioned/scheme/register.go +++ b/pkg/client/clientset/versioned/scheme/register.go @@ -20,6 +20,7 @@ package scheme import ( azurev1alpha1 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha1" + azurev1alpha2 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha2" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" schema "k8s.io/apimachinery/pkg/runtime/schema" @@ -32,6 +33,7 @@ var Codecs = serializer.NewCodecFactory(Scheme) var ParameterCodec = runtime.NewParameterCodec(Scheme) var localSchemeBuilder = runtime.SchemeBuilder{ azurev1alpha1.AddToScheme, + azurev1alpha2.AddToScheme, } // AddToScheme adds all types of this clientset into the given scheme. This allows composition diff --git a/pkg/client/clientset/versioned/typed/metrics/v1alpha1/custommetric.go b/pkg/client/clientset/versioned/typed/metrics/v1alpha1/custommetric.go index dc7d3a7b..7c065c20 100644 --- a/pkg/client/clientset/versioned/typed/metrics/v1alpha1/custommetric.go +++ b/pkg/client/clientset/versioned/typed/metrics/v1alpha1/custommetric.go @@ -19,6 +19,8 @@ limitations under the License. package v1alpha1 import ( + "time" + v1alpha1 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha1" scheme "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned/scheme" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -73,11 +75,16 @@ func (c *customMetrics) Get(name string, options v1.GetOptions) (result *v1alpha // List takes label and field selectors, and returns the list of CustomMetrics that match those selectors. func (c *customMetrics) List(opts v1.ListOptions) (result *v1alpha1.CustomMetricList, err error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } result = &v1alpha1.CustomMetricList{} err = c.client.Get(). Namespace(c.ns). Resource("custommetrics"). VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). Do(). Into(result) return @@ -85,11 +92,16 @@ func (c *customMetrics) List(opts v1.ListOptions) (result *v1alpha1.CustomMetric // Watch returns a watch.Interface that watches the requested customMetrics. func (c *customMetrics) Watch(opts v1.ListOptions) (watch.Interface, error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } opts.Watch = true return c.client.Get(). Namespace(c.ns). Resource("custommetrics"). VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). Watch() } @@ -131,10 +143,15 @@ func (c *customMetrics) Delete(name string, options *v1.DeleteOptions) error { // DeleteCollection deletes a collection of objects. func (c *customMetrics) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { + var timeout time.Duration + if listOptions.TimeoutSeconds != nil { + timeout = time.Duration(*listOptions.TimeoutSeconds) * time.Second + } return c.client.Delete(). Namespace(c.ns). Resource("custommetrics"). VersionedParams(&listOptions, scheme.ParameterCodec). + Timeout(timeout). Body(options). Do(). Error() diff --git a/pkg/client/clientset/versioned/typed/metrics/v1alpha1/externalmetric.go b/pkg/client/clientset/versioned/typed/metrics/v1alpha1/externalmetric.go index 61ece856..c8c4c642 100644 --- a/pkg/client/clientset/versioned/typed/metrics/v1alpha1/externalmetric.go +++ b/pkg/client/clientset/versioned/typed/metrics/v1alpha1/externalmetric.go @@ -19,6 +19,8 @@ limitations under the License. package v1alpha1 import ( + "time" + v1alpha1 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha1" scheme "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned/scheme" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -73,11 +75,16 @@ func (c *externalMetrics) Get(name string, options v1.GetOptions) (result *v1alp // List takes label and field selectors, and returns the list of ExternalMetrics that match those selectors. func (c *externalMetrics) List(opts v1.ListOptions) (result *v1alpha1.ExternalMetricList, err error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } result = &v1alpha1.ExternalMetricList{} err = c.client.Get(). Namespace(c.ns). Resource("externalmetrics"). VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). Do(). Into(result) return @@ -85,11 +92,16 @@ func (c *externalMetrics) List(opts v1.ListOptions) (result *v1alpha1.ExternalMe // Watch returns a watch.Interface that watches the requested externalMetrics. func (c *externalMetrics) Watch(opts v1.ListOptions) (watch.Interface, error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } opts.Watch = true return c.client.Get(). Namespace(c.ns). Resource("externalmetrics"). VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). Watch() } @@ -131,10 +143,15 @@ func (c *externalMetrics) Delete(name string, options *v1.DeleteOptions) error { // DeleteCollection deletes a collection of objects. func (c *externalMetrics) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { + var timeout time.Duration + if listOptions.TimeoutSeconds != nil { + timeout = time.Duration(*listOptions.TimeoutSeconds) * time.Second + } return c.client.Delete(). Namespace(c.ns). Resource("externalmetrics"). VersionedParams(&listOptions, scheme.ParameterCodec). + Timeout(timeout). Body(options). Do(). Error() diff --git a/pkg/client/clientset/versioned/typed/metrics/v1alpha2/custommetric.go b/pkg/client/clientset/versioned/typed/metrics/v1alpha2/custommetric.go new file mode 100644 index 00000000..24d2d089 --- /dev/null +++ b/pkg/client/clientset/versioned/typed/metrics/v1alpha2/custommetric.go @@ -0,0 +1,158 @@ +/* +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 client-gen. DO NOT EDIT. + +package v1alpha2 + +import ( + "time" + + v1alpha2 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha2" + scheme "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned/scheme" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + watch "k8s.io/apimachinery/pkg/watch" + rest "k8s.io/client-go/rest" +) + +// CustomMetricsGetter has a method to return a CustomMetricInterface. +// A group's client should implement this interface. +type CustomMetricsGetter interface { + CustomMetrics(namespace string) CustomMetricInterface +} + +// CustomMetricInterface has methods to work with CustomMetric resources. +type CustomMetricInterface interface { + Create(*v1alpha2.CustomMetric) (*v1alpha2.CustomMetric, error) + Update(*v1alpha2.CustomMetric) (*v1alpha2.CustomMetric, error) + Delete(name string, options *v1.DeleteOptions) error + DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error + Get(name string, options v1.GetOptions) (*v1alpha2.CustomMetric, error) + List(opts v1.ListOptions) (*v1alpha2.CustomMetricList, error) + Watch(opts v1.ListOptions) (watch.Interface, error) + CustomMetricExpansion +} + +// customMetrics implements CustomMetricInterface +type customMetrics struct { + client rest.Interface + ns string +} + +// newCustomMetrics returns a CustomMetrics +func newCustomMetrics(c *AzureV1alpha2Client, namespace string) *customMetrics { + return &customMetrics{ + client: c.RESTClient(), + ns: namespace, + } +} + +// Get takes name of the customMetric, and returns the corresponding customMetric object, and an error if there is any. +func (c *customMetrics) Get(name string, options v1.GetOptions) (result *v1alpha2.CustomMetric, err error) { + result = &v1alpha2.CustomMetric{} + err = c.client.Get(). + Namespace(c.ns). + Resource("custommetrics"). + Name(name). + VersionedParams(&options, scheme.ParameterCodec). + Do(). + Into(result) + return +} + +// List takes label and field selectors, and returns the list of CustomMetrics that match those selectors. +func (c *customMetrics) List(opts v1.ListOptions) (result *v1alpha2.CustomMetricList, err error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + result = &v1alpha2.CustomMetricList{} + err = c.client.Get(). + Namespace(c.ns). + Resource("custommetrics"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Do(). + Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested customMetrics. +func (c *customMetrics) Watch(opts v1.ListOptions) (watch.Interface, error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + opts.Watch = true + return c.client.Get(). + Namespace(c.ns). + Resource("custommetrics"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Watch() +} + +// Create takes the representation of a customMetric and creates it. Returns the server's representation of the customMetric, and an error, if there is any. +func (c *customMetrics) Create(customMetric *v1alpha2.CustomMetric) (result *v1alpha2.CustomMetric, err error) { + result = &v1alpha2.CustomMetric{} + err = c.client.Post(). + Namespace(c.ns). + Resource("custommetrics"). + Body(customMetric). + Do(). + Into(result) + return +} + +// Update takes the representation of a customMetric and updates it. Returns the server's representation of the customMetric, and an error, if there is any. +func (c *customMetrics) Update(customMetric *v1alpha2.CustomMetric) (result *v1alpha2.CustomMetric, err error) { + result = &v1alpha2.CustomMetric{} + err = c.client.Put(). + Namespace(c.ns). + Resource("custommetrics"). + Name(customMetric.Name). + Body(customMetric). + Do(). + Into(result) + return +} + +// Delete takes name of the customMetric and deletes it. Returns an error if one occurs. +func (c *customMetrics) Delete(name string, options *v1.DeleteOptions) error { + return c.client.Delete(). + Namespace(c.ns). + Resource("custommetrics"). + Name(name). + Body(options). + Do(). + Error() +} + +// DeleteCollection deletes a collection of objects. +func (c *customMetrics) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { + var timeout time.Duration + if listOptions.TimeoutSeconds != nil { + timeout = time.Duration(*listOptions.TimeoutSeconds) * time.Second + } + return c.client.Delete(). + Namespace(c.ns). + Resource("custommetrics"). + VersionedParams(&listOptions, scheme.ParameterCodec). + Timeout(timeout). + Body(options). + Do(). + Error() +} diff --git a/pkg/client/clientset/versioned/typed/metrics/v1alpha2/doc.go b/pkg/client/clientset/versioned/typed/metrics/v1alpha2/doc.go new file mode 100644 index 00000000..baaf2d98 --- /dev/null +++ b/pkg/client/clientset/versioned/typed/metrics/v1alpha2/doc.go @@ -0,0 +1,20 @@ +/* +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 client-gen. DO NOT EDIT. + +// This package has the automatically generated typed clients. +package v1alpha2 diff --git a/pkg/client/clientset/versioned/typed/metrics/v1alpha2/externalmetric.go b/pkg/client/clientset/versioned/typed/metrics/v1alpha2/externalmetric.go new file mode 100644 index 00000000..2c42089a --- /dev/null +++ b/pkg/client/clientset/versioned/typed/metrics/v1alpha2/externalmetric.go @@ -0,0 +1,158 @@ +/* +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 client-gen. DO NOT EDIT. + +package v1alpha2 + +import ( + "time" + + v1alpha2 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha2" + scheme "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned/scheme" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + watch "k8s.io/apimachinery/pkg/watch" + rest "k8s.io/client-go/rest" +) + +// ExternalMetricsGetter has a method to return a ExternalMetricInterface. +// A group's client should implement this interface. +type ExternalMetricsGetter interface { + ExternalMetrics(namespace string) ExternalMetricInterface +} + +// ExternalMetricInterface has methods to work with ExternalMetric resources. +type ExternalMetricInterface interface { + Create(*v1alpha2.ExternalMetric) (*v1alpha2.ExternalMetric, error) + Update(*v1alpha2.ExternalMetric) (*v1alpha2.ExternalMetric, error) + Delete(name string, options *v1.DeleteOptions) error + DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error + Get(name string, options v1.GetOptions) (*v1alpha2.ExternalMetric, error) + List(opts v1.ListOptions) (*v1alpha2.ExternalMetricList, error) + Watch(opts v1.ListOptions) (watch.Interface, error) + ExternalMetricExpansion +} + +// externalMetrics implements ExternalMetricInterface +type externalMetrics struct { + client rest.Interface + ns string +} + +// newExternalMetrics returns a ExternalMetrics +func newExternalMetrics(c *AzureV1alpha2Client, namespace string) *externalMetrics { + return &externalMetrics{ + client: c.RESTClient(), + ns: namespace, + } +} + +// Get takes name of the externalMetric, and returns the corresponding externalMetric object, and an error if there is any. +func (c *externalMetrics) Get(name string, options v1.GetOptions) (result *v1alpha2.ExternalMetric, err error) { + result = &v1alpha2.ExternalMetric{} + err = c.client.Get(). + Namespace(c.ns). + Resource("externalmetrics"). + Name(name). + VersionedParams(&options, scheme.ParameterCodec). + Do(). + Into(result) + return +} + +// List takes label and field selectors, and returns the list of ExternalMetrics that match those selectors. +func (c *externalMetrics) List(opts v1.ListOptions) (result *v1alpha2.ExternalMetricList, err error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + result = &v1alpha2.ExternalMetricList{} + err = c.client.Get(). + Namespace(c.ns). + Resource("externalmetrics"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Do(). + Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested externalMetrics. +func (c *externalMetrics) Watch(opts v1.ListOptions) (watch.Interface, error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + opts.Watch = true + return c.client.Get(). + Namespace(c.ns). + Resource("externalmetrics"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Watch() +} + +// Create takes the representation of a externalMetric and creates it. Returns the server's representation of the externalMetric, and an error, if there is any. +func (c *externalMetrics) Create(externalMetric *v1alpha2.ExternalMetric) (result *v1alpha2.ExternalMetric, err error) { + result = &v1alpha2.ExternalMetric{} + err = c.client.Post(). + Namespace(c.ns). + Resource("externalmetrics"). + Body(externalMetric). + Do(). + Into(result) + return +} + +// Update takes the representation of a externalMetric and updates it. Returns the server's representation of the externalMetric, and an error, if there is any. +func (c *externalMetrics) Update(externalMetric *v1alpha2.ExternalMetric) (result *v1alpha2.ExternalMetric, err error) { + result = &v1alpha2.ExternalMetric{} + err = c.client.Put(). + Namespace(c.ns). + Resource("externalmetrics"). + Name(externalMetric.Name). + Body(externalMetric). + Do(). + Into(result) + return +} + +// Delete takes name of the externalMetric and deletes it. Returns an error if one occurs. +func (c *externalMetrics) Delete(name string, options *v1.DeleteOptions) error { + return c.client.Delete(). + Namespace(c.ns). + Resource("externalmetrics"). + Name(name). + Body(options). + Do(). + Error() +} + +// DeleteCollection deletes a collection of objects. +func (c *externalMetrics) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { + var timeout time.Duration + if listOptions.TimeoutSeconds != nil { + timeout = time.Duration(*listOptions.TimeoutSeconds) * time.Second + } + return c.client.Delete(). + Namespace(c.ns). + Resource("externalmetrics"). + VersionedParams(&listOptions, scheme.ParameterCodec). + Timeout(timeout). + Body(options). + Do(). + Error() +} diff --git a/pkg/client/clientset/versioned/typed/metrics/v1alpha2/fake/doc.go b/pkg/client/clientset/versioned/typed/metrics/v1alpha2/fake/doc.go new file mode 100644 index 00000000..16f44399 --- /dev/null +++ b/pkg/client/clientset/versioned/typed/metrics/v1alpha2/fake/doc.go @@ -0,0 +1,20 @@ +/* +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 client-gen. DO NOT EDIT. + +// Package fake has the automatically generated clients. +package fake diff --git a/pkg/client/clientset/versioned/typed/metrics/v1alpha2/fake/fake_custommetric.go b/pkg/client/clientset/versioned/typed/metrics/v1alpha2/fake/fake_custommetric.go new file mode 100644 index 00000000..7adf7f71 --- /dev/null +++ b/pkg/client/clientset/versioned/typed/metrics/v1alpha2/fake/fake_custommetric.go @@ -0,0 +1,116 @@ +/* +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 client-gen. DO NOT EDIT. + +package fake + +import ( + v1alpha2 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha2" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + labels "k8s.io/apimachinery/pkg/labels" + schema "k8s.io/apimachinery/pkg/runtime/schema" + watch "k8s.io/apimachinery/pkg/watch" + testing "k8s.io/client-go/testing" +) + +// FakeCustomMetrics implements CustomMetricInterface +type FakeCustomMetrics struct { + Fake *FakeAzureV1alpha2 + ns string +} + +var custommetricsResource = schema.GroupVersionResource{Group: "azure.com", Version: "v1alpha2", Resource: "custommetrics"} + +var custommetricsKind = schema.GroupVersionKind{Group: "azure.com", Version: "v1alpha2", Kind: "CustomMetric"} + +// Get takes name of the customMetric, and returns the corresponding customMetric object, and an error if there is any. +func (c *FakeCustomMetrics) Get(name string, options v1.GetOptions) (result *v1alpha2.CustomMetric, err error) { + obj, err := c.Fake. + Invokes(testing.NewGetAction(custommetricsResource, c.ns, name), &v1alpha2.CustomMetric{}) + + if obj == nil { + return nil, err + } + return obj.(*v1alpha2.CustomMetric), err +} + +// List takes label and field selectors, and returns the list of CustomMetrics that match those selectors. +func (c *FakeCustomMetrics) List(opts v1.ListOptions) (result *v1alpha2.CustomMetricList, err error) { + obj, err := c.Fake. + Invokes(testing.NewListAction(custommetricsResource, custommetricsKind, c.ns, opts), &v1alpha2.CustomMetricList{}) + + if obj == nil { + return nil, err + } + + label, _, _ := testing.ExtractFromListOptions(opts) + if label == nil { + label = labels.Everything() + } + list := &v1alpha2.CustomMetricList{ListMeta: obj.(*v1alpha2.CustomMetricList).ListMeta} + for _, item := range obj.(*v1alpha2.CustomMetricList).Items { + if label.Matches(labels.Set(item.Labels)) { + list.Items = append(list.Items, item) + } + } + return list, err +} + +// Watch returns a watch.Interface that watches the requested customMetrics. +func (c *FakeCustomMetrics) Watch(opts v1.ListOptions) (watch.Interface, error) { + return c.Fake. + InvokesWatch(testing.NewWatchAction(custommetricsResource, c.ns, opts)) + +} + +// Create takes the representation of a customMetric and creates it. Returns the server's representation of the customMetric, and an error, if there is any. +func (c *FakeCustomMetrics) Create(customMetric *v1alpha2.CustomMetric) (result *v1alpha2.CustomMetric, err error) { + obj, err := c.Fake. + Invokes(testing.NewCreateAction(custommetricsResource, c.ns, customMetric), &v1alpha2.CustomMetric{}) + + if obj == nil { + return nil, err + } + return obj.(*v1alpha2.CustomMetric), err +} + +// Update takes the representation of a customMetric and updates it. Returns the server's representation of the customMetric, and an error, if there is any. +func (c *FakeCustomMetrics) Update(customMetric *v1alpha2.CustomMetric) (result *v1alpha2.CustomMetric, err error) { + obj, err := c.Fake. + Invokes(testing.NewUpdateAction(custommetricsResource, c.ns, customMetric), &v1alpha2.CustomMetric{}) + + if obj == nil { + return nil, err + } + return obj.(*v1alpha2.CustomMetric), err +} + +// Delete takes name of the customMetric and deletes it. Returns an error if one occurs. +func (c *FakeCustomMetrics) Delete(name string, options *v1.DeleteOptions) error { + _, err := c.Fake. + Invokes(testing.NewDeleteAction(custommetricsResource, c.ns, name), &v1alpha2.CustomMetric{}) + + return err +} + +// DeleteCollection deletes a collection of objects. +func (c *FakeCustomMetrics) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { + action := testing.NewDeleteCollectionAction(custommetricsResource, c.ns, listOptions) + + _, err := c.Fake.Invokes(action, &v1alpha2.CustomMetricList{}) + return err +} diff --git a/pkg/client/clientset/versioned/typed/metrics/v1alpha2/fake/fake_externalmetric.go b/pkg/client/clientset/versioned/typed/metrics/v1alpha2/fake/fake_externalmetric.go new file mode 100644 index 00000000..4a938448 --- /dev/null +++ b/pkg/client/clientset/versioned/typed/metrics/v1alpha2/fake/fake_externalmetric.go @@ -0,0 +1,116 @@ +/* +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 client-gen. DO NOT EDIT. + +package fake + +import ( + v1alpha2 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha2" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + labels "k8s.io/apimachinery/pkg/labels" + schema "k8s.io/apimachinery/pkg/runtime/schema" + watch "k8s.io/apimachinery/pkg/watch" + testing "k8s.io/client-go/testing" +) + +// FakeExternalMetrics implements ExternalMetricInterface +type FakeExternalMetrics struct { + Fake *FakeAzureV1alpha2 + ns string +} + +var externalmetricsResource = schema.GroupVersionResource{Group: "azure.com", Version: "v1alpha2", Resource: "externalmetrics"} + +var externalmetricsKind = schema.GroupVersionKind{Group: "azure.com", Version: "v1alpha2", Kind: "ExternalMetric"} + +// Get takes name of the externalMetric, and returns the corresponding externalMetric object, and an error if there is any. +func (c *FakeExternalMetrics) Get(name string, options v1.GetOptions) (result *v1alpha2.ExternalMetric, err error) { + obj, err := c.Fake. + Invokes(testing.NewGetAction(externalmetricsResource, c.ns, name), &v1alpha2.ExternalMetric{}) + + if obj == nil { + return nil, err + } + return obj.(*v1alpha2.ExternalMetric), err +} + +// List takes label and field selectors, and returns the list of ExternalMetrics that match those selectors. +func (c *FakeExternalMetrics) List(opts v1.ListOptions) (result *v1alpha2.ExternalMetricList, err error) { + obj, err := c.Fake. + Invokes(testing.NewListAction(externalmetricsResource, externalmetricsKind, c.ns, opts), &v1alpha2.ExternalMetricList{}) + + if obj == nil { + return nil, err + } + + label, _, _ := testing.ExtractFromListOptions(opts) + if label == nil { + label = labels.Everything() + } + list := &v1alpha2.ExternalMetricList{ListMeta: obj.(*v1alpha2.ExternalMetricList).ListMeta} + for _, item := range obj.(*v1alpha2.ExternalMetricList).Items { + if label.Matches(labels.Set(item.Labels)) { + list.Items = append(list.Items, item) + } + } + return list, err +} + +// Watch returns a watch.Interface that watches the requested externalMetrics. +func (c *FakeExternalMetrics) Watch(opts v1.ListOptions) (watch.Interface, error) { + return c.Fake. + InvokesWatch(testing.NewWatchAction(externalmetricsResource, c.ns, opts)) + +} + +// Create takes the representation of a externalMetric and creates it. Returns the server's representation of the externalMetric, and an error, if there is any. +func (c *FakeExternalMetrics) Create(externalMetric *v1alpha2.ExternalMetric) (result *v1alpha2.ExternalMetric, err error) { + obj, err := c.Fake. + Invokes(testing.NewCreateAction(externalmetricsResource, c.ns, externalMetric), &v1alpha2.ExternalMetric{}) + + if obj == nil { + return nil, err + } + return obj.(*v1alpha2.ExternalMetric), err +} + +// Update takes the representation of a externalMetric and updates it. Returns the server's representation of the externalMetric, and an error, if there is any. +func (c *FakeExternalMetrics) Update(externalMetric *v1alpha2.ExternalMetric) (result *v1alpha2.ExternalMetric, err error) { + obj, err := c.Fake. + Invokes(testing.NewUpdateAction(externalmetricsResource, c.ns, externalMetric), &v1alpha2.ExternalMetric{}) + + if obj == nil { + return nil, err + } + return obj.(*v1alpha2.ExternalMetric), err +} + +// Delete takes name of the externalMetric and deletes it. Returns an error if one occurs. +func (c *FakeExternalMetrics) Delete(name string, options *v1.DeleteOptions) error { + _, err := c.Fake. + Invokes(testing.NewDeleteAction(externalmetricsResource, c.ns, name), &v1alpha2.ExternalMetric{}) + + return err +} + +// DeleteCollection deletes a collection of objects. +func (c *FakeExternalMetrics) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { + action := testing.NewDeleteCollectionAction(externalmetricsResource, c.ns, listOptions) + + _, err := c.Fake.Invokes(action, &v1alpha2.ExternalMetricList{}) + return err +} diff --git a/pkg/client/clientset/versioned/typed/metrics/v1alpha2/fake/fake_metrics_client.go b/pkg/client/clientset/versioned/typed/metrics/v1alpha2/fake/fake_metrics_client.go new file mode 100644 index 00000000..fb407821 --- /dev/null +++ b/pkg/client/clientset/versioned/typed/metrics/v1alpha2/fake/fake_metrics_client.go @@ -0,0 +1,44 @@ +/* +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 client-gen. DO NOT EDIT. + +package fake + +import ( + v1alpha2 "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned/typed/metrics/v1alpha2" + rest "k8s.io/client-go/rest" + testing "k8s.io/client-go/testing" +) + +type FakeAzureV1alpha2 struct { + *testing.Fake +} + +func (c *FakeAzureV1alpha2) CustomMetrics(namespace string) v1alpha2.CustomMetricInterface { + return &FakeCustomMetrics{c, namespace} +} + +func (c *FakeAzureV1alpha2) ExternalMetrics(namespace string) v1alpha2.ExternalMetricInterface { + return &FakeExternalMetrics{c, namespace} +} + +// RESTClient returns a RESTClient that is used to communicate +// with API server by this client implementation. +func (c *FakeAzureV1alpha2) RESTClient() rest.Interface { + var ret *rest.RESTClient + return ret +} diff --git a/pkg/client/clientset/versioned/typed/metrics/v1alpha2/generated_expansion.go b/pkg/client/clientset/versioned/typed/metrics/v1alpha2/generated_expansion.go new file mode 100644 index 00000000..188bbd3d --- /dev/null +++ b/pkg/client/clientset/versioned/typed/metrics/v1alpha2/generated_expansion.go @@ -0,0 +1,23 @@ +/* +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 client-gen. DO NOT EDIT. + +package v1alpha2 + +type CustomMetricExpansion interface{} + +type ExternalMetricExpansion interface{} diff --git a/pkg/client/clientset/versioned/typed/metrics/v1alpha2/metrics_client.go b/pkg/client/clientset/versioned/typed/metrics/v1alpha2/metrics_client.go new file mode 100644 index 00000000..bc69c6c0 --- /dev/null +++ b/pkg/client/clientset/versioned/typed/metrics/v1alpha2/metrics_client.go @@ -0,0 +1,95 @@ +/* +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 client-gen. DO NOT EDIT. + +package v1alpha2 + +import ( + v1alpha2 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha2" + "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned/scheme" + serializer "k8s.io/apimachinery/pkg/runtime/serializer" + rest "k8s.io/client-go/rest" +) + +type AzureV1alpha2Interface interface { + RESTClient() rest.Interface + CustomMetricsGetter + ExternalMetricsGetter +} + +// AzureV1alpha2Client is used to interact with features provided by the azure.com group. +type AzureV1alpha2Client struct { + restClient rest.Interface +} + +func (c *AzureV1alpha2Client) CustomMetrics(namespace string) CustomMetricInterface { + return newCustomMetrics(c, namespace) +} + +func (c *AzureV1alpha2Client) ExternalMetrics(namespace string) ExternalMetricInterface { + return newExternalMetrics(c, namespace) +} + +// NewForConfig creates a new AzureV1alpha2Client for the given config. +func NewForConfig(c *rest.Config) (*AzureV1alpha2Client, error) { + config := *c + if err := setConfigDefaults(&config); err != nil { + return nil, err + } + client, err := rest.RESTClientFor(&config) + if err != nil { + return nil, err + } + return &AzureV1alpha2Client{client}, nil +} + +// NewForConfigOrDie creates a new AzureV1alpha2Client for the given config and +// panics if there is an error in the config. +func NewForConfigOrDie(c *rest.Config) *AzureV1alpha2Client { + client, err := NewForConfig(c) + if err != nil { + panic(err) + } + return client +} + +// New creates a new AzureV1alpha2Client for the given RESTClient. +func New(c rest.Interface) *AzureV1alpha2Client { + return &AzureV1alpha2Client{c} +} + +func setConfigDefaults(config *rest.Config) error { + gv := v1alpha2.SchemeGroupVersion + config.GroupVersion = &gv + config.APIPath = "/apis" + config.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs} + + if config.UserAgent == "" { + config.UserAgent = rest.DefaultKubernetesUserAgent() + } + + return nil +} + +// RESTClient returns a RESTClient that is used to communicate +// with API server by this client implementation. +func (c *AzureV1alpha2Client) RESTClient() rest.Interface { + if c == nil { + return nil + } + return c.restClient +} diff --git a/pkg/client/informers/externalversions/generic.go b/pkg/client/informers/externalversions/generic.go index 066cef1f..67f6ef82 100644 --- a/pkg/client/informers/externalversions/generic.go +++ b/pkg/client/informers/externalversions/generic.go @@ -22,6 +22,7 @@ import ( "fmt" v1alpha1 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha1" + v1alpha2 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha2" schema "k8s.io/apimachinery/pkg/runtime/schema" cache "k8s.io/client-go/tools/cache" ) @@ -58,6 +59,12 @@ func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource case v1alpha1.SchemeGroupVersion.WithResource("externalmetrics"): return &genericInformer{resource: resource.GroupResource(), informer: f.Azure().V1alpha1().ExternalMetrics().Informer()}, nil + // Group=azure.com, Version=v1alpha2 + case v1alpha2.SchemeGroupVersion.WithResource("custommetrics"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Azure().V1alpha2().CustomMetrics().Informer()}, nil + case v1alpha2.SchemeGroupVersion.WithResource("externalmetrics"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Azure().V1alpha2().ExternalMetrics().Informer()}, nil + } return nil, fmt.Errorf("no informer found for %v", resource) diff --git a/pkg/client/informers/externalversions/internalinterfaces/factory_interfaces.go b/pkg/client/informers/externalversions/internalinterfaces/factory_interfaces.go index 6f86a7b1..185b3f38 100644 --- a/pkg/client/informers/externalversions/internalinterfaces/factory_interfaces.go +++ b/pkg/client/informers/externalversions/internalinterfaces/factory_interfaces.go @@ -27,6 +27,7 @@ import ( cache "k8s.io/client-go/tools/cache" ) +// NewInformerFunc takes versioned.Interface and time.Duration to return a SharedIndexInformer. type NewInformerFunc func(versioned.Interface, time.Duration) cache.SharedIndexInformer // SharedInformerFactory a small interface to allow for adding an informer without an import cycle @@ -35,4 +36,5 @@ type SharedInformerFactory interface { InformerFor(obj runtime.Object, newFunc NewInformerFunc) cache.SharedIndexInformer } +// TweakListOptionsFunc is a function that transforms a v1.ListOptions. type TweakListOptionsFunc func(*v1.ListOptions) diff --git a/pkg/client/informers/externalversions/metrics/interface.go b/pkg/client/informers/externalversions/metrics/interface.go index ee5c9e5f..2ed58570 100644 --- a/pkg/client/informers/externalversions/metrics/interface.go +++ b/pkg/client/informers/externalversions/metrics/interface.go @@ -21,12 +21,15 @@ package azure import ( internalinterfaces "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/informers/externalversions/internalinterfaces" v1alpha1 "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/informers/externalversions/metrics/v1alpha1" + v1alpha2 "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/informers/externalversions/metrics/v1alpha2" ) // Interface provides access to each of this group's versions. type Interface interface { // V1alpha1 provides access to shared informers for resources in V1alpha1. V1alpha1() v1alpha1.Interface + // V1alpha2 provides access to shared informers for resources in V1alpha2. + V1alpha2() v1alpha2.Interface } type group struct { @@ -44,3 +47,8 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList func (g *group) V1alpha1() v1alpha1.Interface { return v1alpha1.New(g.factory, g.namespace, g.tweakListOptions) } + +// V1alpha2 returns a new v1alpha2.Interface. +func (g *group) V1alpha2() v1alpha2.Interface { + return v1alpha2.New(g.factory, g.namespace, g.tweakListOptions) +} diff --git a/pkg/client/informers/externalversions/metrics/v1alpha2/custommetric.go b/pkg/client/informers/externalversions/metrics/v1alpha2/custommetric.go new file mode 100644 index 00000000..0f4bc8b6 --- /dev/null +++ b/pkg/client/informers/externalversions/metrics/v1alpha2/custommetric.go @@ -0,0 +1,89 @@ +/* +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 informer-gen. DO NOT EDIT. + +package v1alpha2 + +import ( + time "time" + + metricsv1alpha2 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha2" + versioned "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned" + internalinterfaces "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/informers/externalversions/internalinterfaces" + v1alpha2 "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/listers/metrics/v1alpha2" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + watch "k8s.io/apimachinery/pkg/watch" + cache "k8s.io/client-go/tools/cache" +) + +// CustomMetricInformer provides access to a shared informer and lister for +// CustomMetrics. +type CustomMetricInformer interface { + Informer() cache.SharedIndexInformer + Lister() v1alpha2.CustomMetricLister +} + +type customMetricInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc + namespace string +} + +// NewCustomMetricInformer constructs a new informer for CustomMetric type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewCustomMetricInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredCustomMetricInformer(client, namespace, resyncPeriod, indexers, nil) +} + +// NewFilteredCustomMetricInformer constructs a new informer for CustomMetric type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewFilteredCustomMetricInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return cache.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AzureV1alpha2().CustomMetrics(namespace).List(options) + }, + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AzureV1alpha2().CustomMetrics(namespace).Watch(options) + }, + }, + &metricsv1alpha2.CustomMetric{}, + resyncPeriod, + indexers, + ) +} + +func (f *customMetricInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredCustomMetricInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +} + +func (f *customMetricInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&metricsv1alpha2.CustomMetric{}, f.defaultInformer) +} + +func (f *customMetricInformer) Lister() v1alpha2.CustomMetricLister { + return v1alpha2.NewCustomMetricLister(f.Informer().GetIndexer()) +} diff --git a/pkg/client/informers/externalversions/metrics/v1alpha2/externalmetric.go b/pkg/client/informers/externalversions/metrics/v1alpha2/externalmetric.go new file mode 100644 index 00000000..ca4778ba --- /dev/null +++ b/pkg/client/informers/externalversions/metrics/v1alpha2/externalmetric.go @@ -0,0 +1,89 @@ +/* +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 informer-gen. DO NOT EDIT. + +package v1alpha2 + +import ( + time "time" + + metricsv1alpha2 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha2" + versioned "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned" + internalinterfaces "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/informers/externalversions/internalinterfaces" + v1alpha2 "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/listers/metrics/v1alpha2" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + watch "k8s.io/apimachinery/pkg/watch" + cache "k8s.io/client-go/tools/cache" +) + +// ExternalMetricInformer provides access to a shared informer and lister for +// ExternalMetrics. +type ExternalMetricInformer interface { + Informer() cache.SharedIndexInformer + Lister() v1alpha2.ExternalMetricLister +} + +type externalMetricInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc + namespace string +} + +// NewExternalMetricInformer constructs a new informer for ExternalMetric type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewExternalMetricInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredExternalMetricInformer(client, namespace, resyncPeriod, indexers, nil) +} + +// NewFilteredExternalMetricInformer constructs a new informer for ExternalMetric type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewFilteredExternalMetricInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return cache.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AzureV1alpha2().ExternalMetrics(namespace).List(options) + }, + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.AzureV1alpha2().ExternalMetrics(namespace).Watch(options) + }, + }, + &metricsv1alpha2.ExternalMetric{}, + resyncPeriod, + indexers, + ) +} + +func (f *externalMetricInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredExternalMetricInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +} + +func (f *externalMetricInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&metricsv1alpha2.ExternalMetric{}, f.defaultInformer) +} + +func (f *externalMetricInformer) Lister() v1alpha2.ExternalMetricLister { + return v1alpha2.NewExternalMetricLister(f.Informer().GetIndexer()) +} diff --git a/pkg/client/informers/externalversions/metrics/v1alpha2/interface.go b/pkg/client/informers/externalversions/metrics/v1alpha2/interface.go new file mode 100644 index 00000000..8db02530 --- /dev/null +++ b/pkg/client/informers/externalversions/metrics/v1alpha2/interface.go @@ -0,0 +1,52 @@ +/* +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 informer-gen. DO NOT EDIT. + +package v1alpha2 + +import ( + internalinterfaces "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/informers/externalversions/internalinterfaces" +) + +// Interface provides access to all the informers in this group version. +type Interface interface { + // CustomMetrics returns a CustomMetricInformer. + CustomMetrics() CustomMetricInformer + // ExternalMetrics returns a ExternalMetricInformer. + ExternalMetrics() ExternalMetricInformer +} + +type version struct { + factory internalinterfaces.SharedInformerFactory + namespace string + tweakListOptions internalinterfaces.TweakListOptionsFunc +} + +// New returns a new Interface. +func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { + return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} +} + +// CustomMetrics returns a CustomMetricInformer. +func (v *version) CustomMetrics() CustomMetricInformer { + return &customMetricInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} +} + +// ExternalMetrics returns a ExternalMetricInformer. +func (v *version) ExternalMetrics() ExternalMetricInformer { + return &externalMetricInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} +} diff --git a/pkg/client/listers/metrics/v1alpha2/custommetric.go b/pkg/client/listers/metrics/v1alpha2/custommetric.go new file mode 100644 index 00000000..2644d61f --- /dev/null +++ b/pkg/client/listers/metrics/v1alpha2/custommetric.go @@ -0,0 +1,94 @@ +/* +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 lister-gen. DO NOT EDIT. + +package v1alpha2 + +import ( + v1alpha2 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha2" + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/client-go/tools/cache" +) + +// CustomMetricLister helps list CustomMetrics. +type CustomMetricLister interface { + // List lists all CustomMetrics in the indexer. + List(selector labels.Selector) (ret []*v1alpha2.CustomMetric, err error) + // CustomMetrics returns an object that can list and get CustomMetrics. + CustomMetrics(namespace string) CustomMetricNamespaceLister + CustomMetricListerExpansion +} + +// customMetricLister implements the CustomMetricLister interface. +type customMetricLister struct { + indexer cache.Indexer +} + +// NewCustomMetricLister returns a new CustomMetricLister. +func NewCustomMetricLister(indexer cache.Indexer) CustomMetricLister { + return &customMetricLister{indexer: indexer} +} + +// List lists all CustomMetrics in the indexer. +func (s *customMetricLister) List(selector labels.Selector) (ret []*v1alpha2.CustomMetric, err error) { + err = cache.ListAll(s.indexer, selector, func(m interface{}) { + ret = append(ret, m.(*v1alpha2.CustomMetric)) + }) + return ret, err +} + +// CustomMetrics returns an object that can list and get CustomMetrics. +func (s *customMetricLister) CustomMetrics(namespace string) CustomMetricNamespaceLister { + return customMetricNamespaceLister{indexer: s.indexer, namespace: namespace} +} + +// CustomMetricNamespaceLister helps list and get CustomMetrics. +type CustomMetricNamespaceLister interface { + // List lists all CustomMetrics in the indexer for a given namespace. + List(selector labels.Selector) (ret []*v1alpha2.CustomMetric, err error) + // Get retrieves the CustomMetric from the indexer for a given namespace and name. + Get(name string) (*v1alpha2.CustomMetric, error) + CustomMetricNamespaceListerExpansion +} + +// customMetricNamespaceLister implements the CustomMetricNamespaceLister +// interface. +type customMetricNamespaceLister struct { + indexer cache.Indexer + namespace string +} + +// List lists all CustomMetrics in the indexer for a given namespace. +func (s customMetricNamespaceLister) List(selector labels.Selector) (ret []*v1alpha2.CustomMetric, err error) { + err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { + ret = append(ret, m.(*v1alpha2.CustomMetric)) + }) + return ret, err +} + +// Get retrieves the CustomMetric from the indexer for a given namespace and name. +func (s customMetricNamespaceLister) Get(name string) (*v1alpha2.CustomMetric, error) { + obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(v1alpha2.Resource("custommetric"), name) + } + return obj.(*v1alpha2.CustomMetric), nil +} diff --git a/pkg/client/listers/metrics/v1alpha2/expansion_generated.go b/pkg/client/listers/metrics/v1alpha2/expansion_generated.go new file mode 100644 index 00000000..cd321eb3 --- /dev/null +++ b/pkg/client/listers/metrics/v1alpha2/expansion_generated.go @@ -0,0 +1,35 @@ +/* +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 lister-gen. DO NOT EDIT. + +package v1alpha2 + +// CustomMetricListerExpansion allows custom methods to be added to +// CustomMetricLister. +type CustomMetricListerExpansion interface{} + +// CustomMetricNamespaceListerExpansion allows custom methods to be added to +// CustomMetricNamespaceLister. +type CustomMetricNamespaceListerExpansion interface{} + +// ExternalMetricListerExpansion allows custom methods to be added to +// ExternalMetricLister. +type ExternalMetricListerExpansion interface{} + +// ExternalMetricNamespaceListerExpansion allows custom methods to be added to +// ExternalMetricNamespaceLister. +type ExternalMetricNamespaceListerExpansion interface{} diff --git a/pkg/client/listers/metrics/v1alpha2/externalmetric.go b/pkg/client/listers/metrics/v1alpha2/externalmetric.go new file mode 100644 index 00000000..48bb3217 --- /dev/null +++ b/pkg/client/listers/metrics/v1alpha2/externalmetric.go @@ -0,0 +1,94 @@ +/* +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 lister-gen. DO NOT EDIT. + +package v1alpha2 + +import ( + v1alpha2 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha2" + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/client-go/tools/cache" +) + +// ExternalMetricLister helps list ExternalMetrics. +type ExternalMetricLister interface { + // List lists all ExternalMetrics in the indexer. + List(selector labels.Selector) (ret []*v1alpha2.ExternalMetric, err error) + // ExternalMetrics returns an object that can list and get ExternalMetrics. + ExternalMetrics(namespace string) ExternalMetricNamespaceLister + ExternalMetricListerExpansion +} + +// externalMetricLister implements the ExternalMetricLister interface. +type externalMetricLister struct { + indexer cache.Indexer +} + +// NewExternalMetricLister returns a new ExternalMetricLister. +func NewExternalMetricLister(indexer cache.Indexer) ExternalMetricLister { + return &externalMetricLister{indexer: indexer} +} + +// List lists all ExternalMetrics in the indexer. +func (s *externalMetricLister) List(selector labels.Selector) (ret []*v1alpha2.ExternalMetric, err error) { + err = cache.ListAll(s.indexer, selector, func(m interface{}) { + ret = append(ret, m.(*v1alpha2.ExternalMetric)) + }) + return ret, err +} + +// ExternalMetrics returns an object that can list and get ExternalMetrics. +func (s *externalMetricLister) ExternalMetrics(namespace string) ExternalMetricNamespaceLister { + return externalMetricNamespaceLister{indexer: s.indexer, namespace: namespace} +} + +// ExternalMetricNamespaceLister helps list and get ExternalMetrics. +type ExternalMetricNamespaceLister interface { + // List lists all ExternalMetrics in the indexer for a given namespace. + List(selector labels.Selector) (ret []*v1alpha2.ExternalMetric, err error) + // Get retrieves the ExternalMetric from the indexer for a given namespace and name. + Get(name string) (*v1alpha2.ExternalMetric, error) + ExternalMetricNamespaceListerExpansion +} + +// externalMetricNamespaceLister implements the ExternalMetricNamespaceLister +// interface. +type externalMetricNamespaceLister struct { + indexer cache.Indexer + namespace string +} + +// List lists all ExternalMetrics in the indexer for a given namespace. +func (s externalMetricNamespaceLister) List(selector labels.Selector) (ret []*v1alpha2.ExternalMetric, err error) { + err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { + ret = append(ret, m.(*v1alpha2.ExternalMetric)) + }) + return ret, err +} + +// Get retrieves the ExternalMetric from the indexer for a given namespace and name. +func (s externalMetricNamespaceLister) Get(name string) (*v1alpha2.ExternalMetric, error) { + obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(v1alpha2.Resource("externalmetric"), name) + } + return obj.(*v1alpha2.ExternalMetric), nil +} From 4ee9c5e8267e6ff144122fdee9ff7a14c6ab903b Mon Sep 17 00:00:00 2001 From: Marc Sensenich Date: Wed, 23 Jan 2019 18:25:35 -0500 Subject: [PATCH 08/23] [GH-42] Break out clients to use the generic interface and add the factory --- .gitignore | 2 + main.go | 11 +- pkg/azure/external_metric_types/providers.go | 8 - .../client.go | 4 +- pkg/azure/external_metrics/factory.go | 27 +++ .../metricrequest.go | 33 ++-- .../metricrequest_test.go | 22 +-- .../monitor_client.go} | 23 +-- .../monitor_client_test.go} | 28 ++-- pkg/azure/external_metrics/providers.go | 10 ++ .../service_bus_subscription_client.go} | 19 +-- .../service_bus_subscription_client_test.go} | 25 ++- pkg/azure/monitor/metricrequest.go | 154 ------------------ pkg/controller/handler.go | 6 +- pkg/controller/handler_test.go | 14 +- pkg/metriccache/metric_cache.go | 9 +- pkg/provider/provider.go | 31 ++-- pkg/provider/provider_external.go | 17 +- pkg/provider/provider_external_test.go | 39 +++-- 19 files changed, 186 insertions(+), 296 deletions(-) delete mode 100644 pkg/azure/external_metric_types/providers.go rename pkg/azure/{external_metric_types => external_metrics}/client.go (81%) create mode 100644 pkg/azure/external_metrics/factory.go rename pkg/azure/{external_metric_types => external_metrics}/metricrequest.go (88%) rename pkg/azure/{monitor => external_metrics}/metricrequest_test.go (89%) rename pkg/azure/{monitor/client.go => external_metrics/monitor_client.go} (75%) rename pkg/azure/{monitor/client_test.go => external_metrics/monitor_client_test.go} (79%) create mode 100644 pkg/azure/external_metrics/providers.go rename pkg/azure/{servicebus/subscription_count_client.go => external_metrics/service_bus_subscription_client.go} (72%) rename pkg/azure/{servicebus/subscription_count_client_test.go => external_metrics/service_bus_subscription_client_test.go} (77%) delete mode 100644 pkg/azure/monitor/metricrequest.go diff --git a/.gitignore b/.gitignore index 9c94c135..f581bd64 100755 --- a/.gitignore +++ b/.gitignore @@ -97,3 +97,5 @@ typings/ # Serverless directories .serverless local-dev-values.yaml + +.circleci diff --git a/main.go b/main.go index 6f262104..be8fef4d 100755 --- a/main.go +++ b/main.go @@ -12,9 +12,8 @@ import ( "time" "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/appinsights" + "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/external_metrics" "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/instancemetadata" - "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/monitor" - "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/servicebus" clientset "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned" informers "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/informers/externalversions" "github.com/Azure/azure-k8s-metrics-adapter/pkg/controller" @@ -66,11 +65,13 @@ func setupAzureProvider(cmd *basecmd.AdapterBase, metricsCache *metriccache.Metr } defaultSubscriptionID := getDefaultSubscriptionID() - serviceBusSubscriptionClient := servicebus.NewClient(defaultSubscriptionID) - monitorClient := monitor.NewClient(defaultSubscriptionID) appinsightsClient := appinsights.NewClient() - azureProvider := azureprovider.NewAzureProvider(defaultSubscriptionID, mapper, dynamicClient, appinsightsClient, monitorClient, serviceBusSubscriptionClient, metricsCache) + azureExternalClientFactory := azureexternalmetrics.AzureExternalMetricClientFactory{ + DefaultSubscriptionID: defaultSubscriptionID, + } + + azureProvider := azureprovider.NewAzureProvider(defaultSubscriptionID, mapper, dynamicClient, appinsightsClient, azureExternalClientFactory, metricsCache) cmd.WithCustomMetrics(azureProvider) cmd.WithExternalMetrics(azureProvider) } diff --git a/pkg/azure/external_metric_types/providers.go b/pkg/azure/external_metric_types/providers.go deleted file mode 100644 index f33657a8..00000000 --- a/pkg/azure/external_metric_types/providers.go +++ /dev/null @@ -1,8 +0,0 @@ -package externalmetrictypes - -type AzureExternalMetricProvider string - -const ( - Monitor AzureExternalMetricProvider = "monitor" - ServiceBusSubscription AzureExternalMetricProvider = "servicebussubscription" -) diff --git a/pkg/azure/external_metric_types/client.go b/pkg/azure/external_metrics/client.go similarity index 81% rename from pkg/azure/external_metric_types/client.go rename to pkg/azure/external_metrics/client.go index 985200d6..d33b3fd0 100644 --- a/pkg/azure/external_metric_types/client.go +++ b/pkg/azure/external_metrics/client.go @@ -1,7 +1,7 @@ -package externalmetrictypes +package azureexternalmetrics type AzureExternalMetricResponse struct { - Total int64 + Total float64 } type AzureExternalMetricClient interface { diff --git a/pkg/azure/external_metrics/factory.go b/pkg/azure/external_metrics/factory.go new file mode 100644 index 00000000..0dc789b4 --- /dev/null +++ b/pkg/azure/external_metrics/factory.go @@ -0,0 +1,27 @@ +package azureexternalmetrics + +import "fmt" + +type AzureClientFactory interface { + GetAzureExternalMetricClient(clientType string) (AzureExternalMetricClient, error) +} + +type AzureExternalMetricClientFactory struct { + DefaultSubscriptionID string +} + +func (f AzureExternalMetricClientFactory) GetAzureExternalMetricClient(clientType string) (client AzureExternalMetricClient, err error) { + switch clientType { + case Monitor: + client = NewMonitorClient(f.DefaultSubscriptionID) + break + case ServiceBusSubscription: + client = NewServiceBusSubscriptionClient(f.DefaultSubscriptionID) + break + default: + err = fmt.Errorf("Unknown Azure external metric client type provided: %s", clientType) + break + } + + return client, err +} diff --git a/pkg/azure/external_metric_types/metricrequest.go b/pkg/azure/external_metrics/metricrequest.go similarity index 88% rename from pkg/azure/external_metric_types/metricrequest.go rename to pkg/azure/external_metrics/metricrequest.go index b9fa4c0b..b561edd4 100644 --- a/pkg/azure/external_metric_types/metricrequest.go +++ b/pkg/azure/external_metrics/metricrequest.go @@ -1,4 +1,4 @@ -package externalmetrictypes +package azureexternalmetrics import ( "errors" @@ -122,25 +122,29 @@ func IsInvalidMetricRequestError(err error) bool { } func (amr AzureExternalMetricRequest) Validate() error { + // Shared if amr.MetricName == "" { return InvalidMetricRequestError{err: "metricName is required"} } if amr.ResourceGroup == "" { return InvalidMetricRequestError{err: "resourceGroup is required"} } - if amr.Namespace == "" { - return InvalidMetricRequestError{err: "namespace is required"} - } - if amr.Topic == "" { - return InvalidMetricRequestError{err: "topic is required"} - } - if amr.Subscription == "" { - return InvalidMetricRequestError{err: "subscription is required"} - } if amr.SubscriptionID == "" { return InvalidMetricRequestError{err: "subscriptionID is required. set a default or pass via label selectors"} } + // Service Bus + + // if amr.Namespace == "" { + // return InvalidMetricRequestError{err: "namespace is required"} + // } + // if amr.Topic == "" { + // return InvalidMetricRequestError{err: "topic is required"} + // } + // if amr.Subscription == "" { + // return InvalidMetricRequestError{err: "subscription is required"} + // } + // if here then valid! return nil } @@ -153,3 +157,12 @@ func TimeSpan() string { starttime := time.Now().Add(-(5 * time.Minute)).UTC().Format(time.RFC3339) return fmt.Sprintf("%s/%s", starttime, endtime) } + +func (amr AzureExternalMetricRequest) MetricResourceURI() string { + return fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/%s/%s/%s", + amr.SubscriptionID, + amr.ResourceGroup, + amr.ResourceProviderNamespace, + amr.ResourceType, + amr.ResourceName) +} diff --git a/pkg/azure/monitor/metricrequest_test.go b/pkg/azure/external_metrics/metricrequest_test.go similarity index 89% rename from pkg/azure/monitor/metricrequest_test.go rename to pkg/azure/external_metrics/metricrequest_test.go index 0da9104a..971b9a1f 100644 --- a/pkg/azure/monitor/metricrequest_test.go +++ b/pkg/azure/external_metrics/metricrequest_test.go @@ -1,4 +1,4 @@ -package monitor +package azureexternalmetrics import ( "fmt" @@ -13,12 +13,12 @@ const validLabelSelector = "resourceProviderNamespace=Microsoft.Servicebus,resou func TestAzureMetricRequestGeneratesValidMetricResourceURI(t *testing.T) { tests := []struct { name string - amr AzureMetricRequest + amr AzureExternalMetricRequest want string }{ { name: "valid metric", - amr: AzureMetricRequest{ + amr: AzureExternalMetricRequest{ SubscriptionID: "1234-1234-234-12414", ResourceGroup: "test-rg", ResourceProviderNamespace: "Microsoft.Servicebus", @@ -45,7 +45,7 @@ func TestParseAzureMetric(t *testing.T) { tests := []struct { name string args args - want AzureMetricRequest + want AzureExternalMetricRequest wantErr bool }{ { @@ -54,7 +54,7 @@ func TestParseAzureMetric(t *testing.T) { defaultSubscriptionID: "", metricSelector: nil, }, - want: AzureMetricRequest{}, + want: AzureExternalMetricRequest{}, wantErr: true, }, } @@ -93,7 +93,7 @@ func TestParseWithSubIdPassedIsValid(t *testing.T) { err := metric.Validate() if err != nil { - t.Errorf("validate got error %v, want nil", err) + t.Errorf("validate got error: %v, want nil", err) } } @@ -107,7 +107,7 @@ func TestParseWithSubIdOnSelectorPassedIsValid(t *testing.T) { err := metric.Validate() if err != nil { - t.Errorf("validate got error %v, want nil", err) + t.Errorf("validate got error: %v, want nil", err) } } @@ -124,7 +124,7 @@ func TestParseWithNoSubIdPassedIsFails(t *testing.T) { } func TestValidateWithValidMetric(t *testing.T) { - mr := AzureMetricRequest{ + mr := AzureExternalMetricRequest{ Aggregation: "Total", Filter: "EntityName eq 'externalq'", MetricName: "Test", @@ -139,12 +139,12 @@ func TestValidateWithValidMetric(t *testing.T) { err := mr.Validate() if err != nil { - t.Errorf("validate got error %v, want nil", err) + t.Errorf("validate got error: %v, want nil", err) } } func TestValidateFilterIsOptional(t *testing.T) { - mr := AzureMetricRequest{ + mr := AzureExternalMetricRequest{ Aggregation: "Total", Filter: "", MetricName: "Test", @@ -159,6 +159,6 @@ func TestValidateFilterIsOptional(t *testing.T) { err := mr.Validate() if err != nil { - t.Errorf("validate got error %v, want nil", err) + t.Errorf("validate got error: %v, want nil", err) } } diff --git a/pkg/azure/monitor/client.go b/pkg/azure/external_metrics/monitor_client.go similarity index 75% rename from pkg/azure/monitor/client.go rename to pkg/azure/external_metrics/monitor_client.go index 5da1ccc7..8f666510 100644 --- a/pkg/azure/monitor/client.go +++ b/pkg/azure/external_metrics/monitor_client.go @@ -1,4 +1,4 @@ -package monitor +package azureexternalmetrics import ( "context" @@ -8,15 +8,6 @@ import ( "github.com/golang/glog" ) -// AzureMonitorClient provides an interface to make requests to Azure Monitor -type AzureMonitorClient interface { - GetAzureMetric(azMetricRequest AzureMetricRequest) (AzureMetricResponse, error) -} - -type AzureMetricResponse struct { - Total float64 -} - type insightsmonitorClient interface { List(ctx context.Context, resourceURI string, timespan string, interval *string, metricnames string, aggregation string, top *int32, orderby string, filter string, resultType insights.ResultType, metricnamespace string) (result insights.Response, err error) } @@ -26,7 +17,7 @@ type monitorClient struct { DefaultSubscriptionID string } -func NewClient(defaultsubscriptionID string) AzureMonitorClient { +func NewMonitorClient(defaultsubscriptionID string) AzureExternalMetricClient { client := insights.NewMetricsClient(defaultsubscriptionID) authorizer, err := auth.NewAuthorizerFromEnvironment() if err == nil { @@ -39,7 +30,7 @@ func NewClient(defaultsubscriptionID string) AzureMonitorClient { } } -func newClient(defaultsubscriptionID string, client insightsmonitorClient) monitorClient { +func newMonitorClient(defaultsubscriptionID string, client insightsmonitorClient) monitorClient { return monitorClient{ client: client, DefaultSubscriptionID: defaultsubscriptionID, @@ -47,10 +38,10 @@ func newClient(defaultsubscriptionID string, client insightsmonitorClient) monit } // GetAzureMetric calls Azure Monitor endpoint and returns a metric -func (c *monitorClient) GetAzureMetric(azMetricRequest AzureMetricRequest) (AzureMetricResponse, error) { +func (c *monitorClient) GetAzureMetric(azMetricRequest AzureExternalMetricRequest) (AzureExternalMetricResponse, error) { err := azMetricRequest.Validate() if err != nil { - return AzureMetricResponse{}, err + return AzureExternalMetricResponse{}, err } metricResourceURI := azMetricRequest.MetricResourceURI() @@ -61,7 +52,7 @@ func (c *monitorClient) GetAzureMetric(azMetricRequest AzureMetricRequest) (Azur azMetricRequest.MetricName, azMetricRequest.Aggregation, nil, "", azMetricRequest.Filter, "", "") if err != nil { - return AzureMetricResponse{}, err + return AzureExternalMetricResponse{}, err } total := extractValue(metricResult) @@ -69,7 +60,7 @@ func (c *monitorClient) GetAzureMetric(azMetricRequest AzureMetricRequest) (Azur glog.V(2).Infof("found metric value: %f", total) // TODO set Value based on aggregations type - return AzureMetricResponse{ + return AzureExternalMetricResponse{ Total: total, }, nil } diff --git a/pkg/azure/monitor/client_test.go b/pkg/azure/external_metrics/monitor_client_test.go similarity index 79% rename from pkg/azure/monitor/client_test.go rename to pkg/azure/external_metrics/monitor_client_test.go index a513d7a6..9e01b05c 100644 --- a/pkg/azure/monitor/client_test.go +++ b/pkg/azure/external_metrics/monitor_client_test.go @@ -1,4 +1,4 @@ -package monitor +package azureexternalmetrics import ( "context" @@ -8,12 +8,12 @@ import ( "github.com/Azure/azure-sdk-for-go/services/preview/monitor/mgmt/2018-03-01/insights" ) -func TestIfEmptyRequestGetError(t *testing.T) { +func TestAzureMonitorIfEmptyRequestGetError(t *testing.T) { monitorClient := newFakeMonitorClient(insights.Response{}, nil) - client := newClient("", monitorClient) + client := newMonitorClient("", monitorClient) - request := AzureMetricRequest{} + request := AzureExternalMetricRequest{} _, err := client.GetAzureMetric(request) if err == nil { @@ -25,13 +25,13 @@ func TestIfEmptyRequestGetError(t *testing.T) { } } -func TestIfFailedResponseGetError(t *testing.T) { +func TestAzureMonitorIfFailedResponseGetError(t *testing.T) { fakeError := errors.New("fake monitor failed") monitorClient := newFakeMonitorClient(insights.Response{}, fakeError) - client := newClient("", monitorClient) + client := newMonitorClient("", monitorClient) - request := newMetricRequest() + request := newAzureMonitorMetricRequest() _, err := client.GetAzureMetric(request) if err == nil { @@ -43,13 +43,13 @@ func TestIfFailedResponseGetError(t *testing.T) { } } -func TestIfValidRequestGetResult(t *testing.T) { - response := makeResponse(15) +func TestAzureMonitorIfValidRequestGetResult(t *testing.T) { + response := makeAzureMonitorResponse(15) monitorClient := newFakeMonitorClient(response, nil) - client := newClient("", monitorClient) + client := newMonitorClient("", monitorClient) - request := newMetricRequest() + request := newAzureMonitorMetricRequest() metricResponse, err := client.GetAzureMetric(request) if err != nil { @@ -61,7 +61,7 @@ func TestIfValidRequestGetResult(t *testing.T) { } } -func makeResponse(value float64) insights.Response { +func makeAzureMonitorResponse(value float64) insights.Response { // create metric value mv := insights.MetricValue{ Total: &value, @@ -90,8 +90,8 @@ func makeResponse(value float64) insights.Response { return response } -func newMetricRequest() AzureMetricRequest { - return AzureMetricRequest{ +func newAzureMonitorMetricRequest() AzureExternalMetricRequest { + return AzureExternalMetricRequest{ ResourceGroup: "ResourceGroup", ResourceName: "ResourceName", ResourceProviderNamespace: "ResourceProviderNamespace", diff --git a/pkg/azure/external_metrics/providers.go b/pkg/azure/external_metrics/providers.go new file mode 100644 index 00000000..025e300f --- /dev/null +++ b/pkg/azure/external_metrics/providers.go @@ -0,0 +1,10 @@ +package azureexternalmetrics + +type AzureExternalMetricClientProvider interface { + NewClient(defaultSubscriptionID string) +} + +const ( + Monitor string = "monitor" + ServiceBusSubscription string = "servicebussubscription" +) diff --git a/pkg/azure/servicebus/subscription_count_client.go b/pkg/azure/external_metrics/service_bus_subscription_client.go similarity index 72% rename from pkg/azure/servicebus/subscription_count_client.go rename to pkg/azure/external_metrics/service_bus_subscription_client.go index 9e76f0d7..5a8bb428 100644 --- a/pkg/azure/servicebus/subscription_count_client.go +++ b/pkg/azure/external_metrics/service_bus_subscription_client.go @@ -1,9 +1,8 @@ -package servicebus +package azureexternalmetrics import ( "context" - "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/external_metric_types" "github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus" "github.com/Azure/go-autorest/autorest/azure/auth" "github.com/golang/glog" @@ -18,7 +17,7 @@ type servicebusClient struct { DefaultSubscriptionID string } -func NewClient(defaultSubscriptionID string) externalmetrictypes.AzureExternalMetricClient { +func NewServiceBusSubscriptionClient(defaultSubscriptionID string) AzureExternalMetricClient { glog.V(2).Info("Creating a new Azure Service Bus Subscriptions client") client := servicebus.NewSubscriptionsClient(defaultSubscriptionID) authorizer, err := auth.NewAuthorizerFromEnvironment() @@ -32,18 +31,18 @@ func NewClient(defaultSubscriptionID string) externalmetrictypes.AzureExternalMe } } -func newClient(defaultsubscriptionID string, client servicebusSubscriptionsClient) servicebusClient { +func newServiceBusSubscriptionClient(defaultsubscriptionID string, client servicebusSubscriptionsClient) servicebusClient { return servicebusClient{ client: client, DefaultSubscriptionID: defaultsubscriptionID, } } -func (c *servicebusClient) GetAzureMetric(azMetricRequest externalmetrictypes.AzureExternalMetricRequest) (externalmetrictypes.AzureExternalMetricResponse, error) { +func (c *servicebusClient) GetAzureMetric(azMetricRequest AzureExternalMetricRequest) (AzureExternalMetricResponse, error) { glog.V(6).Infof("Received metric request:\n%v", azMetricRequest) err := azMetricRequest.Validate() if err != nil { - return externalmetrictypes.AzureExternalMetricResponse{}, err + return AzureExternalMetricResponse{}, err } glog.V(2).Infof("Requesting Service Bus Subscription %s to topic %s in namespace %s from resource group %s", azMetricRequest.Subscription, azMetricRequest.Topic, azMetricRequest.Namespace, azMetricRequest.ResourceGroup) @@ -55,18 +54,18 @@ func (c *servicebusClient) GetAzureMetric(azMetricRequest externalmetrictypes.Az azMetricRequest.Subscription, ) if err != nil { - return externalmetrictypes.AzureExternalMetricResponse{}, err + return AzureExternalMetricResponse{}, err } glog.V(2).Infof("Successfully retrieved Service Bus Subscription %s to topic %s in namespace %s from resource group %s", azMetricRequest.Subscription, azMetricRequest.Topic, azMetricRequest.Namespace, azMetricRequest.ResourceGroup) glog.V(6).Infof("%v", subscriptionResult.Response) - activeMessageCount := *subscriptionResult.SBSubscriptionProperties.CountDetails.ActiveMessageCount + activeMessageCount := float64(*subscriptionResult.SBSubscriptionProperties.CountDetails.ActiveMessageCount) - glog.V(4).Infof("Service Bus Subscription active message count: %d", activeMessageCount) + glog.V(4).Infof("Service Bus Subscription active message count: %f", activeMessageCount) // TODO set Value based on aggregations type - return externalmetrictypes.AzureExternalMetricResponse{ + return AzureExternalMetricResponse{ Total: activeMessageCount, }, nil } diff --git a/pkg/azure/servicebus/subscription_count_client_test.go b/pkg/azure/external_metrics/service_bus_subscription_client_test.go similarity index 77% rename from pkg/azure/servicebus/subscription_count_client_test.go rename to pkg/azure/external_metrics/service_bus_subscription_client_test.go index 1e283484..a22456c5 100644 --- a/pkg/azure/servicebus/subscription_count_client_test.go +++ b/pkg/azure/external_metrics/service_bus_subscription_client_test.go @@ -1,27 +1,26 @@ -package servicebus +package azureexternalmetrics import ( "context" "errors" "testing" - "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/external_metric_types" "github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus" ) func TestIfEmptyRequestGetError(t *testing.T) { servicebusClient := newFakeServicebusClient(servicebus.SBSubscription{}, nil) - client := newClient("", servicebusClient) + client := newServiceBusSubscriptionClient("", servicebusClient) - request := externalmetrictypes.AzureExternalMetricRequest{} + request := AzureExternalMetricRequest{} _, err := client.GetAzureMetric(request) if err == nil { t.Errorf("no error after processing got: %v, want error", nil) } - if !externalmetrictypes.IsInvalidMetricRequestError(err) { + if !IsInvalidMetricRequestError(err) { t.Errorf("should be InvalidMetricRequest error got %v, want InvalidMetricRequestError", err) } } @@ -30,9 +29,9 @@ func TestIfFailedResponseGetError(t *testing.T) { fakeError := errors.New("fake servicebus failed") serviceBusClient := newFakeServicebusClient(servicebus.SBSubscription{}, fakeError) - client := newClient("", serviceBusClient) + client := newServiceBusSubscriptionClient("", serviceBusClient) - request := newMetricRequest() + request := newServiceBusSubscriptionMetricRequest() _, err := client.GetAzureMetric(request) if err == nil { @@ -45,12 +44,12 @@ func TestIfFailedResponseGetError(t *testing.T) { } func TestIfValidRequestGetResult(t *testing.T) { - response := makeResponse(15) + response := makeServiceBusSubscriptionResponse(15) serviceBusClient := newFakeServicebusClient(response, nil) - client := newClient("", serviceBusClient) + client := newServiceBusSubscriptionClient("", serviceBusClient) - request := newMetricRequest() + request := newServiceBusSubscriptionMetricRequest() metricResponse, err := client.GetAzureMetric(request) if err != nil { @@ -62,7 +61,7 @@ func TestIfValidRequestGetResult(t *testing.T) { } } -func makeResponse(value int64) servicebus.SBSubscription { +func makeServiceBusSubscriptionResponse(value int64) servicebus.SBSubscription { messageCountDetails := servicebus.MessageCountDetails{ ActiveMessageCount: &value, } @@ -78,8 +77,8 @@ func makeResponse(value int64) servicebus.SBSubscription { return response } -func newMetricRequest() externalmetrictypes.AzureExternalMetricRequest { - return externalmetrictypes.AzureExternalMetricRequest{ +func newServiceBusSubscriptionMetricRequest() AzureExternalMetricRequest { + return AzureExternalMetricRequest{ ResourceGroup: "ResourceGroup", SubscriptionID: "SubscriptionID", MetricName: "MetricName", diff --git a/pkg/azure/monitor/metricrequest.go b/pkg/azure/monitor/metricrequest.go deleted file mode 100644 index 014a07bb..00000000 --- a/pkg/azure/monitor/metricrequest.go +++ /dev/null @@ -1,154 +0,0 @@ -package monitor - -import ( - "errors" - "fmt" - "strings" - "time" - - "github.com/golang/glog" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/apimachinery/pkg/selection" -) - -type AzureMetricRequest struct { - MetricName string - ResourceGroup string - ResourceName string - ResourceProviderNamespace string - ResourceType string - Aggregation string - Timespan string - Filter string - SubscriptionID string -} - -func ParseAzureMetric(metricSelector labels.Selector, defaultSubscriptionID string) (AzureMetricRequest, error) { - glog.V(2).Infof("begin parsing metric") - - if metricSelector == nil { - return AzureMetricRequest{}, fmt.Errorf("metricSelector cannot be nil") - } - - // Using selectors to pass required values thorugh - // to retain camel case as azure provider is case sensitive. - // - // There is are restrictions so using some conversion - // restrictions here - // note: requirement values are already validated by apiserver - merticReq := AzureMetricRequest{ - Timespan: TimeSpan(), - SubscriptionID: defaultSubscriptionID, - } - requirements, _ := metricSelector.Requirements() - for _, request := range requirements { - if request.Operator() != selection.Equals { - return AzureMetricRequest{}, errors.New("selector type not supported. only equals is supported at this time") - } - - value := request.Values().List()[0] - - switch request.Key() { - case "metricName": - glog.V(2).Infof("metricName: %s", value) - merticReq.MetricName = value - case "resourceGroup": - glog.V(2).Infof("resourceGroup: %s", value) - merticReq.ResourceGroup = value - case "resourceName": - glog.V(2).Infof("resourceName: %s", value) - merticReq.ResourceName = value - case "resourceProviderNamespace": - glog.V(2).Infof("resourceProviderNamespace: %s", value) - merticReq.ResourceProviderNamespace = value - case "resourceType": - glog.V(2).Infof("resourceType: %s", value) - merticReq.ResourceType = value - case "aggregation": - glog.V(2).Infof("aggregation: %s", value) - merticReq.Aggregation = value - case "filter": - // TODO: Should handle filters by converting equality and setbased label selectors - // to oData syntax: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors - glog.V(2).Infof("filter: %s", value) - filterStrings := strings.Split(value, "_") - merticReq.Filter = fmt.Sprintf("%s %s '%s'", filterStrings[0], filterStrings[1], filterStrings[2]) - glog.V(2).Infof("filter formatted: %s", merticReq.Filter) - case "subscriptionID": - // if sub id is passed via label selectors then it takes precedence - glog.V(2).Infof("override azure subscription id with : %s", value) - merticReq.SubscriptionID = value - default: - return AzureMetricRequest{}, fmt.Errorf("selector label '%s' not supported", request.Key()) - } - } - - return merticReq, nil -} - -type InvalidMetricRequestError struct { - err string -} - -func (i InvalidMetricRequestError) Error() string { - return fmt.Sprintf(i.err) -} - -func IsInvalidMetricRequestError(err error) bool { - if _, ok := err.(InvalidMetricRequestError); ok { - return true - } - return false -} - -func (amr AzureMetricRequest) Validate() error { - if amr.MetricName == "" { - return InvalidMetricRequestError{err: "metricName is required"} - } - if amr.ResourceGroup == "" { - return InvalidMetricRequestError{err: "resourceGroup is required"} - } - if amr.ResourceName == "" { - return InvalidMetricRequestError{err: "resourceName is required"} - } - if amr.ResourceProviderNamespace == "" { - return InvalidMetricRequestError{err: "resourceProviderNamespace is required"} - } - if amr.ResourceType == "" { - return InvalidMetricRequestError{err: "resourceType is required"} - } - if amr.Aggregation == "" { - return InvalidMetricRequestError{err: "aggregation is required"} - } - if amr.Timespan == "" { - return InvalidMetricRequestError{err: "timespan is required"} - } - if amr.Filter == "" { - glog.V(2).Infof("filter on request was not set") - } - - if amr.SubscriptionID == "" { - return InvalidMetricRequestError{err: "subscriptionID is required. set a default or pass via label selectors"} - } - - // if here then valid! - return nil -} - -func (amr AzureMetricRequest) MetricResourceURI() string { - return fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/%s/%s/%s", - amr.SubscriptionID, - amr.ResourceGroup, - amr.ResourceProviderNamespace, - amr.ResourceType, - amr.ResourceName) -} - -// TimeSpan sets the default time to aggregate a metric -func TimeSpan() string { - // defaults to last five minutes. - // TODO support configuration via config - endtime := time.Now().UTC().Format(time.RFC3339) - starttime := time.Now().Add(-(5 * time.Minute)).UTC().Format(time.RFC3339) - return fmt.Sprintf("%s/%s", starttime, endtime) -} diff --git a/pkg/controller/handler.go b/pkg/controller/handler.go index aa3ec22a..5ee9dddc 100644 --- a/pkg/controller/handler.go +++ b/pkg/controller/handler.go @@ -4,8 +4,7 @@ import ( "fmt" "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/appinsights" - - "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/monitor" + "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/external_metrics" listers "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/listers/metrics/v1alpha1" "github.com/Azure/azure-k8s-metrics-adapter/pkg/metriccache" "github.com/golang/glog" @@ -93,7 +92,8 @@ func (h *Handler) handleExternalMetric(ns, name string, queueItem namespacedQueu return err } - azureMetricRequest := monitor.AzureMetricRequest{ + // TODO: Map the new fields here for Service Bus + azureMetricRequest := azureexternalmetrics.AzureExternalMetricRequest{ ResourceGroup: externalMetricInfo.Spec.AzureConfig.ResourceGroup, ResourceName: externalMetricInfo.Spec.AzureConfig.ResourceName, ResourceProviderNamespace: externalMetricInfo.Spec.AzureConfig.ResourceProviderNamespace, diff --git a/pkg/controller/handler_test.go b/pkg/controller/handler_test.go index efe0bd1c..60ee1460 100644 --- a/pkg/controller/handler_test.go +++ b/pkg/controller/handler_test.go @@ -4,16 +4,14 @@ import ( "fmt" "testing" - "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/appinsights" - api "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha1" - "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/monitor" + "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/appinsights" + "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/external_metrics" + "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned/fake" + informers "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/informers/externalversions" "github.com/Azure/azure-k8s-metrics-adapter/pkg/metriccache" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" - - "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned/fake" - informers "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/informers/externalversions" ) func getExternalKey(externalMetric *api.ExternalMetric) namespacedQueueItem { @@ -168,7 +166,7 @@ func TestWhenExternalItemHasBeenDeleted(t *testing.T) { // add the item to the cache then test if it gets deleted queueItem := getExternalKey(externalMetric) - metriccache.Update(queueItem.Key(), monitor.AzureMetricRequest{}) + metriccache.Update(queueItem.Key(), azureexternalmetrics.AzureExternalMetricRequest{}) err := handler.Process(queueItem) @@ -258,7 +256,7 @@ func newHandler(storeObjects []runtime.Object, externalMetricsListerCache []*api return handler, metriccache } -func validateExternalMetricResult(metricRequest monitor.AzureMetricRequest, externalMetricInfo *api.ExternalMetric, t *testing.T) { +func validateExternalMetricResult(metricRequest azureexternalmetrics.AzureExternalMetricRequest, externalMetricInfo *api.ExternalMetric, t *testing.T) { // Metric Config if metricRequest.MetricName != externalMetricInfo.Spec.MetricConfig.MetricName { diff --git a/pkg/metriccache/metric_cache.go b/pkg/metriccache/metric_cache.go index 8b940439..cb599fcb 100644 --- a/pkg/metriccache/metric_cache.go +++ b/pkg/metriccache/metric_cache.go @@ -5,8 +5,7 @@ import ( "sync" "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/appinsights" - - "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/monitor" + "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/external_metrics" "github.com/golang/glog" ) @@ -32,7 +31,7 @@ func (mc *MetricCache) Update(key string, metricRequest interface{}) { } // GetAzureMonitorRequest retrieves a metric request from the cache -func (mc *MetricCache) GetAzureMonitorRequest(namepace, name string) (monitor.AzureMetricRequest, bool) { +func (mc *MetricCache) GetAzureMonitorRequest(namepace, name string) (azureexternalmetrics.AzureExternalMetricRequest, bool) { mc.metricMutext.RLock() defer mc.metricMutext.RUnlock() @@ -40,10 +39,10 @@ func (mc *MetricCache) GetAzureMonitorRequest(namepace, name string) (monitor.Az metricRequest, exists := mc.metricRequests[key] if !exists { glog.V(2).Infof("metric not found %s", key) - return monitor.AzureMetricRequest{}, false + return azureexternalmetrics.AzureExternalMetricRequest{}, false } - return metricRequest.(monitor.AzureMetricRequest), true + return metricRequest.(azureexternalmetrics.AzureExternalMetricRequest), true } // GetAppInsightsRequest retrieves a metric request from the cache diff --git a/pkg/provider/provider.go b/pkg/provider/provider.go index a15c67d6..c8bf909e 100755 --- a/pkg/provider/provider.go +++ b/pkg/provider/provider.go @@ -4,8 +4,7 @@ package provider import ( "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/appinsights" - "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/external_metric_types" - "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/monitor" + "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/external_metrics" "github.com/Azure/azure-k8s-metrics-adapter/pkg/metriccache" "github.com/kubernetes-incubator/custom-metrics-apiserver/pkg/provider" apimeta "k8s.io/apimachinery/pkg/api/meta" @@ -13,23 +12,21 @@ import ( ) type AzureProvider struct { - appinsightsClient appinsights.AzureAppInsightsClient - mapper apimeta.RESTMapper - kubeClient dynamic.Interface - monitorClient monitor.AzureMonitorClient - metricCache *metriccache.MetricCache - serviceBusSubscriptionClient externalmetrictypes.AzureExternalMetricClient - defaultSubscriptionID string + appinsightsClient appinsights.AzureAppInsightsClient + mapper apimeta.RESTMapper + kubeClient dynamic.Interface + metricCache *metriccache.MetricCache + azureClientFactory azureexternalmetrics.AzureClientFactory + defaultSubscriptionID string } -func NewAzureProvider(defaultSubscriptionID string, mapper apimeta.RESTMapper, kubeClient dynamic.Interface, appinsightsClient appinsights.AzureAppInsightsClient, monitorClient monitor.AzureMonitorClient, serviceBusSubscriptionClient externalmetrictypes.AzureExternalMetricClient, metricCache *metriccache.MetricCache) provider.MetricsProvider { +func NewAzureProvider(defaultSubscriptionID string, mapper apimeta.RESTMapper, kubeClient dynamic.Interface, appinsightsClient appinsights.AzureAppInsightsClient, azureClientFactory azureexternalmetrics.AzureClientFactory, metricCache *metriccache.MetricCache) provider.MetricsProvider { return &AzureProvider{ - defaultSubscriptionID: defaultSubscriptionID, - mapper: mapper, - kubeClient: kubeClient, - appinsightsClient: appinsightsClient, - monitorClient: monitorClient, - metricCache: metricCache, - serviceBusSubscriptionClient: serviceBusSubscriptionClient, + defaultSubscriptionID: defaultSubscriptionID, + mapper: mapper, + kubeClient: kubeClient, + appinsightsClient: appinsightsClient, + metricCache: metricCache, + azureClientFactory: azureClientFactory, } } diff --git a/pkg/provider/provider_external.go b/pkg/provider/provider_external.go index 80ad3ca8..cfa74901 100644 --- a/pkg/provider/provider_external.go +++ b/pkg/provider/provider_external.go @@ -3,7 +3,7 @@ package provider import ( - "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/monitor" + "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/external_metrics" "github.com/golang/glog" "github.com/kubernetes-incubator/custom-metrics-apiserver/pkg/provider" "k8s.io/apimachinery/pkg/api/errors" @@ -33,7 +33,12 @@ func (p *AzureProvider) GetExternalMetric(namespace string, metricSelector label return nil, errors.NewBadRequest(err.Error()) } - metricValue, err := p.monitorClient.GetAzureMetric(azMetricRequest) + externalMetricClient, err := p.azureClientFactory.GetAzureExternalMetricClient(azMetricRequest.Type) + if err != nil { + return nil, errors.NewBadRequest(err.Error()) + } + + metricValue, err := externalMetricClient.GetAzureMetric(azMetricRequest) if err != nil { glog.Errorf("bad request: %v", err) return nil, errors.NewBadRequest(err.Error()) @@ -67,20 +72,20 @@ func (p *AzureProvider) ListAllExternalMetrics() []provider.ExternalMetricInfo { return externalMetricsInfo } -func (p *AzureProvider) getMetricRequest(namespace string, metricName string, metricSelector labels.Selector) (monitor.AzureMetricRequest, error) { +func (p *AzureProvider) getMetricRequest(namespace string, metricName string, metricSelector labels.Selector) (azureexternalmetrics.AzureExternalMetricRequest, error) { azMetricRequest, found := p.metricCache.GetAzureMonitorRequest(namespace, metricName) if found { - azMetricRequest.Timespan = monitor.TimeSpan() + azMetricRequest.Timespan = azureexternalmetrics.TimeSpan() if azMetricRequest.SubscriptionID == "" { azMetricRequest.SubscriptionID = p.defaultSubscriptionID } return azMetricRequest, nil } - azMetricRequest, err := monitor.ParseAzureMetric(metricSelector, p.defaultSubscriptionID) + azMetricRequest, err := azureexternalmetrics.ParseAzureMetric(metricSelector, p.defaultSubscriptionID) if err != nil { - return monitor.AzureMetricRequest{}, err + return azureexternalmetrics.AzureExternalMetricRequest{}, err } return azMetricRequest, nil diff --git a/pkg/provider/provider_external_test.go b/pkg/provider/provider_external_test.go index 9e9269f5..ea5c8723 100644 --- a/pkg/provider/provider_external_test.go +++ b/pkg/provider/provider_external_test.go @@ -4,10 +4,9 @@ import ( "fmt" "testing" + "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/external_metrics" "github.com/Azure/azure-k8s-metrics-adapter/pkg/metriccache" k8sprovider "github.com/kubernetes-incubator/custom-metrics-apiserver/pkg/provider" - - "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/monitor" "k8s.io/apimachinery/pkg/labels" ) @@ -33,7 +32,7 @@ func createLabelSelector(metricName, subscriptionID string) labels.Selector { func TestFindMetricInCache(t *testing.T) { metricCache := metriccache.NewMetricCache() - request := monitor.AzureMetricRequest{ + request := azureexternalmetrics.AzureExternalMetricRequest{ MetricName: "MessageCount", } metricCache.Update("ExternalMetric/default/metricname", request) @@ -66,7 +65,7 @@ func TestFindMetricInCache(t *testing.T) { func TestFindMetricInCacheUsesOverrideSubscriptionId(t *testing.T) { metricCache := metriccache.NewMetricCache() - request := monitor.AzureMetricRequest{ + request := azureexternalmetrics.AzureExternalMetricRequest{ MetricName: "MessageCount", SubscriptionID: "9876", } @@ -167,17 +166,14 @@ func TestInvalidLabelSelector(t *testing.T) { } func TestReturnsExeternalMetric(t *testing.T) { - fakeClient := fakeAzureMonitorClient{ - err: nil, - result: monitor.AzureMetricResponse{Total: 15}, - } + fakeFactory := fakeAzureExternalClientFactory{} selector, _ := labels.Parse("") info := k8sprovider.ExternalMetricInfo{ Metric: "MetricName", } - provider := newProvider(fakeClient) + provider := newProvider(fakeFactory) returnList, err := provider.GetExternalMetric("default", selector, info) if err != nil { @@ -198,22 +194,37 @@ func TestReturnsExeternalMetric(t *testing.T) { } } -func newProvider(fakeclient fakeAzureMonitorClient) AzureProvider { +func newProvider(fakeFactory fakeAzureExternalClientFactory) AzureProvider { + // func newProvider(fakeclient fakeAzureMonitorClient) AzureProvider { metricCache := metriccache.NewMetricCache() provider := AzureProvider{ - metricCache: metricCache, - monitorClient: fakeclient, + metricCache: metricCache, + azureClientFactory: fakeFactory, } return provider } +// externalMetricClient, err := p.azureExternalClientFactory.GetAzureExternalMetricClient(azMetricRequest.Type) + +type fakeAzureExternalClientFactory struct { +} + +func (f fakeAzureExternalClientFactory) GetAzureExternalMetricClient(clientType string) (client azureexternalmetrics.AzureExternalMetricClient, err error) { + fakeClient := fakeAzureMonitorClient{ + err: nil, + result: azureexternalmetrics.AzureExternalMetricResponse{Total: 15}, + } + + return fakeClient, nil +} + type fakeAzureMonitorClient struct { - result monitor.AzureMetricResponse + result azureexternalmetrics.AzureExternalMetricResponse err error } -func (f fakeAzureMonitorClient) GetAzureMetric(azMetricRequest monitor.AzureMetricRequest) (monitor.AzureMetricResponse, error) { +func (f fakeAzureMonitorClient) GetAzureMetric(azMetricRequest azureexternalmetrics.AzureExternalMetricRequest) (azureexternalmetrics.AzureExternalMetricResponse, error) { return f.result, f.err } From 29465433136ff4b29d4a14c72fc6b3f44834b1cd Mon Sep 17 00:00:00 2001 From: James Sturtevant Date: Fri, 25 Jan 2019 16:14:53 -0800 Subject: [PATCH 09/23] generated client files --- .../typed/metrics/v1alpha1/custommetric.go | 17 ----------------- .../typed/metrics/v1alpha1/externalmetric.go | 17 ----------------- .../typed/metrics/v1alpha2/custommetric.go | 17 ----------------- .../typed/metrics/v1alpha2/externalmetric.go | 17 ----------------- .../internalinterfaces/factory_interfaces.go | 2 -- 5 files changed, 70 deletions(-) diff --git a/pkg/client/clientset/versioned/typed/metrics/v1alpha1/custommetric.go b/pkg/client/clientset/versioned/typed/metrics/v1alpha1/custommetric.go index 7c065c20..dc7d3a7b 100644 --- a/pkg/client/clientset/versioned/typed/metrics/v1alpha1/custommetric.go +++ b/pkg/client/clientset/versioned/typed/metrics/v1alpha1/custommetric.go @@ -19,8 +19,6 @@ limitations under the License. package v1alpha1 import ( - "time" - v1alpha1 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha1" scheme "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned/scheme" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -75,16 +73,11 @@ func (c *customMetrics) Get(name string, options v1.GetOptions) (result *v1alpha // List takes label and field selectors, and returns the list of CustomMetrics that match those selectors. func (c *customMetrics) List(opts v1.ListOptions) (result *v1alpha1.CustomMetricList, err error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } result = &v1alpha1.CustomMetricList{} err = c.client.Get(). Namespace(c.ns). Resource("custommetrics"). VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). Do(). Into(result) return @@ -92,16 +85,11 @@ func (c *customMetrics) List(opts v1.ListOptions) (result *v1alpha1.CustomMetric // Watch returns a watch.Interface that watches the requested customMetrics. func (c *customMetrics) Watch(opts v1.ListOptions) (watch.Interface, error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } opts.Watch = true return c.client.Get(). Namespace(c.ns). Resource("custommetrics"). VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). Watch() } @@ -143,15 +131,10 @@ func (c *customMetrics) Delete(name string, options *v1.DeleteOptions) error { // DeleteCollection deletes a collection of objects. func (c *customMetrics) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - var timeout time.Duration - if listOptions.TimeoutSeconds != nil { - timeout = time.Duration(*listOptions.TimeoutSeconds) * time.Second - } return c.client.Delete(). Namespace(c.ns). Resource("custommetrics"). VersionedParams(&listOptions, scheme.ParameterCodec). - Timeout(timeout). Body(options). Do(). Error() diff --git a/pkg/client/clientset/versioned/typed/metrics/v1alpha1/externalmetric.go b/pkg/client/clientset/versioned/typed/metrics/v1alpha1/externalmetric.go index c8c4c642..61ece856 100644 --- a/pkg/client/clientset/versioned/typed/metrics/v1alpha1/externalmetric.go +++ b/pkg/client/clientset/versioned/typed/metrics/v1alpha1/externalmetric.go @@ -19,8 +19,6 @@ limitations under the License. package v1alpha1 import ( - "time" - v1alpha1 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha1" scheme "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned/scheme" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -75,16 +73,11 @@ func (c *externalMetrics) Get(name string, options v1.GetOptions) (result *v1alp // List takes label and field selectors, and returns the list of ExternalMetrics that match those selectors. func (c *externalMetrics) List(opts v1.ListOptions) (result *v1alpha1.ExternalMetricList, err error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } result = &v1alpha1.ExternalMetricList{} err = c.client.Get(). Namespace(c.ns). Resource("externalmetrics"). VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). Do(). Into(result) return @@ -92,16 +85,11 @@ func (c *externalMetrics) List(opts v1.ListOptions) (result *v1alpha1.ExternalMe // Watch returns a watch.Interface that watches the requested externalMetrics. func (c *externalMetrics) Watch(opts v1.ListOptions) (watch.Interface, error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } opts.Watch = true return c.client.Get(). Namespace(c.ns). Resource("externalmetrics"). VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). Watch() } @@ -143,15 +131,10 @@ func (c *externalMetrics) Delete(name string, options *v1.DeleteOptions) error { // DeleteCollection deletes a collection of objects. func (c *externalMetrics) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - var timeout time.Duration - if listOptions.TimeoutSeconds != nil { - timeout = time.Duration(*listOptions.TimeoutSeconds) * time.Second - } return c.client.Delete(). Namespace(c.ns). Resource("externalmetrics"). VersionedParams(&listOptions, scheme.ParameterCodec). - Timeout(timeout). Body(options). Do(). Error() diff --git a/pkg/client/clientset/versioned/typed/metrics/v1alpha2/custommetric.go b/pkg/client/clientset/versioned/typed/metrics/v1alpha2/custommetric.go index 24d2d089..21bad765 100644 --- a/pkg/client/clientset/versioned/typed/metrics/v1alpha2/custommetric.go +++ b/pkg/client/clientset/versioned/typed/metrics/v1alpha2/custommetric.go @@ -19,8 +19,6 @@ limitations under the License. package v1alpha2 import ( - "time" - v1alpha2 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha2" scheme "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned/scheme" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -75,16 +73,11 @@ func (c *customMetrics) Get(name string, options v1.GetOptions) (result *v1alpha // List takes label and field selectors, and returns the list of CustomMetrics that match those selectors. func (c *customMetrics) List(opts v1.ListOptions) (result *v1alpha2.CustomMetricList, err error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } result = &v1alpha2.CustomMetricList{} err = c.client.Get(). Namespace(c.ns). Resource("custommetrics"). VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). Do(). Into(result) return @@ -92,16 +85,11 @@ func (c *customMetrics) List(opts v1.ListOptions) (result *v1alpha2.CustomMetric // Watch returns a watch.Interface that watches the requested customMetrics. func (c *customMetrics) Watch(opts v1.ListOptions) (watch.Interface, error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } opts.Watch = true return c.client.Get(). Namespace(c.ns). Resource("custommetrics"). VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). Watch() } @@ -143,15 +131,10 @@ func (c *customMetrics) Delete(name string, options *v1.DeleteOptions) error { // DeleteCollection deletes a collection of objects. func (c *customMetrics) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - var timeout time.Duration - if listOptions.TimeoutSeconds != nil { - timeout = time.Duration(*listOptions.TimeoutSeconds) * time.Second - } return c.client.Delete(). Namespace(c.ns). Resource("custommetrics"). VersionedParams(&listOptions, scheme.ParameterCodec). - Timeout(timeout). Body(options). Do(). Error() diff --git a/pkg/client/clientset/versioned/typed/metrics/v1alpha2/externalmetric.go b/pkg/client/clientset/versioned/typed/metrics/v1alpha2/externalmetric.go index 2c42089a..b7539ee6 100644 --- a/pkg/client/clientset/versioned/typed/metrics/v1alpha2/externalmetric.go +++ b/pkg/client/clientset/versioned/typed/metrics/v1alpha2/externalmetric.go @@ -19,8 +19,6 @@ limitations under the License. package v1alpha2 import ( - "time" - v1alpha2 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha2" scheme "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned/scheme" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -75,16 +73,11 @@ func (c *externalMetrics) Get(name string, options v1.GetOptions) (result *v1alp // List takes label and field selectors, and returns the list of ExternalMetrics that match those selectors. func (c *externalMetrics) List(opts v1.ListOptions) (result *v1alpha2.ExternalMetricList, err error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } result = &v1alpha2.ExternalMetricList{} err = c.client.Get(). Namespace(c.ns). Resource("externalmetrics"). VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). Do(). Into(result) return @@ -92,16 +85,11 @@ func (c *externalMetrics) List(opts v1.ListOptions) (result *v1alpha2.ExternalMe // Watch returns a watch.Interface that watches the requested externalMetrics. func (c *externalMetrics) Watch(opts v1.ListOptions) (watch.Interface, error) { - var timeout time.Duration - if opts.TimeoutSeconds != nil { - timeout = time.Duration(*opts.TimeoutSeconds) * time.Second - } opts.Watch = true return c.client.Get(). Namespace(c.ns). Resource("externalmetrics"). VersionedParams(&opts, scheme.ParameterCodec). - Timeout(timeout). Watch() } @@ -143,15 +131,10 @@ func (c *externalMetrics) Delete(name string, options *v1.DeleteOptions) error { // DeleteCollection deletes a collection of objects. func (c *externalMetrics) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - var timeout time.Duration - if listOptions.TimeoutSeconds != nil { - timeout = time.Duration(*listOptions.TimeoutSeconds) * time.Second - } return c.client.Delete(). Namespace(c.ns). Resource("externalmetrics"). VersionedParams(&listOptions, scheme.ParameterCodec). - Timeout(timeout). Body(options). Do(). Error() diff --git a/pkg/client/informers/externalversions/internalinterfaces/factory_interfaces.go b/pkg/client/informers/externalversions/internalinterfaces/factory_interfaces.go index 185b3f38..6f86a7b1 100644 --- a/pkg/client/informers/externalversions/internalinterfaces/factory_interfaces.go +++ b/pkg/client/informers/externalversions/internalinterfaces/factory_interfaces.go @@ -27,7 +27,6 @@ import ( cache "k8s.io/client-go/tools/cache" ) -// NewInformerFunc takes versioned.Interface and time.Duration to return a SharedIndexInformer. type NewInformerFunc func(versioned.Interface, time.Duration) cache.SharedIndexInformer // SharedInformerFactory a small interface to allow for adding an informer without an import cycle @@ -36,5 +35,4 @@ type SharedInformerFactory interface { InformerFor(obj runtime.Object, newFunc NewInformerFunc) cache.SharedIndexInformer } -// TweakListOptionsFunc is a function that transforms a v1.ListOptions. type TweakListOptionsFunc func(*v1.ListOptions) From 8440c8bfdfc0ef1656d72e7f4665a210c0476193 Mon Sep 17 00:00:00 2001 From: James Sturtevant Date: Fri, 25 Jan 2019 16:18:06 -0800 Subject: [PATCH 10/23] Rename function to match metric provider interface --- pkg/controller/handler_test.go | 8 ++++---- pkg/metriccache/metric_cache.go | 4 ++-- pkg/provider/provider_external.go | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/pkg/controller/handler_test.go b/pkg/controller/handler_test.go index 60ee1460..f5ba1efc 100644 --- a/pkg/controller/handler_test.go +++ b/pkg/controller/handler_test.go @@ -46,7 +46,7 @@ func TestExternalMetricValueIsStored(t *testing.T) { t.Errorf("error after processing = %v, want %v", err, nil) } - metricRequest, exists := metriccache.GetAzureMonitorRequest(externalMetric.Namespace, externalMetric.Name) + metricRequest, exists := metriccache.GetAzureExternalMetricRequest(externalMetric.Namespace, externalMetric.Name) if exists == false { t.Errorf("exist = %v, want %v", exists, true) @@ -82,7 +82,7 @@ func TestShouldBeAbleToStoreCustomAndExternalWithSameNameAndNamespace(t *testing t.Errorf("error after processing = %v, want %v", err, nil) } - externalRequest, exists := metriccache.GetAzureMonitorRequest(externalMetric.Namespace, externalMetric.Name) + externalRequest, exists := metriccache.GetAzureExternalMetricRequest(externalMetric.Namespace, externalMetric.Name) if exists == false { t.Errorf("exist = %v, want %v", exists, true) @@ -147,7 +147,7 @@ func TestShouldFailOnInvalidCacheKey(t *testing.T) { t.Errorf("error after processing nil, want non nil") } - _, exists := metriccache.GetAzureMonitorRequest(externalMetric.Namespace, externalMetric.Name) + _, exists := metriccache.GetAzureExternalMetricRequest(externalMetric.Namespace, externalMetric.Name) if exists == true { t.Errorf("exist = %v, want %v", exists, false) @@ -174,7 +174,7 @@ func TestWhenExternalItemHasBeenDeleted(t *testing.T) { t.Errorf("error == %v, want nil", err) } - _, exists := metriccache.GetAzureMonitorRequest(externalMetric.Namespace, externalMetric.Name) + _, exists := metriccache.GetAzureExternalMetricRequest(externalMetric.Namespace, externalMetric.Name) if exists == true { t.Errorf("exist = %v, want %v", exists, false) diff --git a/pkg/metriccache/metric_cache.go b/pkg/metriccache/metric_cache.go index cb599fcb..0565ab12 100644 --- a/pkg/metriccache/metric_cache.go +++ b/pkg/metriccache/metric_cache.go @@ -30,8 +30,8 @@ func (mc *MetricCache) Update(key string, metricRequest interface{}) { mc.metricRequests[key] = metricRequest } -// GetAzureMonitorRequest retrieves a metric request from the cache -func (mc *MetricCache) GetAzureMonitorRequest(namepace, name string) (azureexternalmetrics.AzureExternalMetricRequest, bool) { +// GetAzureExternalMetricRequest retrieves a metric request from the cache +func (mc *MetricCache) GetAzureExternalMetricRequest(namepace, name string) (azureexternalmetrics.AzureExternalMetricRequest, bool) { mc.metricMutext.RLock() defer mc.metricMutext.RUnlock() diff --git a/pkg/provider/provider_external.go b/pkg/provider/provider_external.go index cfa74901..4fb62ed1 100644 --- a/pkg/provider/provider_external.go +++ b/pkg/provider/provider_external.go @@ -74,7 +74,7 @@ func (p *AzureProvider) ListAllExternalMetrics() []provider.ExternalMetricInfo { func (p *AzureProvider) getMetricRequest(namespace string, metricName string, metricSelector labels.Selector) (azureexternalmetrics.AzureExternalMetricRequest, error) { - azMetricRequest, found := p.metricCache.GetAzureMonitorRequest(namespace, metricName) + azMetricRequest, found := p.metricCache.GetAzureExternalMetricRequest(namespace, metricName) if found { azMetricRequest.Timespan = azureexternalmetrics.TimeSpan() if azMetricRequest.SubscriptionID == "" { From 0fc5d36051a50ebe2615e06deb839c10e7d88e90 Mon Sep 17 00:00:00 2001 From: James Sturtevant Date: Fri, 1 Feb 2019 15:19:36 -0800 Subject: [PATCH 11/23] Move to v1alpha2, drop v1alpha1 --- .../templates/apis.yaml | 4 +- deploy/adapter.yaml | 4 +- hack/update-codegen.sh | 2 +- main.go | 8 +- pkg/apis/metrics/v1alpha1/custommetric.go | 44 ---- pkg/apis/metrics/v1alpha1/doc.go | 4 - pkg/apis/metrics/v1alpha1/externalmetric.go | 54 ----- pkg/apis/metrics/v1alpha1/register.go | 40 --- .../metrics/v1alpha1/zz_generated.deepcopy.go | 228 ------------------ pkg/client/README.md | 6 - pkg/client/clientset/versioned/clientset.go | 26 +- .../versioned/fake/clientset_generated.go | 17 +- .../clientset/versioned/fake/register.go | 2 - .../clientset/versioned/scheme/register.go | 2 - .../typed/metrics/v1alpha1/custommetric.go | 141 ----------- .../versioned/typed/metrics/v1alpha1/doc.go | 20 -- .../typed/metrics/v1alpha1/externalmetric.go | 141 ----------- .../typed/metrics/v1alpha1/fake/doc.go | 20 -- .../v1alpha1/fake/fake_custommetric.go | 116 --------- .../v1alpha1/fake/fake_externalmetric.go | 116 --------- .../v1alpha1/fake/fake_metrics_client.go | 44 ---- .../metrics/v1alpha1/generated_expansion.go | 23 -- .../typed/metrics/v1alpha1/metrics_client.go | 95 -------- .../informers/externalversions/generic.go | 9 +- .../externalversions/metrics/interface.go | 8 - .../metrics/v1alpha1/custommetric.go | 89 ------- .../metrics/v1alpha1/externalmetric.go | 89 ------- .../metrics/v1alpha1/interface.go | 52 ---- .../listers/metrics/v1alpha1/custommetric.go | 94 -------- .../metrics/v1alpha1/expansion_generated.go | 35 --- .../metrics/v1alpha1/externalmetric.go | 94 -------- pkg/controller/controller.go | 8 +- pkg/controller/controller_test.go | 8 +- pkg/controller/handler.go | 6 +- pkg/controller/handler_test.go | 10 +- .../deploy/custom-metric.yaml | 2 +- .../custommetric-example.yaml | 2 +- .../azuremonitor-example.yaml} | 5 +- .../servicebussubscription-example.yaml | 14 ++ .../deploy/externalmetric.yaml | 2 +- 40 files changed, 59 insertions(+), 1625 deletions(-) delete mode 100755 pkg/apis/metrics/v1alpha1/custommetric.go delete mode 100755 pkg/apis/metrics/v1alpha1/doc.go delete mode 100644 pkg/apis/metrics/v1alpha1/externalmetric.go delete mode 100755 pkg/apis/metrics/v1alpha1/register.go delete mode 100644 pkg/apis/metrics/v1alpha1/zz_generated.deepcopy.go delete mode 100644 pkg/client/README.md delete mode 100644 pkg/client/clientset/versioned/typed/metrics/v1alpha1/custommetric.go delete mode 100644 pkg/client/clientset/versioned/typed/metrics/v1alpha1/doc.go delete mode 100644 pkg/client/clientset/versioned/typed/metrics/v1alpha1/externalmetric.go delete mode 100644 pkg/client/clientset/versioned/typed/metrics/v1alpha1/fake/doc.go delete mode 100644 pkg/client/clientset/versioned/typed/metrics/v1alpha1/fake/fake_custommetric.go delete mode 100644 pkg/client/clientset/versioned/typed/metrics/v1alpha1/fake/fake_externalmetric.go delete mode 100644 pkg/client/clientset/versioned/typed/metrics/v1alpha1/fake/fake_metrics_client.go delete mode 100644 pkg/client/clientset/versioned/typed/metrics/v1alpha1/generated_expansion.go delete mode 100644 pkg/client/clientset/versioned/typed/metrics/v1alpha1/metrics_client.go delete mode 100644 pkg/client/informers/externalversions/metrics/v1alpha1/custommetric.go delete mode 100644 pkg/client/informers/externalversions/metrics/v1alpha1/externalmetric.go delete mode 100644 pkg/client/informers/externalversions/metrics/v1alpha1/interface.go delete mode 100644 pkg/client/listers/metrics/v1alpha1/custommetric.go delete mode 100644 pkg/client/listers/metrics/v1alpha1/expansion_generated.go delete mode 100644 pkg/client/listers/metrics/v1alpha1/externalmetric.go rename samples/resources/{ => custommetric-examples}/custommetric-example.yaml (86%) rename samples/resources/{externalmetric-example.yaml => externalmetric-examples/azuremonitor-example.yaml} (78%) create mode 100644 samples/resources/externalmetric-examples/servicebussubscription-example.yaml diff --git a/charts/azure-k8s-metrics-adapter/templates/apis.yaml b/charts/azure-k8s-metrics-adapter/templates/apis.yaml index aa1d1876..199715a9 100755 --- a/charts/azure-k8s-metrics-adapter/templates/apis.yaml +++ b/charts/azure-k8s-metrics-adapter/templates/apis.yaml @@ -6,7 +6,7 @@ metadata: spec: # group name to use for REST API: /apis// group: azure.com - version: v1alpha1 + version: v1alpha2 scope: Namespaced names: # plural name to be used in the URL: /apis/// @@ -25,7 +25,7 @@ metadata: spec: # group name to use for REST API: /apis// group: azure.com - version: v1alpha1 + version: v1alpha2 scope: Namespaced names: # plural name to be used in the URL: /apis/// diff --git a/deploy/adapter.yaml b/deploy/adapter.yaml index 44448161..f4ea0789 100644 --- a/deploy/adapter.yaml +++ b/deploy/adapter.yaml @@ -30,7 +30,7 @@ metadata: spec: # group name to use for REST API: /apis// group: azure.com - version: v1alpha1 + version: v1alpha2 scope: Namespaced names: # plural name to be used in the URL: /apis/// @@ -49,7 +49,7 @@ metadata: spec: # group name to use for REST API: /apis// group: azure.com - version: v1alpha1 + version: v1alpha2 scope: Namespaced names: # plural name to be used in the URL: /apis/// diff --git a/hack/update-codegen.sh b/hack/update-codegen.sh index e6c13f3b..5a096453 100755 --- a/hack/update-codegen.sh +++ b/hack/update-codegen.sh @@ -7,4 +7,4 @@ set -o pipefail $GOPATH/src/k8s.io/code-generator/generate-groups.sh all \ github.com/Azure/azure-k8s-metrics-adapter/pkg/client \ github.com/Azure/azure-k8s-metrics-adapter/pkg/apis \ - metrics:v1alpha1,v1alpha2 + metrics:v1alpha2 diff --git a/main.go b/main.go index be8fef4d..c0cd1457 100755 --- a/main.go +++ b/main.go @@ -87,12 +87,12 @@ func newController(cmd *basecmd.AdapterBase, metricsCache *metriccache.MetricCac } adapterInformerFactory := informers.NewSharedInformerFactory(adapterClientSet, time.Second*30) - handler := controller.NewHandler(adapterInformerFactory.Azure().V1alpha1().ExternalMetrics().Lister(), - adapterInformerFactory.Azure().V1alpha1().CustomMetrics().Lister(), + handler := controller.NewHandler(adapterInformerFactory.Azure().V1alpha2().ExternalMetrics().Lister(), + adapterInformerFactory.Azure().V1alpha2().CustomMetrics().Lister(), metricsCache) - controller := controller.NewController(adapterInformerFactory.Azure().V1alpha1().ExternalMetrics(), - adapterInformerFactory.Azure().V1alpha1().CustomMetrics(), &handler) + controller := controller.NewController(adapterInformerFactory.Azure().V1alpha2().ExternalMetrics(), + adapterInformerFactory.Azure().V1alpha2().CustomMetrics(), &handler) return controller, adapterInformerFactory } diff --git a/pkg/apis/metrics/v1alpha1/custommetric.go b/pkg/apis/metrics/v1alpha1/custommetric.go deleted file mode 100755 index 6bf16d69..00000000 --- a/pkg/apis/metrics/v1alpha1/custommetric.go +++ /dev/null @@ -1,44 +0,0 @@ -package v1alpha1 - -import ( - meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -// +genclient -// +genclient:noStatus -// +genclient:skipVerbs=patch -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// CustomMetric describes a configuration for Application insights -type CustomMetric struct { - // TypeMeta is the metadata for the resource, like kind and apiversion - meta_v1.TypeMeta `json:",inline"` - - // ObjectMeta contains the metadata for the particular object (name, namespace, self link, labels, etc) - meta_v1.ObjectMeta `json:"metadata,omitempty"` - - // Spec is the custom resource spec - Spec CustomMetricSpec `json:"spec"` -} - -// CustomMetricSpec is the spec for a CustomMetric resource -type CustomMetricSpec struct { - MetricConfig CustomMetricConfig `json:"metric"` -} - -// CustomMetricConfig holds app insights configuration -type CustomMetricConfig struct { - MetricName string `json:"metricName"` - ApplicationID string `json:"applicationID"` - Query string `json:"query"` -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// CustomMetricList is a list of CustomMetric resources -type CustomMetricList struct { - meta_v1.TypeMeta `json:",inline"` - meta_v1.ListMeta `json:"metadata"` - - Items []CustomMetric `json:"items"` -} diff --git a/pkg/apis/metrics/v1alpha1/doc.go b/pkg/apis/metrics/v1alpha1/doc.go deleted file mode 100755 index 57b50e6c..00000000 --- a/pkg/apis/metrics/v1alpha1/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// +k8s:deepcopy-gen=package -// +groupName=azure.com - -package v1alpha1 diff --git a/pkg/apis/metrics/v1alpha1/externalmetric.go b/pkg/apis/metrics/v1alpha1/externalmetric.go deleted file mode 100644 index 35da8cbc..00000000 --- a/pkg/apis/metrics/v1alpha1/externalmetric.go +++ /dev/null @@ -1,54 +0,0 @@ -package v1alpha1 - -import ( - meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -// +genclient -// +genclient:noStatus -// +genclient:skipVerbs=patch -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// ExternalMetric describes a ExternalMetric resource -type ExternalMetric struct { - // TypeMeta is the metadata for the resource, like kind and apiversion - meta_v1.TypeMeta `json:",inline"` - - // ObjectMeta contains the metadata for the particular object (name, namespace, self link, labels, etc) - meta_v1.ObjectMeta `json:"metadata,omitempty"` - - // Spec is the custom resource spec - Spec ExternalMetricSpec `json:"spec"` -} - -// ExternalMetricSpec is the spec for a ExternalMetric resource -type ExternalMetricSpec struct { - MetricConfig ExternalMetricConfig `json:"metric"` - AzureConfig AzureConfig `json:"azure"` -} - -// ExternalMetricConfig holds azure monitor metric configuration -type ExternalMetricConfig struct { - MetricName string `json:"metricName"` - Aggregation string `json:"aggregation"` - Filter string `json:"filter"` -} - -// AzureConfig holds azure monitor azure configuration -type AzureConfig struct { - ResourceGroup string `json:"resourceGroup"` - ResourceName string `json:"resourceName"` - ResourceProviderNamespace string `json:"resourceProviderNamespace"` - ResourceType string `json:"resourceType"` - SubscriptionID string `json:"subscriptionID"` -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// ExternalMetricList is a list of ExternalMetric resources -type ExternalMetricList struct { - meta_v1.TypeMeta `json:",inline"` - meta_v1.ListMeta `json:"metadata"` - - Items []ExternalMetric `json:"items"` -} diff --git a/pkg/apis/metrics/v1alpha1/register.go b/pkg/apis/metrics/v1alpha1/register.go deleted file mode 100755 index 11b02435..00000000 --- a/pkg/apis/metrics/v1alpha1/register.go +++ /dev/null @@ -1,40 +0,0 @@ -package v1alpha1 - -import ( - meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - - "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics" -) - -// GroupVersion is the identifier for the API which includes -// the name of the group and the version of the API -var SchemeGroupVersion = schema.GroupVersion{ - Group: externalmetric.GroupName, - Version: "v1alpha1", -} - -var ( - SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) - AddToScheme = SchemeBuilder.AddToScheme -) - -func Resource(resource string) schema.GroupResource { - return SchemeGroupVersion.WithResource(resource).GroupResource() -} - -// addKnownTypes adds our types to the API scheme by registering -func addKnownTypes(scheme *runtime.Scheme) error { - scheme.AddKnownTypes( - SchemeGroupVersion, - &ExternalMetric{}, - &ExternalMetricList{}, - &CustomMetric{}, - &CustomMetricList{}, - ) - - // register the type in the scheme - meta_v1.AddToGroupVersion(scheme, SchemeGroupVersion) - return nil -} diff --git a/pkg/apis/metrics/v1alpha1/zz_generated.deepcopy.go b/pkg/apis/metrics/v1alpha1/zz_generated.deepcopy.go deleted file mode 100644 index 920e573e..00000000 --- a/pkg/apis/metrics/v1alpha1/zz_generated.deepcopy.go +++ /dev/null @@ -1,228 +0,0 @@ -// +build !ignore_autogenerated - -/* -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 deepcopy-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - runtime "k8s.io/apimachinery/pkg/runtime" -) - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *AzureConfig) DeepCopyInto(out *AzureConfig) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AzureConfig. -func (in *AzureConfig) DeepCopy() *AzureConfig { - if in == nil { - return nil - } - out := new(AzureConfig) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *CustomMetric) DeepCopyInto(out *CustomMetric) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - out.Spec = in.Spec - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomMetric. -func (in *CustomMetric) DeepCopy() *CustomMetric { - if in == nil { - return nil - } - out := new(CustomMetric) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *CustomMetric) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *CustomMetricConfig) DeepCopyInto(out *CustomMetricConfig) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomMetricConfig. -func (in *CustomMetricConfig) DeepCopy() *CustomMetricConfig { - if in == nil { - return nil - } - out := new(CustomMetricConfig) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *CustomMetricList) DeepCopyInto(out *CustomMetricList) { - *out = *in - out.TypeMeta = in.TypeMeta - out.ListMeta = in.ListMeta - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]CustomMetric, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomMetricList. -func (in *CustomMetricList) DeepCopy() *CustomMetricList { - if in == nil { - return nil - } - out := new(CustomMetricList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *CustomMetricList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *CustomMetricSpec) DeepCopyInto(out *CustomMetricSpec) { - *out = *in - out.MetricConfig = in.MetricConfig - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CustomMetricSpec. -func (in *CustomMetricSpec) DeepCopy() *CustomMetricSpec { - if in == nil { - return nil - } - out := new(CustomMetricSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ExternalMetric) DeepCopyInto(out *ExternalMetric) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - out.Spec = in.Spec - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExternalMetric. -func (in *ExternalMetric) DeepCopy() *ExternalMetric { - if in == nil { - return nil - } - out := new(ExternalMetric) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *ExternalMetric) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ExternalMetricConfig) DeepCopyInto(out *ExternalMetricConfig) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExternalMetricConfig. -func (in *ExternalMetricConfig) DeepCopy() *ExternalMetricConfig { - if in == nil { - return nil - } - out := new(ExternalMetricConfig) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ExternalMetricList) DeepCopyInto(out *ExternalMetricList) { - *out = *in - out.TypeMeta = in.TypeMeta - out.ListMeta = in.ListMeta - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]ExternalMetric, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExternalMetricList. -func (in *ExternalMetricList) DeepCopy() *ExternalMetricList { - if in == nil { - return nil - } - out := new(ExternalMetricList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *ExternalMetricList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ExternalMetricSpec) DeepCopyInto(out *ExternalMetricSpec) { - *out = *in - out.MetricConfig = in.MetricConfig - out.AzureConfig = in.AzureConfig - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExternalMetricSpec. -func (in *ExternalMetricSpec) DeepCopy() *ExternalMetricSpec { - if in == nil { - return nil - } - out := new(ExternalMetricSpec) - in.DeepCopyInto(out) - return out -} diff --git a/pkg/client/README.md b/pkg/client/README.md deleted file mode 100644 index 66ce187e..00000000 --- a/pkg/client/README.md +++ /dev/null @@ -1,6 +0,0 @@ -All of the code in the folder is auto-generated. To make modifications, update the files under the folder `../apis` and run `make gen-apis` followed by `make verify-apis`. - -Learn more about code generation for CRD's: - -https://blog.openshift.com/kubernetes-deep-dive-code-generation-customresources/ -/~https://github.com/kubernetes/sample-controller/ \ No newline at end of file diff --git a/pkg/client/clientset/versioned/clientset.go b/pkg/client/clientset/versioned/clientset.go index 3c662b29..00f5b803 100644 --- a/pkg/client/clientset/versioned/clientset.go +++ b/pkg/client/clientset/versioned/clientset.go @@ -19,7 +19,6 @@ limitations under the License. package versioned import ( - azurev1alpha1 "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned/typed/metrics/v1alpha1" azurev1alpha2 "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned/typed/metrics/v1alpha2" discovery "k8s.io/client-go/discovery" rest "k8s.io/client-go/rest" @@ -28,33 +27,26 @@ import ( type Interface interface { Discovery() discovery.DiscoveryInterface - AzureV1alpha1() azurev1alpha1.AzureV1alpha1Interface - // Deprecated: please explicitly pick a version if possible. - Azure() azurev1alpha1.AzureV1alpha1Interface AzureV1alpha2() azurev1alpha2.AzureV1alpha2Interface + // Deprecated: please explicitly pick a version if possible. + Azure() azurev1alpha2.AzureV1alpha2Interface } // Clientset contains the clients for groups. Each group has exactly one // version included in a Clientset. type Clientset struct { *discovery.DiscoveryClient - azureV1alpha1 *azurev1alpha1.AzureV1alpha1Client azureV1alpha2 *azurev1alpha2.AzureV1alpha2Client } -// AzureV1alpha1 retrieves the AzureV1alpha1Client -func (c *Clientset) AzureV1alpha1() azurev1alpha1.AzureV1alpha1Interface { - return c.azureV1alpha1 +// AzureV1alpha2 retrieves the AzureV1alpha2Client +func (c *Clientset) AzureV1alpha2() azurev1alpha2.AzureV1alpha2Interface { + return c.azureV1alpha2 } // Deprecated: Azure retrieves the default version of AzureClient. // Please explicitly pick a version. -func (c *Clientset) Azure() azurev1alpha1.AzureV1alpha1Interface { - return c.azureV1alpha1 -} - -// AzureV1alpha2 retrieves the AzureV1alpha2Client -func (c *Clientset) AzureV1alpha2() azurev1alpha2.AzureV1alpha2Interface { +func (c *Clientset) Azure() azurev1alpha2.AzureV1alpha2Interface { return c.azureV1alpha2 } @@ -74,10 +66,6 @@ func NewForConfig(c *rest.Config) (*Clientset, error) { } var cs Clientset var err error - cs.azureV1alpha1, err = azurev1alpha1.NewForConfig(&configShallowCopy) - if err != nil { - return nil, err - } cs.azureV1alpha2, err = azurev1alpha2.NewForConfig(&configShallowCopy) if err != nil { return nil, err @@ -94,7 +82,6 @@ func NewForConfig(c *rest.Config) (*Clientset, error) { // panics if there is an error in the config. func NewForConfigOrDie(c *rest.Config) *Clientset { var cs Clientset - cs.azureV1alpha1 = azurev1alpha1.NewForConfigOrDie(c) cs.azureV1alpha2 = azurev1alpha2.NewForConfigOrDie(c) cs.DiscoveryClient = discovery.NewDiscoveryClientForConfigOrDie(c) @@ -104,7 +91,6 @@ func NewForConfigOrDie(c *rest.Config) *Clientset { // New creates a new Clientset for the given RESTClient. func New(c rest.Interface) *Clientset { var cs Clientset - cs.azureV1alpha1 = azurev1alpha1.New(c) cs.azureV1alpha2 = azurev1alpha2.New(c) cs.DiscoveryClient = discovery.NewDiscoveryClient(c) diff --git a/pkg/client/clientset/versioned/fake/clientset_generated.go b/pkg/client/clientset/versioned/fake/clientset_generated.go index 387285cb..9f194956 100644 --- a/pkg/client/clientset/versioned/fake/clientset_generated.go +++ b/pkg/client/clientset/versioned/fake/clientset_generated.go @@ -20,8 +20,6 @@ package fake import ( clientset "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned" - azurev1alpha1 "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned/typed/metrics/v1alpha1" - fakeazurev1alpha1 "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned/typed/metrics/v1alpha1/fake" azurev1alpha2 "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned/typed/metrics/v1alpha2" fakeazurev1alpha2 "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned/typed/metrics/v1alpha2/fake" "k8s.io/apimachinery/pkg/runtime" @@ -73,17 +71,12 @@ func (c *Clientset) Discovery() discovery.DiscoveryInterface { var _ clientset.Interface = &Clientset{} -// AzureV1alpha1 retrieves the AzureV1alpha1Client -func (c *Clientset) AzureV1alpha1() azurev1alpha1.AzureV1alpha1Interface { - return &fakeazurev1alpha1.FakeAzureV1alpha1{Fake: &c.Fake} -} - -// Azure retrieves the AzureV1alpha1Client -func (c *Clientset) Azure() azurev1alpha1.AzureV1alpha1Interface { - return &fakeazurev1alpha1.FakeAzureV1alpha1{Fake: &c.Fake} -} - // AzureV1alpha2 retrieves the AzureV1alpha2Client func (c *Clientset) AzureV1alpha2() azurev1alpha2.AzureV1alpha2Interface { return &fakeazurev1alpha2.FakeAzureV1alpha2{Fake: &c.Fake} } + +// Azure retrieves the AzureV1alpha2Client +func (c *Clientset) Azure() azurev1alpha2.AzureV1alpha2Interface { + return &fakeazurev1alpha2.FakeAzureV1alpha2{Fake: &c.Fake} +} diff --git a/pkg/client/clientset/versioned/fake/register.go b/pkg/client/clientset/versioned/fake/register.go index 6d840f81..cfbcc4fa 100644 --- a/pkg/client/clientset/versioned/fake/register.go +++ b/pkg/client/clientset/versioned/fake/register.go @@ -19,7 +19,6 @@ limitations under the License. package fake import ( - azurev1alpha1 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha1" azurev1alpha2 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha2" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" @@ -32,7 +31,6 @@ var scheme = runtime.NewScheme() var codecs = serializer.NewCodecFactory(scheme) var parameterCodec = runtime.NewParameterCodec(scheme) var localSchemeBuilder = runtime.SchemeBuilder{ - azurev1alpha1.AddToScheme, azurev1alpha2.AddToScheme, } diff --git a/pkg/client/clientset/versioned/scheme/register.go b/pkg/client/clientset/versioned/scheme/register.go index 012df9b8..7bc6f2c3 100644 --- a/pkg/client/clientset/versioned/scheme/register.go +++ b/pkg/client/clientset/versioned/scheme/register.go @@ -19,7 +19,6 @@ limitations under the License. package scheme import ( - azurev1alpha1 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha1" azurev1alpha2 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha2" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" @@ -32,7 +31,6 @@ var Scheme = runtime.NewScheme() var Codecs = serializer.NewCodecFactory(Scheme) var ParameterCodec = runtime.NewParameterCodec(Scheme) var localSchemeBuilder = runtime.SchemeBuilder{ - azurev1alpha1.AddToScheme, azurev1alpha2.AddToScheme, } diff --git a/pkg/client/clientset/versioned/typed/metrics/v1alpha1/custommetric.go b/pkg/client/clientset/versioned/typed/metrics/v1alpha1/custommetric.go deleted file mode 100644 index dc7d3a7b..00000000 --- a/pkg/client/clientset/versioned/typed/metrics/v1alpha1/custommetric.go +++ /dev/null @@ -1,141 +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 client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha1" - scheme "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" -) - -// CustomMetricsGetter has a method to return a CustomMetricInterface. -// A group's client should implement this interface. -type CustomMetricsGetter interface { - CustomMetrics(namespace string) CustomMetricInterface -} - -// CustomMetricInterface has methods to work with CustomMetric resources. -type CustomMetricInterface interface { - Create(*v1alpha1.CustomMetric) (*v1alpha1.CustomMetric, error) - Update(*v1alpha1.CustomMetric) (*v1alpha1.CustomMetric, error) - Delete(name string, options *v1.DeleteOptions) error - DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error - Get(name string, options v1.GetOptions) (*v1alpha1.CustomMetric, error) - List(opts v1.ListOptions) (*v1alpha1.CustomMetricList, error) - Watch(opts v1.ListOptions) (watch.Interface, error) - CustomMetricExpansion -} - -// customMetrics implements CustomMetricInterface -type customMetrics struct { - client rest.Interface - ns string -} - -// newCustomMetrics returns a CustomMetrics -func newCustomMetrics(c *AzureV1alpha1Client, namespace string) *customMetrics { - return &customMetrics{ - client: c.RESTClient(), - ns: namespace, - } -} - -// Get takes name of the customMetric, and returns the corresponding customMetric object, and an error if there is any. -func (c *customMetrics) Get(name string, options v1.GetOptions) (result *v1alpha1.CustomMetric, err error) { - result = &v1alpha1.CustomMetric{} - err = c.client.Get(). - Namespace(c.ns). - Resource("custommetrics"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of CustomMetrics that match those selectors. -func (c *customMetrics) List(opts v1.ListOptions) (result *v1alpha1.CustomMetricList, err error) { - result = &v1alpha1.CustomMetricList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("custommetrics"). - VersionedParams(&opts, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested customMetrics. -func (c *customMetrics) Watch(opts v1.ListOptions) (watch.Interface, error) { - opts.Watch = true - return c.client.Get(). - Namespace(c.ns). - Resource("custommetrics"). - VersionedParams(&opts, scheme.ParameterCodec). - Watch() -} - -// Create takes the representation of a customMetric and creates it. Returns the server's representation of the customMetric, and an error, if there is any. -func (c *customMetrics) Create(customMetric *v1alpha1.CustomMetric) (result *v1alpha1.CustomMetric, err error) { - result = &v1alpha1.CustomMetric{} - err = c.client.Post(). - Namespace(c.ns). - Resource("custommetrics"). - Body(customMetric). - Do(). - Into(result) - return -} - -// Update takes the representation of a customMetric and updates it. Returns the server's representation of the customMetric, and an error, if there is any. -func (c *customMetrics) Update(customMetric *v1alpha1.CustomMetric) (result *v1alpha1.CustomMetric, err error) { - result = &v1alpha1.CustomMetric{} - err = c.client.Put(). - Namespace(c.ns). - Resource("custommetrics"). - Name(customMetric.Name). - Body(customMetric). - Do(). - Into(result) - return -} - -// Delete takes name of the customMetric and deletes it. Returns an error if one occurs. -func (c *customMetrics) Delete(name string, options *v1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("custommetrics"). - Name(name). - Body(options). - Do(). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *customMetrics) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("custommetrics"). - VersionedParams(&listOptions, scheme.ParameterCodec). - Body(options). - Do(). - Error() -} diff --git a/pkg/client/clientset/versioned/typed/metrics/v1alpha1/doc.go b/pkg/client/clientset/versioned/typed/metrics/v1alpha1/doc.go deleted file mode 100644 index df51baa4..00000000 --- a/pkg/client/clientset/versioned/typed/metrics/v1alpha1/doc.go +++ /dev/null @@ -1,20 +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 client-gen. DO NOT EDIT. - -// This package has the automatically generated typed clients. -package v1alpha1 diff --git a/pkg/client/clientset/versioned/typed/metrics/v1alpha1/externalmetric.go b/pkg/client/clientset/versioned/typed/metrics/v1alpha1/externalmetric.go deleted file mode 100644 index 61ece856..00000000 --- a/pkg/client/clientset/versioned/typed/metrics/v1alpha1/externalmetric.go +++ /dev/null @@ -1,141 +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 client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha1" - scheme "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned/scheme" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" -) - -// ExternalMetricsGetter has a method to return a ExternalMetricInterface. -// A group's client should implement this interface. -type ExternalMetricsGetter interface { - ExternalMetrics(namespace string) ExternalMetricInterface -} - -// ExternalMetricInterface has methods to work with ExternalMetric resources. -type ExternalMetricInterface interface { - Create(*v1alpha1.ExternalMetric) (*v1alpha1.ExternalMetric, error) - Update(*v1alpha1.ExternalMetric) (*v1alpha1.ExternalMetric, error) - Delete(name string, options *v1.DeleteOptions) error - DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error - Get(name string, options v1.GetOptions) (*v1alpha1.ExternalMetric, error) - List(opts v1.ListOptions) (*v1alpha1.ExternalMetricList, error) - Watch(opts v1.ListOptions) (watch.Interface, error) - ExternalMetricExpansion -} - -// externalMetrics implements ExternalMetricInterface -type externalMetrics struct { - client rest.Interface - ns string -} - -// newExternalMetrics returns a ExternalMetrics -func newExternalMetrics(c *AzureV1alpha1Client, namespace string) *externalMetrics { - return &externalMetrics{ - client: c.RESTClient(), - ns: namespace, - } -} - -// Get takes name of the externalMetric, and returns the corresponding externalMetric object, and an error if there is any. -func (c *externalMetrics) Get(name string, options v1.GetOptions) (result *v1alpha1.ExternalMetric, err error) { - result = &v1alpha1.ExternalMetric{} - err = c.client.Get(). - Namespace(c.ns). - Resource("externalmetrics"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of ExternalMetrics that match those selectors. -func (c *externalMetrics) List(opts v1.ListOptions) (result *v1alpha1.ExternalMetricList, err error) { - result = &v1alpha1.ExternalMetricList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("externalmetrics"). - VersionedParams(&opts, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested externalMetrics. -func (c *externalMetrics) Watch(opts v1.ListOptions) (watch.Interface, error) { - opts.Watch = true - return c.client.Get(). - Namespace(c.ns). - Resource("externalmetrics"). - VersionedParams(&opts, scheme.ParameterCodec). - Watch() -} - -// Create takes the representation of a externalMetric and creates it. Returns the server's representation of the externalMetric, and an error, if there is any. -func (c *externalMetrics) Create(externalMetric *v1alpha1.ExternalMetric) (result *v1alpha1.ExternalMetric, err error) { - result = &v1alpha1.ExternalMetric{} - err = c.client.Post(). - Namespace(c.ns). - Resource("externalmetrics"). - Body(externalMetric). - Do(). - Into(result) - return -} - -// Update takes the representation of a externalMetric and updates it. Returns the server's representation of the externalMetric, and an error, if there is any. -func (c *externalMetrics) Update(externalMetric *v1alpha1.ExternalMetric) (result *v1alpha1.ExternalMetric, err error) { - result = &v1alpha1.ExternalMetric{} - err = c.client.Put(). - Namespace(c.ns). - Resource("externalmetrics"). - Name(externalMetric.Name). - Body(externalMetric). - Do(). - Into(result) - return -} - -// Delete takes name of the externalMetric and deletes it. Returns an error if one occurs. -func (c *externalMetrics) Delete(name string, options *v1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("externalmetrics"). - Name(name). - Body(options). - Do(). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *externalMetrics) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("externalmetrics"). - VersionedParams(&listOptions, scheme.ParameterCodec). - Body(options). - Do(). - Error() -} diff --git a/pkg/client/clientset/versioned/typed/metrics/v1alpha1/fake/doc.go b/pkg/client/clientset/versioned/typed/metrics/v1alpha1/fake/doc.go deleted file mode 100644 index 16f44399..00000000 --- a/pkg/client/clientset/versioned/typed/metrics/v1alpha1/fake/doc.go +++ /dev/null @@ -1,20 +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 client-gen. DO NOT EDIT. - -// Package fake has the automatically generated clients. -package fake diff --git a/pkg/client/clientset/versioned/typed/metrics/v1alpha1/fake/fake_custommetric.go b/pkg/client/clientset/versioned/typed/metrics/v1alpha1/fake/fake_custommetric.go deleted file mode 100644 index 1b7bcf60..00000000 --- a/pkg/client/clientset/versioned/typed/metrics/v1alpha1/fake/fake_custommetric.go +++ /dev/null @@ -1,116 +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 client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha1 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - schema "k8s.io/apimachinery/pkg/runtime/schema" - watch "k8s.io/apimachinery/pkg/watch" - testing "k8s.io/client-go/testing" -) - -// FakeCustomMetrics implements CustomMetricInterface -type FakeCustomMetrics struct { - Fake *FakeAzureV1alpha1 - ns string -} - -var custommetricsResource = schema.GroupVersionResource{Group: "azure.com", Version: "v1alpha1", Resource: "custommetrics"} - -var custommetricsKind = schema.GroupVersionKind{Group: "azure.com", Version: "v1alpha1", Kind: "CustomMetric"} - -// Get takes name of the customMetric, and returns the corresponding customMetric object, and an error if there is any. -func (c *FakeCustomMetrics) Get(name string, options v1.GetOptions) (result *v1alpha1.CustomMetric, err error) { - obj, err := c.Fake. - Invokes(testing.NewGetAction(custommetricsResource, c.ns, name), &v1alpha1.CustomMetric{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.CustomMetric), err -} - -// List takes label and field selectors, and returns the list of CustomMetrics that match those selectors. -func (c *FakeCustomMetrics) List(opts v1.ListOptions) (result *v1alpha1.CustomMetricList, err error) { - obj, err := c.Fake. - Invokes(testing.NewListAction(custommetricsResource, custommetricsKind, c.ns, opts), &v1alpha1.CustomMetricList{}) - - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1alpha1.CustomMetricList{ListMeta: obj.(*v1alpha1.CustomMetricList).ListMeta} - for _, item := range obj.(*v1alpha1.CustomMetricList).Items { - if label.Matches(labels.Set(item.Labels)) { - list.Items = append(list.Items, item) - } - } - return list, err -} - -// Watch returns a watch.Interface that watches the requested customMetrics. -func (c *FakeCustomMetrics) Watch(opts v1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewWatchAction(custommetricsResource, c.ns, opts)) - -} - -// Create takes the representation of a customMetric and creates it. Returns the server's representation of the customMetric, and an error, if there is any. -func (c *FakeCustomMetrics) Create(customMetric *v1alpha1.CustomMetric) (result *v1alpha1.CustomMetric, err error) { - obj, err := c.Fake. - Invokes(testing.NewCreateAction(custommetricsResource, c.ns, customMetric), &v1alpha1.CustomMetric{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.CustomMetric), err -} - -// Update takes the representation of a customMetric and updates it. Returns the server's representation of the customMetric, and an error, if there is any. -func (c *FakeCustomMetrics) Update(customMetric *v1alpha1.CustomMetric) (result *v1alpha1.CustomMetric, err error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateAction(custommetricsResource, c.ns, customMetric), &v1alpha1.CustomMetric{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.CustomMetric), err -} - -// Delete takes name of the customMetric and deletes it. Returns an error if one occurs. -func (c *FakeCustomMetrics) Delete(name string, options *v1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewDeleteAction(custommetricsResource, c.ns, name), &v1alpha1.CustomMetric{}) - - return err -} - -// DeleteCollection deletes a collection of objects. -func (c *FakeCustomMetrics) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - action := testing.NewDeleteCollectionAction(custommetricsResource, c.ns, listOptions) - - _, err := c.Fake.Invokes(action, &v1alpha1.CustomMetricList{}) - return err -} diff --git a/pkg/client/clientset/versioned/typed/metrics/v1alpha1/fake/fake_externalmetric.go b/pkg/client/clientset/versioned/typed/metrics/v1alpha1/fake/fake_externalmetric.go deleted file mode 100644 index b9488062..00000000 --- a/pkg/client/clientset/versioned/typed/metrics/v1alpha1/fake/fake_externalmetric.go +++ /dev/null @@ -1,116 +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 client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha1 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - labels "k8s.io/apimachinery/pkg/labels" - schema "k8s.io/apimachinery/pkg/runtime/schema" - watch "k8s.io/apimachinery/pkg/watch" - testing "k8s.io/client-go/testing" -) - -// FakeExternalMetrics implements ExternalMetricInterface -type FakeExternalMetrics struct { - Fake *FakeAzureV1alpha1 - ns string -} - -var externalmetricsResource = schema.GroupVersionResource{Group: "azure.com", Version: "v1alpha1", Resource: "externalmetrics"} - -var externalmetricsKind = schema.GroupVersionKind{Group: "azure.com", Version: "v1alpha1", Kind: "ExternalMetric"} - -// Get takes name of the externalMetric, and returns the corresponding externalMetric object, and an error if there is any. -func (c *FakeExternalMetrics) Get(name string, options v1.GetOptions) (result *v1alpha1.ExternalMetric, err error) { - obj, err := c.Fake. - Invokes(testing.NewGetAction(externalmetricsResource, c.ns, name), &v1alpha1.ExternalMetric{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.ExternalMetric), err -} - -// List takes label and field selectors, and returns the list of ExternalMetrics that match those selectors. -func (c *FakeExternalMetrics) List(opts v1.ListOptions) (result *v1alpha1.ExternalMetricList, err error) { - obj, err := c.Fake. - Invokes(testing.NewListAction(externalmetricsResource, externalmetricsKind, c.ns, opts), &v1alpha1.ExternalMetricList{}) - - if obj == nil { - return nil, err - } - - label, _, _ := testing.ExtractFromListOptions(opts) - if label == nil { - label = labels.Everything() - } - list := &v1alpha1.ExternalMetricList{ListMeta: obj.(*v1alpha1.ExternalMetricList).ListMeta} - for _, item := range obj.(*v1alpha1.ExternalMetricList).Items { - if label.Matches(labels.Set(item.Labels)) { - list.Items = append(list.Items, item) - } - } - return list, err -} - -// Watch returns a watch.Interface that watches the requested externalMetrics. -func (c *FakeExternalMetrics) Watch(opts v1.ListOptions) (watch.Interface, error) { - return c.Fake. - InvokesWatch(testing.NewWatchAction(externalmetricsResource, c.ns, opts)) - -} - -// Create takes the representation of a externalMetric and creates it. Returns the server's representation of the externalMetric, and an error, if there is any. -func (c *FakeExternalMetrics) Create(externalMetric *v1alpha1.ExternalMetric) (result *v1alpha1.ExternalMetric, err error) { - obj, err := c.Fake. - Invokes(testing.NewCreateAction(externalmetricsResource, c.ns, externalMetric), &v1alpha1.ExternalMetric{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.ExternalMetric), err -} - -// Update takes the representation of a externalMetric and updates it. Returns the server's representation of the externalMetric, and an error, if there is any. -func (c *FakeExternalMetrics) Update(externalMetric *v1alpha1.ExternalMetric) (result *v1alpha1.ExternalMetric, err error) { - obj, err := c.Fake. - Invokes(testing.NewUpdateAction(externalmetricsResource, c.ns, externalMetric), &v1alpha1.ExternalMetric{}) - - if obj == nil { - return nil, err - } - return obj.(*v1alpha1.ExternalMetric), err -} - -// Delete takes name of the externalMetric and deletes it. Returns an error if one occurs. -func (c *FakeExternalMetrics) Delete(name string, options *v1.DeleteOptions) error { - _, err := c.Fake. - Invokes(testing.NewDeleteAction(externalmetricsResource, c.ns, name), &v1alpha1.ExternalMetric{}) - - return err -} - -// DeleteCollection deletes a collection of objects. -func (c *FakeExternalMetrics) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - action := testing.NewDeleteCollectionAction(externalmetricsResource, c.ns, listOptions) - - _, err := c.Fake.Invokes(action, &v1alpha1.ExternalMetricList{}) - return err -} diff --git a/pkg/client/clientset/versioned/typed/metrics/v1alpha1/fake/fake_metrics_client.go b/pkg/client/clientset/versioned/typed/metrics/v1alpha1/fake/fake_metrics_client.go deleted file mode 100644 index 42aa3b17..00000000 --- a/pkg/client/clientset/versioned/typed/metrics/v1alpha1/fake/fake_metrics_client.go +++ /dev/null @@ -1,44 +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 client-gen. DO NOT EDIT. - -package fake - -import ( - v1alpha1 "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned/typed/metrics/v1alpha1" - rest "k8s.io/client-go/rest" - testing "k8s.io/client-go/testing" -) - -type FakeAzureV1alpha1 struct { - *testing.Fake -} - -func (c *FakeAzureV1alpha1) CustomMetrics(namespace string) v1alpha1.CustomMetricInterface { - return &FakeCustomMetrics{c, namespace} -} - -func (c *FakeAzureV1alpha1) ExternalMetrics(namespace string) v1alpha1.ExternalMetricInterface { - return &FakeExternalMetrics{c, namespace} -} - -// RESTClient returns a RESTClient that is used to communicate -// with API server by this client implementation. -func (c *FakeAzureV1alpha1) RESTClient() rest.Interface { - var ret *rest.RESTClient - return ret -} diff --git a/pkg/client/clientset/versioned/typed/metrics/v1alpha1/generated_expansion.go b/pkg/client/clientset/versioned/typed/metrics/v1alpha1/generated_expansion.go deleted file mode 100644 index 9ea1049c..00000000 --- a/pkg/client/clientset/versioned/typed/metrics/v1alpha1/generated_expansion.go +++ /dev/null @@ -1,23 +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 client-gen. DO NOT EDIT. - -package v1alpha1 - -type CustomMetricExpansion interface{} - -type ExternalMetricExpansion interface{} diff --git a/pkg/client/clientset/versioned/typed/metrics/v1alpha1/metrics_client.go b/pkg/client/clientset/versioned/typed/metrics/v1alpha1/metrics_client.go deleted file mode 100644 index 69b05ed9..00000000 --- a/pkg/client/clientset/versioned/typed/metrics/v1alpha1/metrics_client.go +++ /dev/null @@ -1,95 +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 client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha1" - "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned/scheme" - serializer "k8s.io/apimachinery/pkg/runtime/serializer" - rest "k8s.io/client-go/rest" -) - -type AzureV1alpha1Interface interface { - RESTClient() rest.Interface - CustomMetricsGetter - ExternalMetricsGetter -} - -// AzureV1alpha1Client is used to interact with features provided by the azure.com group. -type AzureV1alpha1Client struct { - restClient rest.Interface -} - -func (c *AzureV1alpha1Client) CustomMetrics(namespace string) CustomMetricInterface { - return newCustomMetrics(c, namespace) -} - -func (c *AzureV1alpha1Client) ExternalMetrics(namespace string) ExternalMetricInterface { - return newExternalMetrics(c, namespace) -} - -// NewForConfig creates a new AzureV1alpha1Client for the given config. -func NewForConfig(c *rest.Config) (*AzureV1alpha1Client, error) { - config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } - client, err := rest.RESTClientFor(&config) - if err != nil { - return nil, err - } - return &AzureV1alpha1Client{client}, nil -} - -// NewForConfigOrDie creates a new AzureV1alpha1Client for the given config and -// panics if there is an error in the config. -func NewForConfigOrDie(c *rest.Config) *AzureV1alpha1Client { - client, err := NewForConfig(c) - if err != nil { - panic(err) - } - return client -} - -// New creates a new AzureV1alpha1Client for the given RESTClient. -func New(c rest.Interface) *AzureV1alpha1Client { - return &AzureV1alpha1Client{c} -} - -func setConfigDefaults(config *rest.Config) error { - gv := v1alpha1.SchemeGroupVersion - config.GroupVersion = &gv - config.APIPath = "/apis" - config.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs} - - if config.UserAgent == "" { - config.UserAgent = rest.DefaultKubernetesUserAgent() - } - - return nil -} - -// RESTClient returns a RESTClient that is used to communicate -// with API server by this client implementation. -func (c *AzureV1alpha1Client) RESTClient() rest.Interface { - if c == nil { - return nil - } - return c.restClient -} diff --git a/pkg/client/informers/externalversions/generic.go b/pkg/client/informers/externalversions/generic.go index 67f6ef82..da02727e 100644 --- a/pkg/client/informers/externalversions/generic.go +++ b/pkg/client/informers/externalversions/generic.go @@ -21,7 +21,6 @@ package externalversions import ( "fmt" - v1alpha1 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha1" v1alpha2 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha2" schema "k8s.io/apimachinery/pkg/runtime/schema" cache "k8s.io/client-go/tools/cache" @@ -53,13 +52,7 @@ func (f *genericInformer) Lister() cache.GenericLister { // TODO extend this to unknown resources with a client pool func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) { switch resource { - // Group=azure.com, Version=v1alpha1 - case v1alpha1.SchemeGroupVersion.WithResource("custommetrics"): - return &genericInformer{resource: resource.GroupResource(), informer: f.Azure().V1alpha1().CustomMetrics().Informer()}, nil - case v1alpha1.SchemeGroupVersion.WithResource("externalmetrics"): - return &genericInformer{resource: resource.GroupResource(), informer: f.Azure().V1alpha1().ExternalMetrics().Informer()}, nil - - // Group=azure.com, Version=v1alpha2 + // Group=azure.com, Version=v1alpha2 case v1alpha2.SchemeGroupVersion.WithResource("custommetrics"): return &genericInformer{resource: resource.GroupResource(), informer: f.Azure().V1alpha2().CustomMetrics().Informer()}, nil case v1alpha2.SchemeGroupVersion.WithResource("externalmetrics"): diff --git a/pkg/client/informers/externalversions/metrics/interface.go b/pkg/client/informers/externalversions/metrics/interface.go index 2ed58570..ebd59872 100644 --- a/pkg/client/informers/externalversions/metrics/interface.go +++ b/pkg/client/informers/externalversions/metrics/interface.go @@ -20,14 +20,11 @@ package azure import ( internalinterfaces "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/informers/externalversions/internalinterfaces" - v1alpha1 "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/informers/externalversions/metrics/v1alpha1" v1alpha2 "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/informers/externalversions/metrics/v1alpha2" ) // Interface provides access to each of this group's versions. type Interface interface { - // V1alpha1 provides access to shared informers for resources in V1alpha1. - V1alpha1() v1alpha1.Interface // V1alpha2 provides access to shared informers for resources in V1alpha2. V1alpha2() v1alpha2.Interface } @@ -43,11 +40,6 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList return &group{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } -// V1alpha1 returns a new v1alpha1.Interface. -func (g *group) V1alpha1() v1alpha1.Interface { - return v1alpha1.New(g.factory, g.namespace, g.tweakListOptions) -} - // V1alpha2 returns a new v1alpha2.Interface. func (g *group) V1alpha2() v1alpha2.Interface { return v1alpha2.New(g.factory, g.namespace, g.tweakListOptions) diff --git a/pkg/client/informers/externalversions/metrics/v1alpha1/custommetric.go b/pkg/client/informers/externalversions/metrics/v1alpha1/custommetric.go deleted file mode 100644 index f6362b51..00000000 --- a/pkg/client/informers/externalversions/metrics/v1alpha1/custommetric.go +++ /dev/null @@ -1,89 +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 informer-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - time "time" - - metricsv1alpha1 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha1" - versioned "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned" - internalinterfaces "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/informers/externalversions/internalinterfaces" - v1alpha1 "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/listers/metrics/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// CustomMetricInformer provides access to a shared informer and lister for -// CustomMetrics. -type CustomMetricInformer interface { - Informer() cache.SharedIndexInformer - Lister() v1alpha1.CustomMetricLister -} - -type customMetricInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc - namespace string -} - -// NewCustomMetricInformer constructs a new informer for CustomMetric type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewCustomMetricInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredCustomMetricInformer(client, namespace, resyncPeriod, indexers, nil) -} - -// NewFilteredCustomMetricInformer constructs a new informer for CustomMetric type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredCustomMetricInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - &cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.AzureV1alpha1().CustomMetrics(namespace).List(options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.AzureV1alpha1().CustomMetrics(namespace).Watch(options) - }, - }, - &metricsv1alpha1.CustomMetric{}, - resyncPeriod, - indexers, - ) -} - -func (f *customMetricInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredCustomMetricInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *customMetricInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&metricsv1alpha1.CustomMetric{}, f.defaultInformer) -} - -func (f *customMetricInformer) Lister() v1alpha1.CustomMetricLister { - return v1alpha1.NewCustomMetricLister(f.Informer().GetIndexer()) -} diff --git a/pkg/client/informers/externalversions/metrics/v1alpha1/externalmetric.go b/pkg/client/informers/externalversions/metrics/v1alpha1/externalmetric.go deleted file mode 100644 index 56de296a..00000000 --- a/pkg/client/informers/externalversions/metrics/v1alpha1/externalmetric.go +++ /dev/null @@ -1,89 +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 informer-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - time "time" - - metricsv1alpha1 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha1" - versioned "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned" - internalinterfaces "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/informers/externalversions/internalinterfaces" - v1alpha1 "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/listers/metrics/v1alpha1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - watch "k8s.io/apimachinery/pkg/watch" - cache "k8s.io/client-go/tools/cache" -) - -// ExternalMetricInformer provides access to a shared informer and lister for -// ExternalMetrics. -type ExternalMetricInformer interface { - Informer() cache.SharedIndexInformer - Lister() v1alpha1.ExternalMetricLister -} - -type externalMetricInformer struct { - factory internalinterfaces.SharedInformerFactory - tweakListOptions internalinterfaces.TweakListOptionsFunc - namespace string -} - -// NewExternalMetricInformer constructs a new informer for ExternalMetric type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewExternalMetricInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { - return NewFilteredExternalMetricInformer(client, namespace, resyncPeriod, indexers, nil) -} - -// NewFilteredExternalMetricInformer constructs a new informer for ExternalMetric type. -// Always prefer using an informer factory to get a shared informer instead of getting an independent -// one. This reduces memory footprint and number of connections to the server. -func NewFilteredExternalMetricInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { - return cache.NewSharedIndexInformer( - &cache.ListWatch{ - ListFunc: func(options v1.ListOptions) (runtime.Object, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.AzureV1alpha1().ExternalMetrics(namespace).List(options) - }, - WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { - if tweakListOptions != nil { - tweakListOptions(&options) - } - return client.AzureV1alpha1().ExternalMetrics(namespace).Watch(options) - }, - }, - &metricsv1alpha1.ExternalMetric{}, - resyncPeriod, - indexers, - ) -} - -func (f *externalMetricInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { - return NewFilteredExternalMetricInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) -} - -func (f *externalMetricInformer) Informer() cache.SharedIndexInformer { - return f.factory.InformerFor(&metricsv1alpha1.ExternalMetric{}, f.defaultInformer) -} - -func (f *externalMetricInformer) Lister() v1alpha1.ExternalMetricLister { - return v1alpha1.NewExternalMetricLister(f.Informer().GetIndexer()) -} diff --git a/pkg/client/informers/externalversions/metrics/v1alpha1/interface.go b/pkg/client/informers/externalversions/metrics/v1alpha1/interface.go deleted file mode 100644 index b9b69494..00000000 --- a/pkg/client/informers/externalversions/metrics/v1alpha1/interface.go +++ /dev/null @@ -1,52 +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 informer-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - internalinterfaces "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/informers/externalversions/internalinterfaces" -) - -// Interface provides access to all the informers in this group version. -type Interface interface { - // CustomMetrics returns a CustomMetricInformer. - CustomMetrics() CustomMetricInformer - // ExternalMetrics returns a ExternalMetricInformer. - ExternalMetrics() ExternalMetricInformer -} - -type version struct { - factory internalinterfaces.SharedInformerFactory - namespace string - tweakListOptions internalinterfaces.TweakListOptionsFunc -} - -// New returns a new Interface. -func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { - return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} -} - -// CustomMetrics returns a CustomMetricInformer. -func (v *version) CustomMetrics() CustomMetricInformer { - return &customMetricInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} -} - -// ExternalMetrics returns a ExternalMetricInformer. -func (v *version) ExternalMetrics() ExternalMetricInformer { - return &externalMetricInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} -} diff --git a/pkg/client/listers/metrics/v1alpha1/custommetric.go b/pkg/client/listers/metrics/v1alpha1/custommetric.go deleted file mode 100644 index 58810531..00000000 --- a/pkg/client/listers/metrics/v1alpha1/custommetric.go +++ /dev/null @@ -1,94 +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 lister-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" -) - -// CustomMetricLister helps list CustomMetrics. -type CustomMetricLister interface { - // List lists all CustomMetrics in the indexer. - List(selector labels.Selector) (ret []*v1alpha1.CustomMetric, err error) - // CustomMetrics returns an object that can list and get CustomMetrics. - CustomMetrics(namespace string) CustomMetricNamespaceLister - CustomMetricListerExpansion -} - -// customMetricLister implements the CustomMetricLister interface. -type customMetricLister struct { - indexer cache.Indexer -} - -// NewCustomMetricLister returns a new CustomMetricLister. -func NewCustomMetricLister(indexer cache.Indexer) CustomMetricLister { - return &customMetricLister{indexer: indexer} -} - -// List lists all CustomMetrics in the indexer. -func (s *customMetricLister) List(selector labels.Selector) (ret []*v1alpha1.CustomMetric, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.CustomMetric)) - }) - return ret, err -} - -// CustomMetrics returns an object that can list and get CustomMetrics. -func (s *customMetricLister) CustomMetrics(namespace string) CustomMetricNamespaceLister { - return customMetricNamespaceLister{indexer: s.indexer, namespace: namespace} -} - -// CustomMetricNamespaceLister helps list and get CustomMetrics. -type CustomMetricNamespaceLister interface { - // List lists all CustomMetrics in the indexer for a given namespace. - List(selector labels.Selector) (ret []*v1alpha1.CustomMetric, err error) - // Get retrieves the CustomMetric from the indexer for a given namespace and name. - Get(name string) (*v1alpha1.CustomMetric, error) - CustomMetricNamespaceListerExpansion -} - -// customMetricNamespaceLister implements the CustomMetricNamespaceLister -// interface. -type customMetricNamespaceLister struct { - indexer cache.Indexer - namespace string -} - -// List lists all CustomMetrics in the indexer for a given namespace. -func (s customMetricNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.CustomMetric, err error) { - err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.CustomMetric)) - }) - return ret, err -} - -// Get retrieves the CustomMetric from the indexer for a given namespace and name. -func (s customMetricNamespaceLister) Get(name string) (*v1alpha1.CustomMetric, error) { - obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("custommetric"), name) - } - return obj.(*v1alpha1.CustomMetric), nil -} diff --git a/pkg/client/listers/metrics/v1alpha1/expansion_generated.go b/pkg/client/listers/metrics/v1alpha1/expansion_generated.go deleted file mode 100644 index 132ff582..00000000 --- a/pkg/client/listers/metrics/v1alpha1/expansion_generated.go +++ /dev/null @@ -1,35 +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 lister-gen. DO NOT EDIT. - -package v1alpha1 - -// CustomMetricListerExpansion allows custom methods to be added to -// CustomMetricLister. -type CustomMetricListerExpansion interface{} - -// CustomMetricNamespaceListerExpansion allows custom methods to be added to -// CustomMetricNamespaceLister. -type CustomMetricNamespaceListerExpansion interface{} - -// ExternalMetricListerExpansion allows custom methods to be added to -// ExternalMetricLister. -type ExternalMetricListerExpansion interface{} - -// ExternalMetricNamespaceListerExpansion allows custom methods to be added to -// ExternalMetricNamespaceLister. -type ExternalMetricNamespaceListerExpansion interface{} diff --git a/pkg/client/listers/metrics/v1alpha1/externalmetric.go b/pkg/client/listers/metrics/v1alpha1/externalmetric.go deleted file mode 100644 index 3c1ccc7a..00000000 --- a/pkg/client/listers/metrics/v1alpha1/externalmetric.go +++ /dev/null @@ -1,94 +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 lister-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1alpha1 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha1" - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/client-go/tools/cache" -) - -// ExternalMetricLister helps list ExternalMetrics. -type ExternalMetricLister interface { - // List lists all ExternalMetrics in the indexer. - List(selector labels.Selector) (ret []*v1alpha1.ExternalMetric, err error) - // ExternalMetrics returns an object that can list and get ExternalMetrics. - ExternalMetrics(namespace string) ExternalMetricNamespaceLister - ExternalMetricListerExpansion -} - -// externalMetricLister implements the ExternalMetricLister interface. -type externalMetricLister struct { - indexer cache.Indexer -} - -// NewExternalMetricLister returns a new ExternalMetricLister. -func NewExternalMetricLister(indexer cache.Indexer) ExternalMetricLister { - return &externalMetricLister{indexer: indexer} -} - -// List lists all ExternalMetrics in the indexer. -func (s *externalMetricLister) List(selector labels.Selector) (ret []*v1alpha1.ExternalMetric, err error) { - err = cache.ListAll(s.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.ExternalMetric)) - }) - return ret, err -} - -// ExternalMetrics returns an object that can list and get ExternalMetrics. -func (s *externalMetricLister) ExternalMetrics(namespace string) ExternalMetricNamespaceLister { - return externalMetricNamespaceLister{indexer: s.indexer, namespace: namespace} -} - -// ExternalMetricNamespaceLister helps list and get ExternalMetrics. -type ExternalMetricNamespaceLister interface { - // List lists all ExternalMetrics in the indexer for a given namespace. - List(selector labels.Selector) (ret []*v1alpha1.ExternalMetric, err error) - // Get retrieves the ExternalMetric from the indexer for a given namespace and name. - Get(name string) (*v1alpha1.ExternalMetric, error) - ExternalMetricNamespaceListerExpansion -} - -// externalMetricNamespaceLister implements the ExternalMetricNamespaceLister -// interface. -type externalMetricNamespaceLister struct { - indexer cache.Indexer - namespace string -} - -// List lists all ExternalMetrics in the indexer for a given namespace. -func (s externalMetricNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.ExternalMetric, err error) { - err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1alpha1.ExternalMetric)) - }) - return ret, err -} - -// Get retrieves the ExternalMetric from the indexer for a given namespace and name. -func (s externalMetricNamespaceLister) Get(name string) (*v1alpha1.ExternalMetric, error) { - obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(v1alpha1.Resource("externalmetric"), name) - } - return obj.(*v1alpha1.ExternalMetric), nil -} diff --git a/pkg/controller/controller.go b/pkg/controller/controller.go index 54cc36dc..3ba59255 100644 --- a/pkg/controller/controller.go +++ b/pkg/controller/controller.go @@ -4,7 +4,7 @@ import ( "fmt" "time" - "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha1" + "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha2" "github.com/golang/glog" "k8s.io/apimachinery/pkg/util/runtime" @@ -13,7 +13,7 @@ import ( "k8s.io/client-go/tools/cache" "k8s.io/client-go/util/workqueue" - informers "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/informers/externalversions/metrics/v1alpha1" + informers "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/informers/externalversions/metrics/v1alpha2" ) // Controller will do the work of syncing the external metrics the metric adapter knows about. @@ -177,9 +177,9 @@ func getKind(obj interface{}) string { // Instead use type to predict Kind which is good enough for our purposes: switch obj.(type) { - case *v1alpha1.ExternalMetric: + case *v1alpha2.ExternalMetric: return "ExternalMetric" - case *v1alpha1.CustomMetric: + case *v1alpha2.CustomMetric: return "CustomMetric" default: glog.Error("No known type of object") diff --git a/pkg/controller/controller_test.go b/pkg/controller/controller_test.go index 53864ba8..c84ef4bc 100644 --- a/pkg/controller/controller_test.go +++ b/pkg/controller/controller_test.go @@ -4,7 +4,7 @@ import ( "errors" "testing" - api "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha1" + api "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha2" "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned/fake" informers "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/informers/externalversions" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -292,7 +292,7 @@ func newController(config controllerConfig) (*Controller, informers.SharedInform fakeClient := fake.NewSimpleClientset(config.store...) i := informers.NewSharedInformerFactory(fakeClient, 0) - c := NewController(i.Azure().V1alpha1().ExternalMetrics(), i.Azure().V1alpha1().CustomMetrics(), config.handler) + c := NewController(i.Azure().V1alpha2().ExternalMetrics(), i.Azure().V1alpha2().CustomMetrics(), config.handler) // override for testing c.externalMetricSynced = config.syncedFunction @@ -308,12 +308,12 @@ func newController(config controllerConfig) (*Controller, informers.SharedInform for _, em := range config.externalMetricsListerCache { // this will force the enqueuer to reload - i.Azure().V1alpha1().ExternalMetrics().Informer().GetIndexer().Add(em) + i.Azure().V1alpha2().ExternalMetrics().Informer().GetIndexer().Add(em) } for _, cm := range config.customMetricsListerCache { // this will force the enqueuer to reload - i.Azure().V1alpha1().CustomMetrics().Informer().GetIndexer().Add(cm) + i.Azure().V1alpha2().CustomMetrics().Informer().GetIndexer().Add(cm) } return c, i diff --git a/pkg/controller/handler.go b/pkg/controller/handler.go index 5ee9dddc..e1cbcf70 100644 --- a/pkg/controller/handler.go +++ b/pkg/controller/handler.go @@ -5,7 +5,7 @@ import ( "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/appinsights" "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/external_metrics" - listers "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/listers/metrics/v1alpha1" + listers "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/listers/metrics/v1alpha2" "github.com/Azure/azure-k8s-metrics-adapter/pkg/metriccache" "github.com/golang/glog" "k8s.io/apimachinery/pkg/api/errors" @@ -102,6 +102,10 @@ func (h *Handler) handleExternalMetric(ns, name string, queueItem namespacedQueu MetricName: externalMetricInfo.Spec.MetricConfig.MetricName, Filter: externalMetricInfo.Spec.MetricConfig.Filter, Aggregation: externalMetricInfo.Spec.MetricConfig.Aggregation, + Topic: externalMetricInfo.Spec.AzureConfig.ServiceBusTopic, + Type: externalMetricInfo.Spec.Type, + Namespace: externalMetricInfo.Spec.AzureConfig.ServiceBusNamespace, + Subscription: externalMetricInfo.Spec.AzureConfig.ServiceBusSubscription, } glog.V(2).Infof("adding to cache item '%s' in namespace '%s'", name, ns) diff --git a/pkg/controller/handler_test.go b/pkg/controller/handler_test.go index f5ba1efc..4c2d8450 100644 --- a/pkg/controller/handler_test.go +++ b/pkg/controller/handler_test.go @@ -4,7 +4,7 @@ import ( "fmt" "testing" - api "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha1" + api "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha2" "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/appinsights" "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/external_metrics" "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned/fake" @@ -239,15 +239,15 @@ func newHandler(storeObjects []runtime.Object, externalMetricsListerCache []*api fakeClient := fake.NewSimpleClientset(storeObjects...) i := informers.NewSharedInformerFactory(fakeClient, 0) - externalMetricLister := i.Azure().V1alpha1().ExternalMetrics().Lister() - customMetricLister := i.Azure().V1alpha1().CustomMetrics().Lister() + externalMetricLister := i.Azure().V1alpha2().ExternalMetrics().Lister() + customMetricLister := i.Azure().V1alpha2().CustomMetrics().Lister() for _, em := range externalMetricsListerCache { - i.Azure().V1alpha1().ExternalMetrics().Informer().GetIndexer().Add(em) + i.Azure().V1alpha2().ExternalMetrics().Informer().GetIndexer().Add(em) } for _, cm := range customMetricsListerCache { - i.Azure().V1alpha1().CustomMetrics().Informer().GetIndexer().Add(cm) + i.Azure().V1alpha2().CustomMetrics().Informer().GetIndexer().Add(cm) } metriccache := metriccache.NewMetricCache() diff --git a/samples/request-per-second/deploy/custom-metric.yaml b/samples/request-per-second/deploy/custom-metric.yaml index 882aaf28..a15bed30 100644 --- a/samples/request-per-second/deploy/custom-metric.yaml +++ b/samples/request-per-second/deploy/custom-metric.yaml @@ -1,4 +1,4 @@ -apiVersion: azure.com/v1alpha1 +apiVersion: azure.com/V1alpha2 kind: CustomMetric metadata: name: rps diff --git a/samples/resources/custommetric-example.yaml b/samples/resources/custommetric-examples/custommetric-example.yaml similarity index 86% rename from samples/resources/custommetric-example.yaml rename to samples/resources/custommetric-examples/custommetric-example.yaml index 9ff1c1ee..74fcde2d 100644 --- a/samples/resources/custommetric-example.yaml +++ b/samples/resources/custommetric-examples/custommetric-example.yaml @@ -1,4 +1,4 @@ -apiVersion: azure.com/v1alpha1 +apiVersion: azure.com/V1alpha2 kind: CustomMetric metadata: name: example-custom-metric-ai diff --git a/samples/resources/externalmetric-example.yaml b/samples/resources/externalmetric-examples/azuremonitor-example.yaml similarity index 78% rename from samples/resources/externalmetric-example.yaml rename to samples/resources/externalmetric-examples/azuremonitor-example.yaml index 9bb98055..8e6bf4c8 100755 --- a/samples/resources/externalmetric-example.yaml +++ b/samples/resources/externalmetric-examples/azuremonitor-example.yaml @@ -1,11 +1,12 @@ -apiVersion: azure.com/v1alpha1 +apiVersion: azure.com/v1alpha2 kind: ExternalMetric metadata: name: example-external-metric-sb spec: + type: monitor azure: resourceGroup: sb-external-example - resourceName: sb-external-ns + resourceName: sb-external-ns-js resourceProviderNamespace: Microsoft.ServiceBus resourceType: namespaces metric: diff --git a/samples/resources/externalmetric-examples/servicebussubscription-example.yaml b/samples/resources/externalmetric-examples/servicebussubscription-example.yaml new file mode 100644 index 00000000..11d74816 --- /dev/null +++ b/samples/resources/externalmetric-examples/servicebussubscription-example.yaml @@ -0,0 +1,14 @@ +apiVersion: azure.com/v1alpha2 +kind: ExternalMetric +metadata: + name: example-external-metric-service-bus-subscription +spec: + type: servicebussubscription + azure: + resourceGroup: sb-external-example + serviceBusNamespace: sb-external-ns-js + serviceBusTopic: example-topic + serviceBusSubscription: example-sub + metric: + # This would default to activeMessageCount, but could be updated to one of the counts from /~https://github.com/Azure/azure-sdk-for-go/blob/master/services/servicebus/mgmt/2017-04-01/servicebus/models.go#L1116 + metricName: activeMessageCount \ No newline at end of file diff --git a/samples/servicebus-queue/deploy/externalmetric.yaml b/samples/servicebus-queue/deploy/externalmetric.yaml index 0e64b910..28d425e7 100755 --- a/samples/servicebus-queue/deploy/externalmetric.yaml +++ b/samples/servicebus-queue/deploy/externalmetric.yaml @@ -1,4 +1,4 @@ -apiVersion: azure.com/v1alpha1 +apiVersion: azure.com/V1alpha2 kind: ExternalMetric metadata: name: queuemessages From f6a129ced5b7064b46c1a01038a9f6e4277d62bd Mon Sep 17 00:00:00 2001 From: James Sturtevant Date: Fri, 1 Feb 2019 15:21:30 -0800 Subject: [PATCH 12/23] fix samples --- samples/request-per-second/deploy/custom-metric.yaml | 2 +- .../externalmetric-examples/azuremonitor-example.yaml | 2 +- .../servicebussubscription-example.yaml | 2 +- samples/servicebus-queue/deploy/externalmetric.yaml | 3 ++- 4 files changed, 5 insertions(+), 4 deletions(-) diff --git a/samples/request-per-second/deploy/custom-metric.yaml b/samples/request-per-second/deploy/custom-metric.yaml index a15bed30..80f63de8 100644 --- a/samples/request-per-second/deploy/custom-metric.yaml +++ b/samples/request-per-second/deploy/custom-metric.yaml @@ -1,4 +1,4 @@ -apiVersion: azure.com/V1alpha2 +apiVersion: azure.com/v1alpha2 kind: CustomMetric metadata: name: rps diff --git a/samples/resources/externalmetric-examples/azuremonitor-example.yaml b/samples/resources/externalmetric-examples/azuremonitor-example.yaml index 8e6bf4c8..abdd3075 100755 --- a/samples/resources/externalmetric-examples/azuremonitor-example.yaml +++ b/samples/resources/externalmetric-examples/azuremonitor-example.yaml @@ -6,7 +6,7 @@ spec: type: monitor azure: resourceGroup: sb-external-example - resourceName: sb-external-ns-js + resourceName: sb-external-ns resourceProviderNamespace: Microsoft.ServiceBus resourceType: namespaces metric: diff --git a/samples/resources/externalmetric-examples/servicebussubscription-example.yaml b/samples/resources/externalmetric-examples/servicebussubscription-example.yaml index 11d74816..663ea87f 100644 --- a/samples/resources/externalmetric-examples/servicebussubscription-example.yaml +++ b/samples/resources/externalmetric-examples/servicebussubscription-example.yaml @@ -6,7 +6,7 @@ spec: type: servicebussubscription azure: resourceGroup: sb-external-example - serviceBusNamespace: sb-external-ns-js + serviceBusNamespace: sb-external-ns serviceBusTopic: example-topic serviceBusSubscription: example-sub metric: diff --git a/samples/servicebus-queue/deploy/externalmetric.yaml b/samples/servicebus-queue/deploy/externalmetric.yaml index 28d425e7..ce8d4b34 100755 --- a/samples/servicebus-queue/deploy/externalmetric.yaml +++ b/samples/servicebus-queue/deploy/externalmetric.yaml @@ -1,8 +1,9 @@ -apiVersion: azure.com/V1alpha2 +apiVersion: azure.com/v1alpha2 kind: ExternalMetric metadata: name: queuemessages spec: + type: monitor azure: resourceGroup: sb-external-example resourceName: sb-external-ns From b0be5a2ab6c0d7369319d71f0308b7fbc17ce20f Mon Sep 17 00:00:00 2001 From: James Sturtevant Date: Fri, 1 Feb 2019 16:03:35 -0800 Subject: [PATCH 13/23] aligned the naming for the metric packages --- main.go | 10 +++++----- .../appinsights.go | 2 +- .../appinsights_test.go | 2 +- .../client.go | 2 +- .../factory.go | 2 +- .../metricrequest.go | 2 +- .../metricrequest_test.go | 2 +- .../monitor_client.go | 2 +- .../monitor_client_test.go | 2 +- .../providers.go | 2 +- .../service_bus_subscription_client.go | 2 +- .../service_bus_subscription_client_test.go | 2 +- pkg/controller/handler.go | 8 ++++---- pkg/controller/handler_test.go | 12 ++++++------ pkg/metriccache/metric_cache.go | 16 ++++++++-------- pkg/provider/provider.go | 10 +++++----- pkg/provider/provider_custom.go | 6 +++--- pkg/provider/provider_custom_test.go | 6 +++--- pkg/provider/provider_external.go | 10 +++++----- pkg/provider/provider_external_test.go | 14 +++++++------- 20 files changed, 57 insertions(+), 57 deletions(-) rename pkg/azure/{appinsights => custommetrics}/appinsights.go (99%) rename pkg/azure/{appinsights => custommetrics}/appinsights_test.go (97%) rename pkg/azure/{external_metrics => externalmetrics}/client.go (87%) rename pkg/azure/{external_metrics => externalmetrics}/factory.go (95%) rename pkg/azure/{external_metrics => externalmetrics}/metricrequest.go (99%) rename pkg/azure/{external_metrics => externalmetrics}/metricrequest_test.go (99%) rename pkg/azure/{external_metrics => externalmetrics}/monitor_client.go (98%) rename pkg/azure/{external_metrics => externalmetrics}/monitor_client_test.go (99%) rename pkg/azure/{external_metrics => externalmetrics}/providers.go (87%) rename pkg/azure/{external_metrics => externalmetrics}/service_bus_subscription_client.go (98%) rename pkg/azure/{external_metrics => externalmetrics}/service_bus_subscription_client_test.go (99%) diff --git a/main.go b/main.go index c0cd1457..1eaed3f7 100755 --- a/main.go +++ b/main.go @@ -11,8 +11,8 @@ import ( "runtime" "time" - "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/appinsights" - "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/external_metrics" + "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/custommetrics" + "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/externalmetrics" "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/instancemetadata" clientset "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned" informers "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/informers/externalversions" @@ -65,13 +65,13 @@ func setupAzureProvider(cmd *basecmd.AdapterBase, metricsCache *metriccache.Metr } defaultSubscriptionID := getDefaultSubscriptionID() - appinsightsClient := appinsights.NewClient() + customMetricsClient := custommetrics.NewClient() - azureExternalClientFactory := azureexternalmetrics.AzureExternalMetricClientFactory{ + azureExternalClientFactory := externalmetrics.AzureExternalMetricClientFactory{ DefaultSubscriptionID: defaultSubscriptionID, } - azureProvider := azureprovider.NewAzureProvider(defaultSubscriptionID, mapper, dynamicClient, appinsightsClient, azureExternalClientFactory, metricsCache) + azureProvider := azureprovider.NewAzureProvider(defaultSubscriptionID, mapper, dynamicClient, customMetricsClient, azureExternalClientFactory, metricsCache) cmd.WithCustomMetrics(azureProvider) cmd.WithExternalMetrics(azureProvider) } diff --git a/pkg/azure/appinsights/appinsights.go b/pkg/azure/custommetrics/appinsights.go similarity index 99% rename from pkg/azure/appinsights/appinsights.go rename to pkg/azure/custommetrics/appinsights.go index 66a5e34b..665e70db 100755 --- a/pkg/azure/appinsights/appinsights.go +++ b/pkg/azure/custommetrics/appinsights.go @@ -1,4 +1,4 @@ -package appinsights +package custommetrics import ( "context" diff --git a/pkg/azure/appinsights/appinsights_test.go b/pkg/azure/custommetrics/appinsights_test.go similarity index 97% rename from pkg/azure/appinsights/appinsights_test.go rename to pkg/azure/custommetrics/appinsights_test.go index 6ddd29fd..6812f08a 100755 --- a/pkg/azure/appinsights/appinsights_test.go +++ b/pkg/azure/custommetrics/appinsights_test.go @@ -1,4 +1,4 @@ -package appinsights +package custommetrics import ( "testing" diff --git a/pkg/azure/external_metrics/client.go b/pkg/azure/externalmetrics/client.go similarity index 87% rename from pkg/azure/external_metrics/client.go rename to pkg/azure/externalmetrics/client.go index d33b3fd0..5e1941e3 100644 --- a/pkg/azure/external_metrics/client.go +++ b/pkg/azure/externalmetrics/client.go @@ -1,4 +1,4 @@ -package azureexternalmetrics +package externalmetrics type AzureExternalMetricResponse struct { Total float64 diff --git a/pkg/azure/external_metrics/factory.go b/pkg/azure/externalmetrics/factory.go similarity index 95% rename from pkg/azure/external_metrics/factory.go rename to pkg/azure/externalmetrics/factory.go index 0dc789b4..a193afa2 100644 --- a/pkg/azure/external_metrics/factory.go +++ b/pkg/azure/externalmetrics/factory.go @@ -1,4 +1,4 @@ -package azureexternalmetrics +package externalmetrics import "fmt" diff --git a/pkg/azure/external_metrics/metricrequest.go b/pkg/azure/externalmetrics/metricrequest.go similarity index 99% rename from pkg/azure/external_metrics/metricrequest.go rename to pkg/azure/externalmetrics/metricrequest.go index b561edd4..702b3fca 100644 --- a/pkg/azure/external_metrics/metricrequest.go +++ b/pkg/azure/externalmetrics/metricrequest.go @@ -1,4 +1,4 @@ -package azureexternalmetrics +package externalmetrics import ( "errors" diff --git a/pkg/azure/external_metrics/metricrequest_test.go b/pkg/azure/externalmetrics/metricrequest_test.go similarity index 99% rename from pkg/azure/external_metrics/metricrequest_test.go rename to pkg/azure/externalmetrics/metricrequest_test.go index 971b9a1f..9da99c78 100644 --- a/pkg/azure/external_metrics/metricrequest_test.go +++ b/pkg/azure/externalmetrics/metricrequest_test.go @@ -1,4 +1,4 @@ -package azureexternalmetrics +package externalmetrics import ( "fmt" diff --git a/pkg/azure/external_metrics/monitor_client.go b/pkg/azure/externalmetrics/monitor_client.go similarity index 98% rename from pkg/azure/external_metrics/monitor_client.go rename to pkg/azure/externalmetrics/monitor_client.go index 8f666510..aade0d40 100644 --- a/pkg/azure/external_metrics/monitor_client.go +++ b/pkg/azure/externalmetrics/monitor_client.go @@ -1,4 +1,4 @@ -package azureexternalmetrics +package externalmetrics import ( "context" diff --git a/pkg/azure/external_metrics/monitor_client_test.go b/pkg/azure/externalmetrics/monitor_client_test.go similarity index 99% rename from pkg/azure/external_metrics/monitor_client_test.go rename to pkg/azure/externalmetrics/monitor_client_test.go index 9e01b05c..9630a298 100644 --- a/pkg/azure/external_metrics/monitor_client_test.go +++ b/pkg/azure/externalmetrics/monitor_client_test.go @@ -1,4 +1,4 @@ -package azureexternalmetrics +package externalmetrics import ( "context" diff --git a/pkg/azure/external_metrics/providers.go b/pkg/azure/externalmetrics/providers.go similarity index 87% rename from pkg/azure/external_metrics/providers.go rename to pkg/azure/externalmetrics/providers.go index 025e300f..a58f7822 100644 --- a/pkg/azure/external_metrics/providers.go +++ b/pkg/azure/externalmetrics/providers.go @@ -1,4 +1,4 @@ -package azureexternalmetrics +package externalmetrics type AzureExternalMetricClientProvider interface { NewClient(defaultSubscriptionID string) diff --git a/pkg/azure/external_metrics/service_bus_subscription_client.go b/pkg/azure/externalmetrics/service_bus_subscription_client.go similarity index 98% rename from pkg/azure/external_metrics/service_bus_subscription_client.go rename to pkg/azure/externalmetrics/service_bus_subscription_client.go index 5a8bb428..8edd54fc 100644 --- a/pkg/azure/external_metrics/service_bus_subscription_client.go +++ b/pkg/azure/externalmetrics/service_bus_subscription_client.go @@ -1,4 +1,4 @@ -package azureexternalmetrics +package externalmetrics import ( "context" diff --git a/pkg/azure/external_metrics/service_bus_subscription_client_test.go b/pkg/azure/externalmetrics/service_bus_subscription_client_test.go similarity index 99% rename from pkg/azure/external_metrics/service_bus_subscription_client_test.go rename to pkg/azure/externalmetrics/service_bus_subscription_client_test.go index a22456c5..c0a35bd0 100644 --- a/pkg/azure/external_metrics/service_bus_subscription_client_test.go +++ b/pkg/azure/externalmetrics/service_bus_subscription_client_test.go @@ -1,4 +1,4 @@ -package azureexternalmetrics +package externalmetrics import ( "context" diff --git a/pkg/controller/handler.go b/pkg/controller/handler.go index e1cbcf70..2e65214e 100644 --- a/pkg/controller/handler.go +++ b/pkg/controller/handler.go @@ -3,8 +3,8 @@ package controller import ( "fmt" - "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/appinsights" - "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/external_metrics" + "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/custommetrics" + "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/externalmetrics" listers "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/listers/metrics/v1alpha2" "github.com/Azure/azure-k8s-metrics-adapter/pkg/metriccache" "github.com/golang/glog" @@ -67,7 +67,7 @@ func (h *Handler) handleCustomMetric(ns, name string, queueItem namespacedQueueI return err } - metric := appinsights.MetricRequest{ + metric := custommetrics.MetricRequest{ MetricName: customMetricInfo.Spec.MetricConfig.MetricName, } @@ -93,7 +93,7 @@ func (h *Handler) handleExternalMetric(ns, name string, queueItem namespacedQueu } // TODO: Map the new fields here for Service Bus - azureMetricRequest := azureexternalmetrics.AzureExternalMetricRequest{ + azureMetricRequest := externalmetrics.AzureExternalMetricRequest{ ResourceGroup: externalMetricInfo.Spec.AzureConfig.ResourceGroup, ResourceName: externalMetricInfo.Spec.AzureConfig.ResourceName, ResourceProviderNamespace: externalMetricInfo.Spec.AzureConfig.ResourceProviderNamespace, diff --git a/pkg/controller/handler_test.go b/pkg/controller/handler_test.go index 4c2d8450..275498a6 100644 --- a/pkg/controller/handler_test.go +++ b/pkg/controller/handler_test.go @@ -5,8 +5,8 @@ import ( "testing" api "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha2" - "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/appinsights" - "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/external_metrics" + "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/custommetrics" + "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/externalmetrics" "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned/fake" informers "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/informers/externalversions" "github.com/Azure/azure-k8s-metrics-adapter/pkg/metriccache" @@ -166,7 +166,7 @@ func TestWhenExternalItemHasBeenDeleted(t *testing.T) { // add the item to the cache then test if it gets deleted queueItem := getExternalKey(externalMetric) - metriccache.Update(queueItem.Key(), azureexternalmetrics.AzureExternalMetricRequest{}) + metriccache.Update(queueItem.Key(), externalmetrics.AzureExternalMetricRequest{}) err := handler.Process(queueItem) @@ -193,7 +193,7 @@ func TestWhenCustomItemHasBeenDeleted(t *testing.T) { // add the item to the cache then test if it gets deleted queueItem := getCustomKey(customMetric) - metriccache.Update(queueItem.Key(), appinsights.MetricRequest{}) + metriccache.Update(queueItem.Key(), custommetrics.MetricRequest{}) err := handler.Process(queueItem) @@ -256,7 +256,7 @@ func newHandler(storeObjects []runtime.Object, externalMetricsListerCache []*api return handler, metriccache } -func validateExternalMetricResult(metricRequest azureexternalmetrics.AzureExternalMetricRequest, externalMetricInfo *api.ExternalMetric, t *testing.T) { +func validateExternalMetricResult(metricRequest externalmetrics.AzureExternalMetricRequest, externalMetricInfo *api.ExternalMetric, t *testing.T) { // Metric Config if metricRequest.MetricName != externalMetricInfo.Spec.MetricConfig.MetricName { @@ -294,7 +294,7 @@ func validateExternalMetricResult(metricRequest azureexternalmetrics.AzureExtern } -func validateCustomMetricResult(metricRequest appinsights.MetricRequest, customMetricInfo *api.CustomMetric, t *testing.T) { +func validateCustomMetricResult(metricRequest custommetrics.MetricRequest, customMetricInfo *api.CustomMetric, t *testing.T) { // Metric Config if metricRequest.MetricName != customMetricInfo.Spec.MetricConfig.MetricName { t.Errorf("metricRequest MetricName = %v, want %v", metricRequest.MetricName, customMetricInfo.Spec.MetricConfig.MetricName) diff --git a/pkg/metriccache/metric_cache.go b/pkg/metriccache/metric_cache.go index 0565ab12..a91fec1b 100644 --- a/pkg/metriccache/metric_cache.go +++ b/pkg/metriccache/metric_cache.go @@ -4,8 +4,8 @@ import ( "fmt" "sync" - "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/appinsights" - "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/external_metrics" + "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/custommetrics" + "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/externalmetrics" "github.com/golang/glog" ) @@ -31,7 +31,7 @@ func (mc *MetricCache) Update(key string, metricRequest interface{}) { } // GetAzureExternalMetricRequest retrieves a metric request from the cache -func (mc *MetricCache) GetAzureExternalMetricRequest(namepace, name string) (azureexternalmetrics.AzureExternalMetricRequest, bool) { +func (mc *MetricCache) GetAzureExternalMetricRequest(namepace, name string) (externalmetrics.AzureExternalMetricRequest, bool) { mc.metricMutext.RLock() defer mc.metricMutext.RUnlock() @@ -39,14 +39,14 @@ func (mc *MetricCache) GetAzureExternalMetricRequest(namepace, name string) (azu metricRequest, exists := mc.metricRequests[key] if !exists { glog.V(2).Infof("metric not found %s", key) - return azureexternalmetrics.AzureExternalMetricRequest{}, false + return externalmetrics.AzureExternalMetricRequest{}, false } - return metricRequest.(azureexternalmetrics.AzureExternalMetricRequest), true + return metricRequest.(externalmetrics.AzureExternalMetricRequest), true } // GetAppInsightsRequest retrieves a metric request from the cache -func (mc *MetricCache) GetAppInsightsRequest(namespace, name string) (appinsights.MetricRequest, bool) { +func (mc *MetricCache) GetAppInsightsRequest(namespace, name string) (custommetrics.MetricRequest, bool) { mc.metricMutext.RLock() defer mc.metricMutext.RUnlock() @@ -54,10 +54,10 @@ func (mc *MetricCache) GetAppInsightsRequest(namespace, name string) (appinsight metricRequest, exists := mc.metricRequests[key] if !exists { glog.V(2).Infof("metric not found %s", key) - return appinsights.MetricRequest{}, false + return custommetrics.MetricRequest{}, false } - return metricRequest.(appinsights.MetricRequest), true + return metricRequest.(custommetrics.MetricRequest), true } // Remove retrieves a metric request from the cache diff --git a/pkg/provider/provider.go b/pkg/provider/provider.go index c8bf909e..c848382f 100755 --- a/pkg/provider/provider.go +++ b/pkg/provider/provider.go @@ -3,8 +3,8 @@ package provider import ( - "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/appinsights" - "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/external_metrics" + "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/custommetrics" + "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/externalmetrics" "github.com/Azure/azure-k8s-metrics-adapter/pkg/metriccache" "github.com/kubernetes-incubator/custom-metrics-apiserver/pkg/provider" apimeta "k8s.io/apimachinery/pkg/api/meta" @@ -12,15 +12,15 @@ import ( ) type AzureProvider struct { - appinsightsClient appinsights.AzureAppInsightsClient + appinsightsClient custommetrics.AzureAppInsightsClient mapper apimeta.RESTMapper kubeClient dynamic.Interface metricCache *metriccache.MetricCache - azureClientFactory azureexternalmetrics.AzureClientFactory + azureClientFactory externalmetrics.AzureClientFactory defaultSubscriptionID string } -func NewAzureProvider(defaultSubscriptionID string, mapper apimeta.RESTMapper, kubeClient dynamic.Interface, appinsightsClient appinsights.AzureAppInsightsClient, azureClientFactory azureexternalmetrics.AzureClientFactory, metricCache *metriccache.MetricCache) provider.MetricsProvider { +func NewAzureProvider(defaultSubscriptionID string, mapper apimeta.RESTMapper, kubeClient dynamic.Interface, appinsightsClient custommetrics.AzureAppInsightsClient, azureClientFactory externalmetrics.AzureClientFactory, metricCache *metriccache.MetricCache) provider.MetricsProvider { return &AzureProvider{ defaultSubscriptionID: defaultSubscriptionID, mapper: mapper, diff --git a/pkg/provider/provider_custom.go b/pkg/provider/provider_custom.go index 4675f4a8..2b7a4acf 100644 --- a/pkg/provider/provider_custom.go +++ b/pkg/provider/provider_custom.go @@ -7,7 +7,7 @@ import ( "strings" "time" - "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/appinsights" + "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/custommetrics" "github.com/golang/glog" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/resource" @@ -99,7 +99,7 @@ func (p *AzureProvider) ListAllMetrics() []provider.CustomMetricInfo { return []provider.CustomMetricInfo{} } -func (p *AzureProvider) getCustomMetricRequest(namespace string, selector labels.Selector, info provider.CustomMetricInfo) appinsights.MetricRequest { +func (p *AzureProvider) getCustomMetricRequest(namespace string, selector labels.Selector, info provider.CustomMetricInfo) custommetrics.MetricRequest { cachedRequest, found := p.metricCache.GetAppInsightsRequest(namespace, info.Metric) if found { @@ -110,7 +110,7 @@ func (p *AzureProvider) getCustomMetricRequest(namespace string, selector labels // through k8s api we convert - to / to get around that convertedMetricName := strings.Replace(info.Metric, "-", "/", -1) glog.V(2).Infof("New call to GetCustomMetric: %s", convertedMetricName) - metricRequestInfo := appinsights.NewMetricRequest(convertedMetricName) + metricRequestInfo := custommetrics.NewMetricRequest(convertedMetricName) return metricRequestInfo } diff --git a/pkg/provider/provider_custom_test.go b/pkg/provider/provider_custom_test.go index cbfd3d0e..3b28ef55 100644 --- a/pkg/provider/provider_custom_test.go +++ b/pkg/provider/provider_custom_test.go @@ -6,7 +6,7 @@ import ( "testing" "time" - "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/appinsights" + "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/custommetrics" "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned/scheme" "github.com/Azure/azure-k8s-metrics-adapter/pkg/metriccache" @@ -133,7 +133,7 @@ func TestReturnsCustomMetricWhenInCache(t *testing.T) { provider, cache := newFakeCustomProvider(fakeClient, storeObjects) - request := appinsights.MetricRequest{ + request := custommetrics.MetricRequest{ MetricName: "cachedName", } @@ -224,6 +224,6 @@ type fakeAppInsightsClient struct { err error } -func (f fakeAppInsightsClient) GetCustomMetric(request appinsights.MetricRequest) (float64, error) { +func (f fakeAppInsightsClient) GetCustomMetric(request custommetrics.MetricRequest) (float64, error) { return f.result, f.err } diff --git a/pkg/provider/provider_external.go b/pkg/provider/provider_external.go index 4fb62ed1..4595bcc8 100644 --- a/pkg/provider/provider_external.go +++ b/pkg/provider/provider_external.go @@ -3,7 +3,7 @@ package provider import ( - "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/external_metrics" + "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/externalmetrics" "github.com/golang/glog" "github.com/kubernetes-incubator/custom-metrics-apiserver/pkg/provider" "k8s.io/apimachinery/pkg/api/errors" @@ -72,20 +72,20 @@ func (p *AzureProvider) ListAllExternalMetrics() []provider.ExternalMetricInfo { return externalMetricsInfo } -func (p *AzureProvider) getMetricRequest(namespace string, metricName string, metricSelector labels.Selector) (azureexternalmetrics.AzureExternalMetricRequest, error) { +func (p *AzureProvider) getMetricRequest(namespace string, metricName string, metricSelector labels.Selector) (externalmetrics.AzureExternalMetricRequest, error) { azMetricRequest, found := p.metricCache.GetAzureExternalMetricRequest(namespace, metricName) if found { - azMetricRequest.Timespan = azureexternalmetrics.TimeSpan() + azMetricRequest.Timespan = externalmetrics.TimeSpan() if azMetricRequest.SubscriptionID == "" { azMetricRequest.SubscriptionID = p.defaultSubscriptionID } return azMetricRequest, nil } - azMetricRequest, err := azureexternalmetrics.ParseAzureMetric(metricSelector, p.defaultSubscriptionID) + azMetricRequest, err := externalmetrics.ParseAzureMetric(metricSelector, p.defaultSubscriptionID) if err != nil { - return azureexternalmetrics.AzureExternalMetricRequest{}, err + return externalmetrics.AzureExternalMetricRequest{}, err } return azMetricRequest, nil diff --git a/pkg/provider/provider_external_test.go b/pkg/provider/provider_external_test.go index ea5c8723..81031261 100644 --- a/pkg/provider/provider_external_test.go +++ b/pkg/provider/provider_external_test.go @@ -4,7 +4,7 @@ import ( "fmt" "testing" - "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/external_metrics" + "github.com/Azure/azure-k8s-metrics-adapter/pkg/azure/externalmetrics" "github.com/Azure/azure-k8s-metrics-adapter/pkg/metriccache" k8sprovider "github.com/kubernetes-incubator/custom-metrics-apiserver/pkg/provider" "k8s.io/apimachinery/pkg/labels" @@ -32,7 +32,7 @@ func createLabelSelector(metricName, subscriptionID string) labels.Selector { func TestFindMetricInCache(t *testing.T) { metricCache := metriccache.NewMetricCache() - request := azureexternalmetrics.AzureExternalMetricRequest{ + request := externalmetrics.AzureExternalMetricRequest{ MetricName: "MessageCount", } metricCache.Update("ExternalMetric/default/metricname", request) @@ -65,7 +65,7 @@ func TestFindMetricInCache(t *testing.T) { func TestFindMetricInCacheUsesOverrideSubscriptionId(t *testing.T) { metricCache := metriccache.NewMetricCache() - request := azureexternalmetrics.AzureExternalMetricRequest{ + request := externalmetrics.AzureExternalMetricRequest{ MetricName: "MessageCount", SubscriptionID: "9876", } @@ -211,20 +211,20 @@ func newProvider(fakeFactory fakeAzureExternalClientFactory) AzureProvider { type fakeAzureExternalClientFactory struct { } -func (f fakeAzureExternalClientFactory) GetAzureExternalMetricClient(clientType string) (client azureexternalmetrics.AzureExternalMetricClient, err error) { +func (f fakeAzureExternalClientFactory) GetAzureExternalMetricClient(clientType string) (client externalmetrics.AzureExternalMetricClient, err error) { fakeClient := fakeAzureMonitorClient{ err: nil, - result: azureexternalmetrics.AzureExternalMetricResponse{Total: 15}, + result: externalmetrics.AzureExternalMetricResponse{Total: 15}, } return fakeClient, nil } type fakeAzureMonitorClient struct { - result azureexternalmetrics.AzureExternalMetricResponse + result externalmetrics.AzureExternalMetricResponse err error } -func (f fakeAzureMonitorClient) GetAzureMetric(azMetricRequest azureexternalmetrics.AzureExternalMetricRequest) (azureexternalmetrics.AzureExternalMetricResponse, error) { +func (f fakeAzureMonitorClient) GetAzureMetric(azMetricRequest externalmetrics.AzureExternalMetricRequest) (externalmetrics.AzureExternalMetricResponse, error) { return f.result, f.err } From 39b535059e52756d48b6e1e100a20d877045a62b Mon Sep 17 00:00:00 2001 From: James Sturtevant Date: Thu, 21 Feb 2019 11:37:44 -0800 Subject: [PATCH 14/23] Set type to azuremonitor to be more explicit --- pkg/azure/externalmetrics/providers.go | 2 +- .../resources/externalmetric-examples/azuremonitor-example.yaml | 2 +- samples/servicebus-queue/deploy/externalmetric.yaml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pkg/azure/externalmetrics/providers.go b/pkg/azure/externalmetrics/providers.go index a58f7822..c37f015c 100644 --- a/pkg/azure/externalmetrics/providers.go +++ b/pkg/azure/externalmetrics/providers.go @@ -5,6 +5,6 @@ type AzureExternalMetricClientProvider interface { } const ( - Monitor string = "monitor" + Monitor string = "azuremonitor" ServiceBusSubscription string = "servicebussubscription" ) diff --git a/samples/resources/externalmetric-examples/azuremonitor-example.yaml b/samples/resources/externalmetric-examples/azuremonitor-example.yaml index abdd3075..b8082f01 100755 --- a/samples/resources/externalmetric-examples/azuremonitor-example.yaml +++ b/samples/resources/externalmetric-examples/azuremonitor-example.yaml @@ -3,7 +3,7 @@ kind: ExternalMetric metadata: name: example-external-metric-sb spec: - type: monitor + type: azuremonitor azure: resourceGroup: sb-external-example resourceName: sb-external-ns diff --git a/samples/servicebus-queue/deploy/externalmetric.yaml b/samples/servicebus-queue/deploy/externalmetric.yaml index ce8d4b34..07af5d86 100755 --- a/samples/servicebus-queue/deploy/externalmetric.yaml +++ b/samples/servicebus-queue/deploy/externalmetric.yaml @@ -3,7 +3,7 @@ kind: ExternalMetric metadata: name: queuemessages spec: - type: monitor + type: azuremonitor azure: resourceGroup: sb-external-example resourceName: sb-external-ns From a64dcdf1ab5263b80d9d65fb850970735f82d08e Mon Sep 17 00:00:00 2001 From: James Sturtevant Date: Fri, 15 Mar 2019 22:36:43 -0700 Subject: [PATCH 15/23] Add e2e tests for service bus topic subs --- .azdevops/image-pipeline.yml | 4 ++ CONTRIBUTING.md | 20 +++++- ...-metrics.sh => configure-queue-metrics.sh} | 0 .../configure-topic-subscriptions-metrics.sh | 20 ++++++ hack/e2e-scripts/deploy-adapter-with-sp.sh | 0 ...ges.sh => gen-and-check-queue-messages.sh} | 19 +----- ...-and-check-topic-subscriptions-messages.sh | 37 +++++++++++ ...{run-consumer.sh => run-queue-consumer.sh} | 6 +- hack/e2e-scripts/run-topic-consumer.sh | 20 ++++++ hack/run-e2e.sh | 16 +++-- samples/servicebus-queue/consumer/main.go | 17 +---- .../deploy/consumer-deployment.yaml | 1 + .../producer/.vscode/launch.json | 20 ------ samples/servicebus-queue/producer/main.go | 13 +++- samples/servicebus-queue/readme.md | 33 +++++----- samples/servicebus-topic/Makefile | 6 ++ samples/servicebus-topic/consumer/main.go | 57 +++++++++++++++++ samples/servicebus-topic/producer/main.go | 63 +++++++++++++++++++ 18 files changed, 277 insertions(+), 75 deletions(-) rename hack/e2e-scripts/{configure-metrics.sh => configure-queue-metrics.sh} (100%) mode change 100644 => 100755 create mode 100755 hack/e2e-scripts/configure-topic-subscriptions-metrics.sh mode change 100644 => 100755 hack/e2e-scripts/deploy-adapter-with-sp.sh rename hack/e2e-scripts/{gen-and-check-messages.sh => gen-and-check-queue-messages.sh} (62%) mode change 100644 => 100755 create mode 100755 hack/e2e-scripts/gen-and-check-topic-subscriptions-messages.sh rename hack/e2e-scripts/{run-consumer.sh => run-queue-consumer.sh} (73%) mode change 100644 => 100755 create mode 100755 hack/e2e-scripts/run-topic-consumer.sh mode change 100644 => 100755 hack/run-e2e.sh delete mode 100644 samples/servicebus-queue/producer/.vscode/launch.json create mode 100644 samples/servicebus-topic/Makefile create mode 100644 samples/servicebus-topic/consumer/main.go create mode 100644 samples/servicebus-topic/producer/main.go diff --git a/.azdevops/image-pipeline.yml b/.azdevops/image-pipeline.yml index 3797ac55..d8670703 100644 --- a/.azdevops/image-pipeline.yml +++ b/.azdevops/image-pipeline.yml @@ -53,18 +53,22 @@ jobs: strategy: matrix: K8s10: + SERVICEBUS_SUBSCRIPTION_NAME: 'externalsub-10' SERVICEBUS_QUEUE_NAME: 'externalq-10' DOCKER_VERSION: '18.06.1~ce~3-0~ubuntu' KUBERNETES_VERSION: '1.10.12' K8s11: + SERVICEBUS_SUBSCRIPTION_NAME: 'externalsub-11' SERVICEBUS_QUEUE_NAME: 'externalq-11' DOCKER_VERSION: '17.03.3~ce-0~ubuntu-xenial' KUBERNETES_VERSION: '1.11.6' K8s12: + SERVICEBUS_SUBSCRIPTION_NAME: 'externalsub-12' SERVICEBUS_QUEUE_NAME: 'externalq-12' DOCKER_VERSION: '18.06.1~ce~3-0~ubuntu' KUBERNETES_VERSION: '1.12.4' K8s13: + SERVICEBUS_SUBSCRIPTION_NAME: 'externalsub-13' SERVICEBUS_QUEUE_NAME: 'externalq-13' DOCKER_VERSION: '18.06.1~ce~3-0~ubuntu' KUBERNETES_VERSION: '1.13.1' diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 87fc0eff..37f59c95 100755 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -76,7 +76,25 @@ To run `make teste2e`, you need the following: #### Environment variables for e2e tests -Edit the [local dev values](local-dev-values.yaml.example) file to create `local-dev-values.yaml`. +Build the project with a custom repository: + +``` +make build +``` + +Edit the [local dev values](local-dev-values.yaml.example) file to create `local-dev-values.yaml`. If using custom image be sure to set the values (`export REGISTRY=` ("" if using DockerHub) +`export IMAGE=azure-k8s-metrics-adapter-testimage`) before building. The `pullPolicy: IfNotPresent` lets you use the local image on your minikube cluster. If you are not using a local cluster you can use `pullPolicy: Always` to use an image that is in a remote repository. + +Example of the `image` setting in the `local-dev-values.yaml` using a custom image: + +``` +image: + repository: metrics-adapter + tag: latest + pullPolicy: IfNotPresent +``` + +Set the following Environment Variables: | Variable name | Description | Optional? | | ------------- | ----------- | --------- | diff --git a/hack/e2e-scripts/configure-metrics.sh b/hack/e2e-scripts/configure-queue-metrics.sh old mode 100644 new mode 100755 similarity index 100% rename from hack/e2e-scripts/configure-metrics.sh rename to hack/e2e-scripts/configure-queue-metrics.sh diff --git a/hack/e2e-scripts/configure-topic-subscriptions-metrics.sh b/hack/e2e-scripts/configure-topic-subscriptions-metrics.sh new file mode 100755 index 00000000..b00ba9ef --- /dev/null +++ b/hack/e2e-scripts/configure-topic-subscriptions-metrics.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +set -o nounset +set -o errexit + +GOPATH="${GOPATH:-$HOME/go}" +SERVICEBUS_TOPIC_NAME="${SERVICEBUS_TOPIC_NAME:-example-topic}" +SERVICEBUS_SUBSCRIPTION_NAME="${SERVICEBUS_SUBSCRIPTION_NAME:-externalsub}" + +echo; echo "Configuring external metric (queuemessages)..." +cd $GOPATH/src/github.com/Azure/azure-k8s-metrics-adapter/samples/resources/externalmetric-examples/ +cp servicebussubscription-example.yaml servicebussubscription-example.yaml.copy + +sed -i 's|sb-external-ns|'${SERVICEBUS_NAMESPACE}'|g' servicebussubscription-example.yaml +sed -i 's|sb-external-example|'${SERVICEBUS_RESOURCE_GROUP}'|g' servicebussubscription-example.yaml +sed -i 's|example-topic|'${SERVICEBUS_TOPIC_NAME}'|g' servicebussubscription-example.yaml +sed -i 's|example-sub|'${SERVICEBUS_SUBSCRIPTION_NAME}'|g' servicebussubscription-example.yaml +kubectl apply -f servicebussubscription-example.yaml + +rm servicebussubscription-example.yaml; mv servicebussubscription-example.yaml.copy servicebussubscription-example.yaml diff --git a/hack/e2e-scripts/deploy-adapter-with-sp.sh b/hack/e2e-scripts/deploy-adapter-with-sp.sh old mode 100644 new mode 100755 diff --git a/hack/e2e-scripts/gen-and-check-messages.sh b/hack/e2e-scripts/gen-and-check-queue-messages.sh old mode 100644 new mode 100755 similarity index 62% rename from hack/e2e-scripts/gen-and-check-messages.sh rename to hack/e2e-scripts/gen-and-check-queue-messages.sh index 9f94c7ec..352f57ab --- a/hack/e2e-scripts/gen-and-check-messages.sh +++ b/hack/e2e-scripts/gen-and-check-queue-messages.sh @@ -8,27 +8,14 @@ SERVICEBUS_QUEUE_NAME="${SERVICEBUS_QUEUE_NAME:-externalq}" cd $GOPATH/src/github.com/Azure/azure-k8s-metrics-adapter/samples/servicebus-queue/ -# Copy original files -cp producer/main.go producer/main.go.copy -cp consumer/main.go consumer/main.go.copy - -echo; echo "Creating random number for producer script..." -NUM=$(( ($RANDOM % 30 ) + 1 )) -sed -i 's|20000|'$(( NUM + 1 ))'|g' producer/main.go - -echo; echo "Replacing queue name in consumer and producer..." -sed -i 's|externalq|'${SERVICEBUS_QUEUE_NAME}'|g' consumer/main.go -sed -i 's|externalq|'${SERVICEBUS_QUEUE_NAME}'|g' producer/main.go - echo; echo "Building producer and consumer..." make -echo; echo "Returning producer and consumer files to original state..." -rm producer/main.go; mv producer/main.go.copy producer/main.go -rm consumer/main.go; mv consumer/main.go.copy consumer/main.go +echo; echo "Creating random number for producer..." +NUM=$(( ($RANDOM % 30 ) + 1 )) echo; echo "Sending $NUM messages..." -./bin/producer 0 > /dev/null +./bin/producer 0 $NUM $SERVICEBUS_QUEUE_NAME> /dev/null echo; echo "Checking metrics endpoint for 4 minutes..." diff --git a/hack/e2e-scripts/gen-and-check-topic-subscriptions-messages.sh b/hack/e2e-scripts/gen-and-check-topic-subscriptions-messages.sh new file mode 100755 index 00000000..1a99edb0 --- /dev/null +++ b/hack/e2e-scripts/gen-and-check-topic-subscriptions-messages.sh @@ -0,0 +1,37 @@ +#!/bin/bash + +set -o nounset +set -o errexit + +GOPATH="${GOPATH:-$HOME/go}" +SERVICEBUS_TOPIC_NAME="${SERVICEBUS_TOPIC_NAME:-example-topic}" +SERVICEBUS_SUBSCRIPTION_NAME="${SERVICEBUS_SUBSCRIPTION_NAME:-externalsub}" + +cd $GOPATH/src/github.com/Azure/azure-k8s-metrics-adapter/samples/servicebus-topic/ + +echo; echo "Building producer and consumer..." +make + +echo; echo "Creating random number for producer script..." +NUM=$(( ($RANDOM % 30 ) + 1 )) + +echo; echo "Sending $NUM messages..." +./bin/producer 0 $NUM $SERVICEBUS_TOPIC_NAME > /dev/null + +echo; echo "Checking metrics endpoint for 4 minutes..." + +MSGCOUNT=$(kubectl get --raw "/apis/external.metrics.k8s.io/v1beta1/namespaces/default/example-external-metric-service-bus-subscription" | jq .items[0].value) +START=`date +%s` + +while [[ ! "$MSGCOUNT" = "\"$NUM\"" ]] && [[ $(( $(date +%s) - 225 )) -lt $START ]]; do + sleep 15 + MSGCOUNT=$(kubectl get --raw "/apis/external.metrics.k8s.io/v1beta1/namespaces/default/example-external-metric-service-bus-subscription" | jq .items[0].value) + echo "Endpoint returned $MSGCOUNT messages" +done + +if [[ ! "$MSGCOUNT" = "\"$NUM\"" ]]; then + echo "Timed out, message count ($MSGCOUNT) not equal to number of messages sent ($NUM)" + exit 1 +else + echo "Message count equal to number of messages sent, metrics adapter working correctly" +fi diff --git a/hack/e2e-scripts/run-consumer.sh b/hack/e2e-scripts/run-queue-consumer.sh old mode 100644 new mode 100755 similarity index 73% rename from hack/e2e-scripts/run-consumer.sh rename to hack/e2e-scripts/run-queue-consumer.sh index 0025ef78..0d03647e --- a/hack/e2e-scripts/run-consumer.sh +++ b/hack/e2e-scripts/run-queue-consumer.sh @@ -3,14 +3,16 @@ set -o nounset GOPATH="${GOPATH:-$HOME/go}" +SERVICEBUS_QUEUE_NAME="${SERVICEBUS_QUEUE_NAME:-externalq}" echo; echo "Running queue consumer to clear queue" cd $GOPATH/src/github.com/Azure/azure-k8s-metrics-adapter/samples/servicebus-queue/ -timeout 30 ./bin/consumer > /dev/null +timeout 30 ./bin/consumer $SERVICEBUS_QUEUE_NAME> /dev/null # Exit status 124 just means timeout completed, which is what we expect if [[ $? = 124 ]]; then echo "Consumer timed out as expected" exit 0 -fi \ No newline at end of file +fi + diff --git a/hack/e2e-scripts/run-topic-consumer.sh b/hack/e2e-scripts/run-topic-consumer.sh new file mode 100755 index 00000000..ca216dc6 --- /dev/null +++ b/hack/e2e-scripts/run-topic-consumer.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +set -o nounset + +GOPATH="${GOPATH:-$HOME/go}" + +SERVICEBUS_TOPIC_NAME="${SERVICEBUS_TOPIC_NAME:-example-topic}" +SERVICEBUS_SUBSCRIPTION_NAME="${SERVICEBUS_SUBSCRIPTION_NAME:-externalsub}" + +echo; echo "Running queue consumer to clear queue" +cd $GOPATH/src/github.com/Azure/azure-k8s-metrics-adapter/samples/servicebus-topic/ + +timeout 30 ./bin/consumer $SERVICEBUS_TOPIC_NAME $SERVICEBUS_SUBSCRIPTION_NAME> /dev/null + +# Exit status 124 just means timeout completed, which is what we expect +if [[ $? = 124 ]]; then + echo "Consumer timed out as expected" + exit 0 +fi + diff --git a/hack/run-e2e.sh b/hack/run-e2e.sh old mode 100644 new mode 100755 index 5e714040..8fe6af9f --- a/hack/run-e2e.sh +++ b/hack/run-e2e.sh @@ -34,17 +34,25 @@ chmod +x *.sh ./deploy-adapter-with-sp.sh if [[ $? = 0 ]]; then - ./configure-metrics.sh + echo "Testing Queue (Azure Monitor) metrics" + ./configure-queue-metrics.sh + ./gen-and-check-queue-messages.sh + if [[ $? = 0 ]]; + then echo $DIVIDER; echo "PASS"; echo $DIVIDER + else echo $DIVIDER; echo "FAIL"; echo $DIVIDER; + fi - echo "Testing deployment" + ./run-queue-consumer.sh - ./gen-and-check-messages.sh + echo "Testing Topic Subscriptions metrics" + ./configure-topic-subscriptions-metrics.sh + ./gen-and-check-topic-subscriptions-messages.sh if [[ $? = 0 ]]; then echo $DIVIDER; echo "PASS"; echo $DIVIDER else echo $DIVIDER; echo "FAIL"; echo $DIVIDER; fi - ./run-consumer.sh + ./run-topic-consumer.sh fi echo "Removing adapter deployment" diff --git a/samples/servicebus-queue/consumer/main.go b/samples/servicebus-queue/consumer/main.go index 5601522e..3fcc4bfa 100644 --- a/samples/servicebus-queue/consumer/main.go +++ b/samples/servicebus-queue/consumer/main.go @@ -5,12 +5,13 @@ import ( "fmt" "os" "os/signal" - "time" "github.com/Azure/azure-service-bus-go" ) func main() { + queueName := os.Args[1] + connStr := os.Getenv("SERVICEBUS_CONNECTION_STRING") ns, err := servicebus.NewNamespace(servicebus.NamespaceWithConnectionString(connStr)) if err != nil { @@ -18,9 +19,6 @@ func main() { panic(err) } - queueName := "externalq" - qm := ns.NewQueueManager() - fmt.Println("connecting to queue: ", queueName) q, err := ns.NewQueue(queueName) if err != nil { @@ -31,22 +29,13 @@ func main() { fmt.Println("setting up listener") var messageHandler servicebus.HandlerFunc = func(ctx context.Context, msg *servicebus.Message) error { fmt.Println("received message: ", string(msg.Data)) - - ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) - defer cancel() - - qe, err := qm.Get(ctx, queueName) - if err != nil { - fmt.Println("create manager created error: ", err) - } - fmt.Println("number message left: ", *qe.MessageCount) return msg.Complete(ctx) } err = q.Receive(context.Background(), messageHandler) if err != nil { // handle queue listener creation err - fmt.Println("listener: ", err) + fmt.Println("listener error: ", err) } fmt.Println("listening...") diff --git a/samples/servicebus-queue/deploy/consumer-deployment.yaml b/samples/servicebus-queue/deploy/consumer-deployment.yaml index d640e845..df65a18c 100644 --- a/samples/servicebus-queue/deploy/consumer-deployment.yaml +++ b/samples/servicebus-queue/deploy/consumer-deployment.yaml @@ -14,6 +14,7 @@ spec: containers: - name: consumer image: jsturtevant/queue-consumer-external-metric + args: ["externalq"] env: - name: SERVICEBUS_CONNECTION_STRING valueFrom: diff --git a/samples/servicebus-queue/producer/.vscode/launch.json b/samples/servicebus-queue/producer/.vscode/launch.json deleted file mode 100644 index 7f21ad7c..00000000 --- a/samples/servicebus-queue/producer/.vscode/launch.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - // Use IntelliSense to learn about possible attributes. - // Hover to view descriptions of existing attributes. - // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 - "version": "0.2.0", - "configurations": [ - { - "name": "Launch Package", - "type": "go", - "request": "launch", - "mode": "debug", - "program": "${workspaceRoot}", - "env": { - "SERVICEBUS_CONNECTION_STRING": "Endpoint=sb://sb-external-ns.servicebus.windows.net/;SharedAccessKeyName=demorule;SharedAccessKey=j1Bd4RKOKvKBw8ryjc593Jby1T+YwrTcetn7paZDsYU=" - }, - "args": ["500"], - "showLog": true - } - ] -} \ No newline at end of file diff --git a/samples/servicebus-queue/producer/main.go b/samples/servicebus-queue/producer/main.go index 93a14aeb..2a2d6003 100644 --- a/samples/servicebus-queue/producer/main.go +++ b/samples/servicebus-queue/producer/main.go @@ -19,14 +19,21 @@ func main() { return } + messagesToSendArg := os.Args[2] + messagesCount, err := strconv.Atoi(messagesToSendArg) + if err != nil { + fmt.Println("Please provide number of messages") + return + } + + queueName := os.Args[3] + connStr := os.Getenv("SERVICEBUS_CONNECTION_STRING") ns, err := servicebus.NewNamespace(servicebus.NamespaceWithConnectionString(connStr)) if err != nil { fmt.Println("namespace: ", err) } - // Initialize and create a Service Bus Queue named helloworld if it doesn't exist - queueName := "externalq" fmt.Println("connecting to queue: ", queueName) q, err := ns.NewQueue(queueName) if err != nil { @@ -42,7 +49,7 @@ func main() { os.Exit(1) }() - for i := 1; i < 20000; i++ { + for i := 1; i <= messagesCount; i++ { fmt.Println("sending message ", i) err = q.Send(context.Background(), servicebus.NewMessageFromString("the answer is 42")) if err != nil { diff --git a/samples/servicebus-queue/readme.md b/samples/servicebus-queue/readme.md index ac09105c..be28d34a 100755 --- a/samples/servicebus-queue/readme.md +++ b/samples/servicebus-queue/readme.md @@ -3,18 +3,19 @@ This is an example of how to scale using Service Bus Queue as an external metric. - [Service Bus Queue External Metric Scaling](#service-bus-queue-external-metric-scaling) - - [Walkthrough](#walkthrough) - - [Setup Service Bus](#setup-service-bus) - - [Setup AKS Cluster](#setup-aks-cluster) - - [Enable Access to Azure Resources](#enable-access-to-azure-resources) - - [Start the producer](#start-the-producer) - - [Configure Secret for consumer pod](#configure-secret-for-consumer-pod) - - [Deploy Consumer](#deploy-consumer) - - [Set up Azure Metrics Adapter](#set-up-azure-metrics-adapter) - - [Deploy the adapter](#deploy-the-adapter) - - [Deploy the HPA](#deploy-the-hpa) - - [Scale!](#scale) - - [Clean up](#clean-up) + - [Walkthrough](#walkthrough) + - [Setup Service Bus](#setup-service-bus) + - [Setup AKS Cluster](#setup-aks-cluster) + - [Enable Access to Azure Resources](#enable-access-to-azure-resources) + - [Start the producer](#start-the-producer) + - [Configure Secret for consumer pod](#configure-secret-for-consumer-pod) + - [Deploy Consumer](#deploy-consumer) + - [Set up Azure Metrics Adapter](#set-up-azure-metrics-adapter) + - [Deploy the adapter](#deploy-the-adapter) + - [Configure Metric Adapter with metrics](#configure-metric-adapter-with-metrics) + - [Deploy the HPA](#deploy-the-hpa) + - [Scale!](#scale) + - [Clean up](#clean-up) ## Walkthrough @@ -74,7 +75,8 @@ make Run the producer to create a few queue items, then hit `ctl-c` after a few message have been sent to stop it: ``` -./bin/producer 500 +# 0 delay in sending messages, send 5 messages to queue 'externalq' +./bin/producer 0 5 externalq ``` Check the queue has values: @@ -195,10 +197,11 @@ kubectl get --raw "/apis/external.metrics.k8s.io/v1beta1/namespaces/default/que ## Scale! -Put some load on the queue. Note this will add 20,000 message then exit. +Put some load on the queue. Note this will add 5,000 message then exit. ``` -./bin/producer 0 +# 0 delay in sending messages, send 5000 messages to queue 'externalq' +./bin/producer 0 5000 externalq ``` Now check your queue is loaded: diff --git a/samples/servicebus-topic/Makefile b/samples/servicebus-topic/Makefile new file mode 100644 index 00000000..2fd1a275 --- /dev/null +++ b/samples/servicebus-topic/Makefile @@ -0,0 +1,6 @@ +all: clean build ; +build: + go build -o ./bin/producer ./producer/main.go + go build -o ./bin/consumer ./consumer/main.go +clean: + go clean && rm -rf ./bin \ No newline at end of file diff --git a/samples/servicebus-topic/consumer/main.go b/samples/servicebus-topic/consumer/main.go new file mode 100644 index 00000000..f4d18259 --- /dev/null +++ b/samples/servicebus-topic/consumer/main.go @@ -0,0 +1,57 @@ +package main + +import ( + "context" + "fmt" + "os" + "os/signal" + + "github.com/Azure/azure-service-bus-go" +) + +// Printer is a type that prints the message +type Printer struct{} + +// Handle takes the message and prints contents +func (p Printer) Handle(ctx context.Context, msg *servicebus.Message) error { + fmt.Println(string(msg.Data)) + return msg.Complete(ctx) +} + +func main() { + topicName := os.Args[1] + subscriptionName := os.Args[2] + + connStr := os.Getenv("SERVICEBUS_CONNECTION_STRING") + ns, err := servicebus.NewNamespace(servicebus.NamespaceWithConnectionString(connStr)) + if err != nil { + fmt.Println("namespace: ", err) + panic(err) + } + + topic, err := ns.NewTopic(topicName) + if err != nil { + fmt.Println(err) + return + } + + fmt.Printf("setting up subscription reciever %s on topic %s", subscriptionName, topicName) + sub, err := topic.NewSubscription(subscriptionName) + if err != nil { + fmt.Println(err) + return + } + + err = sub.Receive(context.Background(), Printer{}) + if err != nil { + fmt.Println(err) + return + } + + fmt.Println("listening...") + + // Wait for a signal to quit: + signalChan := make(chan os.Signal, 1) + signal.Notify(signalChan, os.Interrupt, os.Kill) + <-signalChan +} diff --git a/samples/servicebus-topic/producer/main.go b/samples/servicebus-topic/producer/main.go new file mode 100644 index 00000000..fbf276cc --- /dev/null +++ b/samples/servicebus-topic/producer/main.go @@ -0,0 +1,63 @@ +package main + +import ( + "context" + "fmt" + "os" + "os/signal" + "strconv" + "time" + + servicebus "github.com/Azure/azure-service-bus-go" +) + +func main() { + speedArg := os.Args[1] + speed, err := strconv.Atoi(speedArg) + if err != nil { + fmt.Println("Please provide speed in milliseconds") + return + } + + messagesToSendArg := os.Args[2] + messagesCount, err := strconv.Atoi(messagesToSendArg) + if err != nil { + fmt.Println("Please provide number of messages") + return + } + + topicName := os.Args[3] + + connStr := os.Getenv("SERVICEBUS_CONNECTION_STRING") + ns, err := servicebus.NewNamespace(servicebus.NamespaceWithConnectionString(connStr)) + if err != nil { + fmt.Println("namespace: ", err) + } + + topic, err := ns.NewTopic(topicName) + if err != nil { + fmt.Println(err) + return + } + + //https: //stackoverflow.com/a/18158859/697126 + signalChan := make(chan os.Signal, 1) + signal.Notify(signalChan, os.Interrupt, os.Kill) + go func() { + <-signalChan + os.Exit(1) + }() + + fmt.Printf("sending %d messages ", messagesCount) + for i := 1; i <= messagesCount; i++ { + fmt.Println("sending message ", i) + err = topic.Send(context.Background(), servicebus.NewMessageFromString("the answer is 42")) + if err != nil { + // handle message send error + fmt.Println("error sending message: ", err) + } + + time.Sleep(time.Duration(speed) * time.Millisecond) + } + +} From 929f241424f8afa2aae3b93fb77a73e5cf1a8e9b Mon Sep 17 00:00:00 2001 From: James Sturtevant Date: Mon, 25 Mar 2019 23:55:51 -0700 Subject: [PATCH 16/23] only gen messages for given subscription --- ...-and-check-topic-subscriptions-messages.sh | 2 +- samples/servicebus-topic/producer/main.go | 52 ++++++++++++++++++- 2 files changed, 51 insertions(+), 3 deletions(-) diff --git a/hack/e2e-scripts/gen-and-check-topic-subscriptions-messages.sh b/hack/e2e-scripts/gen-and-check-topic-subscriptions-messages.sh index 1a99edb0..f0570886 100755 --- a/hack/e2e-scripts/gen-and-check-topic-subscriptions-messages.sh +++ b/hack/e2e-scripts/gen-and-check-topic-subscriptions-messages.sh @@ -16,7 +16,7 @@ echo; echo "Creating random number for producer script..." NUM=$(( ($RANDOM % 30 ) + 1 )) echo; echo "Sending $NUM messages..." -./bin/producer 0 $NUM $SERVICEBUS_TOPIC_NAME > /dev/null +./bin/producer 0 $NUM $SERVICEBUS_TOPIC_NAME $SERVICEBUS_SUBSCRIPTION_NAME > /dev/null echo; echo "Checking metrics endpoint for 4 minutes..." diff --git a/samples/servicebus-topic/producer/main.go b/samples/servicebus-topic/producer/main.go index fbf276cc..1c72ae13 100644 --- a/samples/servicebus-topic/producer/main.go +++ b/samples/servicebus-topic/producer/main.go @@ -27,6 +27,7 @@ func main() { } topicName := os.Args[3] + subscription := os.Args[4] connStr := os.Getenv("SERVICEBUS_CONNECTION_STRING") ns, err := servicebus.NewNamespace(servicebus.NamespaceWithConnectionString(connStr)) @@ -40,6 +41,36 @@ func main() { return } + sm, err := ns.NewSubscriptionManager(topicName) + if err != nil { + fmt.Println(err) + return + } + + ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second) + defer cancel() + + _, err = ensureSubscription(ctx, sm, subscription) + if err != nil { + fmt.Println(err) + return + } + + // remove the default rule, which is the "TrueFilter" that accepts all messages + err = sm.DeleteRule(ctx, subscription, "$Default") + if err != nil { + fmt.Printf("delete default rule err: %s", err) + return + } + + exp := fmt.Sprintf("subscription = '%s'", subscription) + fmt.Printf("filter is %s\n", exp) + _, err = sm.PutRule(ctx, subscription, subscription+"Rule", servicebus.SQLFilter{Expression: exp}) + if err != nil { + fmt.Printf("add rule err: %s", err) + return + } + //https: //stackoverflow.com/a/18158859/697126 signalChan := make(chan os.Signal, 1) signal.Notify(signalChan, os.Interrupt, os.Kill) @@ -50,8 +81,10 @@ func main() { fmt.Printf("sending %d messages ", messagesCount) for i := 1; i <= messagesCount; i++ { - fmt.Println("sending message ", i) - err = topic.Send(context.Background(), servicebus.NewMessageFromString("the answer is 42")) + fmt.Printf("sending message %d to sub %s\n", i, subscription) + m := servicebus.NewMessageFromString("the answer is 42") + m.UserProperties = map[string]interface{}{"subscription": subscription} + err = topic.Send(context.Background(), m) if err != nil { // handle message send error fmt.Println("error sending message: ", err) @@ -61,3 +94,18 @@ func main() { } } + +func ensureSubscription(ctx context.Context, sm *servicebus.SubscriptionManager, name string, opts ...servicebus.SubscriptionManagementOption) (*servicebus.SubscriptionEntity, error) { + subEntity, err := sm.Get(ctx, name) + if err == nil { + _ = sm.Delete(ctx, name) + } + + subEntity, err = sm.Put(ctx, name, opts...) + if err != nil { + fmt.Println(err) + return nil, err + } + + return subEntity, nil +} From c1d305aa79d3929b117891b6d974abfca272c027 Mon Sep 17 00:00:00 2001 From: James Sturtevant Date: Mon, 25 Mar 2019 23:56:26 -0700 Subject: [PATCH 17/23] fail build if any tests fail --- hack/run-e2e.sh | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/hack/run-e2e.sh b/hack/run-e2e.sh index 8fe6af9f..62718c4c 100755 --- a/hack/run-e2e.sh +++ b/hack/run-e2e.sh @@ -32,6 +32,8 @@ echo; echo "Running deployment scripts" cd $GOPATH/src/github.com/Azure/azure-k8s-metrics-adapter/hack/e2e-scripts chmod +x *.sh +TEST_FAILED=0 + ./deploy-adapter-with-sp.sh if [[ $? = 0 ]]; then echo "Testing Queue (Azure Monitor) metrics" @@ -39,7 +41,7 @@ if [[ $? = 0 ]]; then ./gen-and-check-queue-messages.sh if [[ $? = 0 ]]; then echo $DIVIDER; echo "PASS"; echo $DIVIDER - else echo $DIVIDER; echo "FAIL"; echo $DIVIDER; + else echo $DIVIDER; echo "FAIL"; echo $DIVIDER; TEST_FAILED=1; fi ./run-queue-consumer.sh @@ -49,7 +51,7 @@ if [[ $? = 0 ]]; then ./gen-and-check-topic-subscriptions-messages.sh if [[ $? = 0 ]]; then echo $DIVIDER; echo "PASS"; echo $DIVIDER - else echo $DIVIDER; echo "FAIL"; echo $DIVIDER; + else echo $DIVIDER; echo "FAIL"; echo $DIVIDER; TEST_FAILED=1; fi ./run-topic-consumer.sh @@ -57,3 +59,8 @@ fi echo "Removing adapter deployment" helm delete --purge adapter + +if [[ $TEST_FAILED == 1 ]]; then + echo $DIVIDER; echo "FAIL"; echo $DIVIDER; + exit 1 +fi From f6459e4f2c6a6684bdb154a6c75b4c826955f690 Mon Sep 17 00:00:00 2001 From: James Sturtevant Date: Tue, 21 May 2019 10:03:11 -0700 Subject: [PATCH 18/23] note that topic with a subscription is needed --- CONTRIBUTING.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 37f59c95..294022a2 100755 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -73,6 +73,7 @@ To run `make teste2e`, you need the following: * jq (used in parsing responses from the endpoint) * [Kubernetes Metrics Server](/~https://github.com/kubernetes-incubator/metrics-server#deployment) deployed on your cluster (it is deployed by default with most deployments) * An Azure [Service Bus Queue](https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-dotnet-get-started-with-queues) +* An Azure Topic with Subscription #### Environment variables for e2e tests @@ -133,4 +134,4 @@ make dev 2. Then run `git push --follow-tags` 3. Everything is automated after the `git push`. `make version` will bump the version and tag the commit. The Circle CI will recognize the tagged master branch and push to the repository. -> note: you must be on the master branch and it must be clean. \ No newline at end of file +> note: you must be on the master branch and it must be clean. From bdf5e5c7cdb5328b9ed6e029e359d2f6f15ad0d4 Mon Sep 17 00:00:00 2001 From: James Sturtevant Date: Tue, 21 May 2019 10:04:27 -0700 Subject: [PATCH 19/23] add env variables --- CONTRIBUTING.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 294022a2..6c2969a8 100755 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -104,6 +104,8 @@ Set the following Environment Variables: | `SERVICEBUS_NAMESPACE` | Service bus namespace | No | | `SERVICEBUS_QUEUE_NAME` | Name of the service bus queue | Yes, defaults to `externalq` if not set | | `GOPATH` | Golang project directory | Yes, defaults to `$HOME/go` if not set | +| `SERVICEBUS_TOPIC_NAME` | Name of the service bus topic | Yes, defaults to `example-topic` if not set | +| `SERVICEBUS_SUBSCRIPTION_NAME` | Name of the service bus subscription | Yes, defaults to `externalsub` if not set | ## Adding dependencies From 7b8b1920a4c13e9452676423e34faf07ad2a2cf0 Mon Sep 17 00:00:00 2001 From: James Sturtevant Date: Tue, 21 May 2019 10:05:05 -0700 Subject: [PATCH 20/23] Update configure-topic-subscriptions-metrics.sh --- hack/e2e-scripts/configure-topic-subscriptions-metrics.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hack/e2e-scripts/configure-topic-subscriptions-metrics.sh b/hack/e2e-scripts/configure-topic-subscriptions-metrics.sh index b00ba9ef..b45e259b 100755 --- a/hack/e2e-scripts/configure-topic-subscriptions-metrics.sh +++ b/hack/e2e-scripts/configure-topic-subscriptions-metrics.sh @@ -7,7 +7,7 @@ GOPATH="${GOPATH:-$HOME/go}" SERVICEBUS_TOPIC_NAME="${SERVICEBUS_TOPIC_NAME:-example-topic}" SERVICEBUS_SUBSCRIPTION_NAME="${SERVICEBUS_SUBSCRIPTION_NAME:-externalsub}" -echo; echo "Configuring external metric (queuemessages)..." +echo; echo "Configuring external metric (subscriptionmessages)..." cd $GOPATH/src/github.com/Azure/azure-k8s-metrics-adapter/samples/resources/externalmetric-examples/ cp servicebussubscription-example.yaml servicebussubscription-example.yaml.copy From 8c6ba38577792d39e7dfa3033b5eb57546f13151 Mon Sep 17 00:00:00 2001 From: James Sturtevant Date: Tue, 21 May 2019 10:05:55 -0700 Subject: [PATCH 21/23] Update run-topic-consumer.sh --- hack/e2e-scripts/run-topic-consumer.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hack/e2e-scripts/run-topic-consumer.sh b/hack/e2e-scripts/run-topic-consumer.sh index ca216dc6..76aa10d9 100755 --- a/hack/e2e-scripts/run-topic-consumer.sh +++ b/hack/e2e-scripts/run-topic-consumer.sh @@ -7,7 +7,7 @@ GOPATH="${GOPATH:-$HOME/go}" SERVICEBUS_TOPIC_NAME="${SERVICEBUS_TOPIC_NAME:-example-topic}" SERVICEBUS_SUBSCRIPTION_NAME="${SERVICEBUS_SUBSCRIPTION_NAME:-externalsub}" -echo; echo "Running queue consumer to clear queue" +echo; echo "Running consumer to clear topic" cd $GOPATH/src/github.com/Azure/azure-k8s-metrics-adapter/samples/servicebus-topic/ timeout 30 ./bin/consumer $SERVICEBUS_TOPIC_NAME $SERVICEBUS_SUBSCRIPTION_NAME> /dev/null From a33f99ceccf43bc2888bbe49d24291f48324e4c9 Mon Sep 17 00:00:00 2001 From: James Sturtevant Date: Thu, 27 Jun 2019 17:24:24 -0700 Subject: [PATCH 22/23] pin to gen tool to specific version --- Makefile | 1 + hack/codegen-repo-fix.sh | 14 ++++++++++++++ 2 files changed, 15 insertions(+) create mode 100755 hack/codegen-repo-fix.sh diff --git a/Makefile b/Makefile index 8512ecd7..0c695ddd 100755 --- a/Makefile +++ b/Makefile @@ -82,6 +82,7 @@ verify-apis: codegen-get codegen-get: go get -u k8s.io/code-generator/... + hack/codegen-repo-fix.sh # Helm deploy generator helpers verify-deploy: diff --git a/hack/codegen-repo-fix.sh b/hack/codegen-repo-fix.sh new file mode 100755 index 00000000..ea82abb5 --- /dev/null +++ b/hack/codegen-repo-fix.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash + +set -o errexit +set -o nounset +set -o pipefail + +# make sure we have correct version of code generator +cd $GOPATH/src/k8s.io/code-generator/ +git fetch --all +git checkout tags/kubernetes-1.12.9 -b kubernetes-1.12.9 + + + + From 9a93060bd0bf903b5882d100b5207d4ba29df067 Mon Sep 17 00:00:00 2001 From: James Sturtevant Date: Fri, 28 Jun 2019 00:43:47 +0000 Subject: [PATCH 23/23] Fix code gen-issue by pinning --- Gopkg.lock | 233 +++--------------- hack/codegen-repo-fix.sh | 10 +- pkg/client/clientset/versioned/clientset.go | 8 - .../versioned/fake/clientset_generated.go | 5 - .../typed/metrics/v1alpha2/custommetric.go | 17 ++ .../typed/metrics/v1alpha2/externalmetric.go | 17 ++ .../internalinterfaces/factory_interfaces.go | 2 + 7 files changed, 73 insertions(+), 219 deletions(-) diff --git a/Gopkg.lock b/Gopkg.lock index 159cc855..1f6809bb 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -3,38 +3,31 @@ [[projects]] branch = "default" - digest = "1:24df057f15e7a09e75c1241cbe6f6590fd3eac9804f1110b02efade3214f042d" name = "bitbucket.org/ww/goautoneg" packages = ["."] - pruneopts = "UT" revision = "75cd24fc2f2c2a2088577d12123ddee5f54e0675" [[projects]] - digest = "1:7798129b37c4132f5b1d87964f070b120124eedfc7d670719805e644796251f5" name = "github.com/Azure/azure-sdk-for-go" packages = [ "services/appinsights/v1/insights", "services/preview/monitor/mgmt/2018-03-01/insights", "services/servicebus/mgmt/2017-04-01/servicebus", - "version", + "version" ] - pruneopts = "UT" revision = "d3bcaa706ac10b18784811ff31e43be635159013" version = "v21.0.0" [[projects]] branch = "master" - digest = "1:6da51e5ec493ad2b44cb04129e2d0a068c8fb9bd6cb5739d199573558696bb94" name = "github.com/Azure/go-ansiterm" packages = [ ".", - "winterm", + "winterm" ] - pruneopts = "UT" revision = "d6e3b3328b783f23731bc4d058875b0371ff8109" [[projects]] - digest = "1:469646dd53a792f7ecbe8ddfb326a356354b7727ec26d783f3d76ea069eb432a" name = "github.com/Azure/go-autorest" packages = [ "autorest", @@ -45,54 +38,42 @@ "autorest/to", "autorest/validation", "logger", - "version", + "version" ] - pruneopts = "UT" revision = "a88c19ef2016e095f0b6c3b451074b4663f53bed" version = "v10.15.4" [[projects]] - digest = "1:0803645e1f57fb5271a6edc7570b9ea59bac2e5de67957075a43f3d74c8dbd97" name = "github.com/NYTimes/gziphandler" packages = ["."] - pruneopts = "UT" revision = "2600fb119af974220d3916a5916d6e31176aac1b" version = "v1.0.1" [[projects]] - digest = "1:d1665c44bd5db19aaee18d1b6233c99b0b9a986e8bccb24ef54747547a48027f" name = "github.com/PuerkitoBio/purell" packages = ["."] - pruneopts = "UT" revision = "0bcb03f4b4d0a9428594752bd2a3b9aa0a9d4bd4" version = "v1.1.0" [[projects]] branch = "master" - digest = "1:c739832d67eb1e9cc478a19cc1a1ccd78df0397bf8a32978b759152e205f644b" name = "github.com/PuerkitoBio/urlesc" packages = ["."] - pruneopts = "UT" revision = "de5bf2ad457846296e2031421a34e2568e304e35" [[projects]] - digest = "1:69b1cc331fca23d702bd72f860c6a647afd0aa9fcbc1d0659b1365e26546dd70" name = "github.com/Sirupsen/logrus" packages = ["."] - pruneopts = "UT" revision = "bcd833dfe83d3cebad139e4a29ed79cb2318bf95" version = "v1.2.0" [[projects]] branch = "master" - digest = "1:d6afaeed1502aa28e80a4ed0981d570ad91b2579193404256ce672ed0a609e0d" name = "github.com/beorn7/perks" packages = ["quantile"] - pruneopts = "UT" revision = "3a771d992973f24aa725d07868b467d1ddfceafb" [[projects]] - digest = "1:5c0bb289ca4f1bc6a0e74943630fc804f3392a9ce9948b4e1088f3b1cd41038d" name = "github.com/coreos/etcd" packages = [ "auth/authpb", @@ -106,257 +87,201 @@ "pkg/tlsutil", "pkg/transport", "pkg/types", - "version", + "version" ] - pruneopts = "UT" revision = "33245c6b5b49130ca99280408fadfab01aac0e48" version = "v3.3.8" [[projects]] - digest = "1:0ef770954bca104ee99b3b6b7f9b240605ac03517d9f98cbc1893daa03f3c038" name = "github.com/coreos/go-semver" packages = ["semver"] - pruneopts = "UT" revision = "8ab6407b697782a06568d4b7f1db25550ec2e4c6" version = "v0.2.0" [[projects]] - digest = "1:1da3a221f0bc090792d3a2a080ff09008427c0e0f0533a4ed6abd8994421da73" name = "github.com/coreos/go-systemd" packages = ["daemon"] - pruneopts = "UT" revision = "39ca1b05acc7ad1220e09f133283b8859a8b71ab" version = "v17" [[projects]] - digest = "1:a2c1d0e43bd3baaa071d1b9ed72c27d78169b2b269f71c105ac4ba34b1be4a39" name = "github.com/davecgh/go-spew" packages = ["spew"] - pruneopts = "UT" revision = "346938d642f2ec3594ed81d874461961cd0faa76" version = "v1.1.0" [[projects]] - digest = "1:76dc72490af7174349349838f2fe118996381b31ea83243812a97e5a0fd5ed55" name = "github.com/dgrijalva/jwt-go" packages = ["."] - pruneopts = "UT" revision = "06ea1031745cb8b3dab3f6a236daf2b0aa468b7e" version = "v3.2.0" [[projects]] branch = "master" - digest = "1:e608bc2d867c3ded40ccea5417715393a50704ac24004afa87431a0e1976e50d" name = "github.com/dimchansky/utfbom" packages = ["."] - pruneopts = "UT" revision = "5448fe645cb1964ba70ac8f9f2ffe975e61a536c" [[projects]] - digest = "1:53e99d883df3e940f5f0223795f300eb32b8c044f226132bfc0e74930f24ea4b" name = "github.com/docker/docker" packages = [ "pkg/term", - "pkg/term/windows", + "pkg/term/windows" ] - pruneopts = "UT" revision = "092cba3727bb9b4a2f0e922cd6c0f93ea270e363" version = "v1.13.1" [[projects]] - digest = "1:f4f6279cb37479954644babd8f8ef00584ff9fa63555d2c6718c1c3517170202" name = "github.com/elazarl/go-bindata-assetfs" packages = ["."] - pruneopts = "UT" revision = "30f82fa23fd844bd5bb1e5f216db87fd77b5eb43" version = "v1.0.0" [[projects]] - digest = "1:899234af23e5793c34e06fd397f86ba33af5307b959b6a7afd19b63db065a9d7" name = "github.com/emicklei/go-restful" packages = [ ".", - "log", + "log" ] - pruneopts = "UT" revision = "3eb9738c1697594ea6e71a7156a9bb32ed216cf0" version = "v2.8.0" [[projects]] - digest = "1:ddab18e89cf46e40707b89dbe3835b4a591b0ea298e1035eefa84002aa9a4b4e" name = "github.com/emicklei/go-restful-swagger12" packages = ["."] - pruneopts = "UT" revision = "dcef7f55730566d41eae5db10e7d6981829720f6" version = "1.0.1" [[projects]] - digest = "1:b48d19e79fa607e9e3715ff9a73cdd3777a9cac254b50b9af721466f687e850d" name = "github.com/evanphx/json-patch" packages = ["."] - pruneopts = "UT" revision = "afac545df32f2287a079e2dfb7ba2745a643747e" version = "v3.0.0" [[projects]] - digest = "1:2cd7915ab26ede7d95b8749e6b1f933f1c6d5398030684e6505940a10f31cfda" name = "github.com/ghodss/yaml" packages = ["."] - pruneopts = "UT" revision = "0ca9ea5df5451ffdf184b4428c902747c2c11cd7" version = "v1.0.0" [[projects]] - digest = "1:2997679181d901ac8aaf4330d11138ecf3974c6d3334995ff36f20cbd597daf8" name = "github.com/go-openapi/jsonpointer" packages = ["."] - pruneopts = "UT" revision = "3a0015ad55fa9873f41605d3e8f28cd279c32ab2" version = "0.15.0" [[projects]] - digest = "1:1ae3f233d75a731b164ca9feafd8ed646cbedf1784095876ed6988ce8aa88b1f" name = "github.com/go-openapi/jsonreference" packages = ["."] - pruneopts = "UT" revision = "3fb327e6747da3043567ee86abd02bb6376b6be2" version = "0.15.0" [[projects]] - digest = "1:cbd9c1cc4ce36075f4ebf0e0525e6cda8597daac1a5eb5f7f88480a3c00e7319" name = "github.com/go-openapi/spec" packages = ["."] - pruneopts = "UT" revision = "bce47c9386f9ecd6b86f450478a80103c3fe1402" version = "0.15.0" [[projects]] - digest = "1:731022b436cdb9b4b2a53be2ead693467a1474b8b873d4f90cb424fffdc3d0ff" name = "github.com/go-openapi/swag" packages = ["."] - pruneopts = "UT" revision = "2b0bd4f193d011c203529df626a65d63cb8a79e8" version = "0.15.0" [[projects]] - digest = "1:db238461f652ddb7c7057bc6fc503f6003a29987b1485ecbb96d92287db65bc9" name = "github.com/gogo/protobuf" packages = [ "gogoproto", "proto", "protoc-gen-gogo/descriptor", - "sortkeys", + "sortkeys" ] - pruneopts = "UT" revision = "636bf0302bc95575d69441b25a2603156ffdddf1" version = "v1.1.1" [[projects]] branch = "master" - digest = "1:1ba1d79f2810270045c328ae5d674321db34e3aae468eb4233883b473c5c0467" name = "github.com/golang/glog" packages = ["."] - pruneopts = "UT" revision = "23def4e6c14b4da8ac2ed8007337bc5eb5007998" [[projects]] - digest = "1:17fe264ee908afc795734e8c4e63db2accabaf57326dbf21763a7d6b86096260" name = "github.com/golang/protobuf" packages = [ "proto", "ptypes", "ptypes/any", "ptypes/duration", - "ptypes/timestamp", + "ptypes/timestamp" ] - pruneopts = "UT" revision = "b4deda0973fb4c70b50d226b1af49f3da59f5265" version = "v1.1.0" [[projects]] branch = "master" - digest = "1:9887333bbef17574b1db5f9893ea137ac44107235d624408a3ac9e0b98fbb2cb" name = "github.com/google/btree" packages = ["."] - pruneopts = "UT" revision = "e89373fe6b4a7413d7acd6da1725b83ef713e6e4" [[projects]] branch = "master" - digest = "1:3ee90c0d94da31b442dde97c99635aaafec68d0b8a3c12ee2075c6bdabeec6bb" name = "github.com/google/gofuzz" packages = ["."] - pruneopts = "UT" revision = "24818f796faf91cd76ec7bddd72458fbced7a6c1" [[projects]] - digest = "1:65c4414eeb350c47b8de71110150d0ea8a281835b1f386eacaa3ad7325929c21" name = "github.com/googleapis/gnostic" packages = [ "OpenAPIv2", "compiler", - "extensions", + "extensions" ] - pruneopts = "UT" revision = "7c663266750e7d82587642f65e60bc4083f1f84e" version = "v0.2.0" [[projects]] branch = "master" - digest = "1:86c1210529e69d69860f2bb3ee9ccce0b595aa3f9165e7dd1388e5c612915888" name = "github.com/gregjones/httpcache" packages = [ ".", - "diskcache", + "diskcache" ] - pruneopts = "UT" revision = "9cad4c3443a7200dd6400aef47183728de563a38" [[projects]] - digest = "1:9b7a07ac7577787a8ecc1334cb9f34df1c76ed82a917d556c5713d3ab84fbc43" name = "github.com/grpc-ecosystem/go-grpc-prometheus" packages = ["."] - pruneopts = "UT" revision = "c225b8c3b01faf2899099b768856a9e916e5087b" version = "v1.2.0" [[projects]] branch = "master" - digest = "1:cf296baa185baae04a9a7004efee8511d08e2f5f51d4cbe5375da89722d681db" name = "github.com/hashicorp/golang-lru" packages = [ ".", - "simplelru", + "simplelru" ] - pruneopts = "UT" revision = "0fb14efe8c47ae851c0034ed7a448854d3d34cf3" [[projects]] - digest = "1:3e260afa138eab6492b531a3b3d10ab4cb70512d423faa78b8949dec76e66a21" name = "github.com/imdario/mergo" packages = ["."] - pruneopts = "UT" revision = "9316a62528ac99aaecb4e47eadd6dc8aa6533d58" version = "v0.3.5" [[projects]] - digest = "1:eaefc85d32c03e5f0c2b88ea2f79fce3d993e2c78316d21319575dd4ea9153ca" name = "github.com/json-iterator/go" packages = ["."] - pruneopts = "UT" revision = "ab8a2e0c74be9d3be70b3184d9acc634935ded82" version = "1.1.4" [[projects]] - digest = "1:0a69a1c0db3591fcefb47f115b224592c8dfa4368b7ba9fae509d5e16cdc95c8" name = "github.com/konsorten/go-windows-terminal-sequences" packages = ["."] - pruneopts = "UT" revision = "5c8c8bd35d3832f5d134ae1e1e375b69a4d25242" version = "v1.0.1" [[projects]] - digest = "1:398a3e3ecd267beb3a077f9072dd4d17e36d829bd5c73dc82066686e5d5f9c8b" name = "github.com/kubernetes-incubator/custom-metrics-apiserver" packages = [ "pkg/apiserver", @@ -367,143 +292,113 @@ "pkg/provider", "pkg/provider/helpers", "pkg/registry/custom_metrics", - "pkg/registry/external_metrics", + "pkg/registry/external_metrics" ] - pruneopts = "UT" revision = "bb8bae16c5550f2aeef3151259a1b36078a0e544" [[projects]] branch = "master" - digest = "1:89cb38858ea53690cdcd952f35b6cdda405dc9f8fc5601872e01b49c88c59991" name = "github.com/mailru/easyjson" packages = [ "buffer", "jlexer", - "jwriter", + "jwriter" ] - pruneopts = "UT" revision = "efc7eb8984d6655c26b5c9d2e65c024e5767c37c" [[projects]] - digest = "1:ff5ebae34cfbf047d505ee150de27e60570e8c394b3b8fdbb720ff6ac71985fc" name = "github.com/matttproud/golang_protobuf_extensions" packages = ["pbutil"] - pruneopts = "UT" revision = "c12348ce28de40eed0136aa2b644d0ee0650e56c" version = "v1.0.1" [[projects]] - digest = "1:33422d238f147d247752996a26574ac48dcf472976eda7f5134015f06bf16563" name = "github.com/modern-go/concurrent" packages = ["."] - pruneopts = "UT" revision = "bacd9c7ef1dd9b15be4a9909b8ac7a4e313eec94" version = "1.0.3" [[projects]] - digest = "1:e32bdbdb7c377a07a9a46378290059822efdce5c8d96fe71940d87cb4f918855" name = "github.com/modern-go/reflect2" packages = ["."] - pruneopts = "UT" revision = "4b7aa43c6742a2c18fdef89dd197aaae7dac7ccd" version = "1.0.1" [[projects]] - digest = "1:361de06aa7ae272616cbe71c3994a654cc6316324e30998e650f7765b20c5b33" name = "github.com/pborman/uuid" packages = ["."] - pruneopts = "UT" revision = "e790cca94e6cc75c7064b1332e63811d4aae1a53" version = "v1.1" [[projects]] branch = "master" - digest = "1:3bf17a6e6eaa6ad24152148a631d18662f7212e21637c2699bff3369b7f00fa2" name = "github.com/petar/GoLLRB" packages = ["llrb"] - pruneopts = "UT" revision = "53be0d36a84c2a886ca057d34b6aa4468df9ccb4" [[projects]] - digest = "1:0e7775ebbcf00d8dd28ac663614af924411c868dca3d5aa762af0fae3808d852" name = "github.com/peterbourgon/diskv" packages = ["."] - pruneopts = "UT" revision = "5f041e8faa004a95c88a202771f4cc3e991971e6" version = "v2.0.1" [[projects]] - digest = "1:b6221ec0f8903b556e127c449e7106b63e6867170c2d10a7c058623d086f2081" name = "github.com/prometheus/client_golang" packages = ["prometheus"] - pruneopts = "UT" revision = "c5b7fccd204277076155f10851dad72b76a49317" version = "v0.8.0" [[projects]] branch = "master" - digest = "1:2d5cd61daa5565187e1d96bae64dbbc6080dacf741448e9629c64fd93203b0d4" name = "github.com/prometheus/client_model" packages = ["go"] - pruneopts = "UT" revision = "5c3871d89910bfb32f5fcab2aa4b9ec68e65a99f" [[projects]] branch = "master" - digest = "1:e469cd65badf7694aeb44874518606d93c1d59e7735d3754ad442782437d3cc3" name = "github.com/prometheus/common" packages = [ "expfmt", "internal/bitbucket.org/ww/goautoneg", - "model", + "model" ] - pruneopts = "UT" revision = "7600349dcfe1abd18d72d3a1770870d9800a7801" [[projects]] branch = "master" - digest = "1:20d9bb50dbee172242f9bcd6ec24a917dd7a5bb17421bf16a79c33111dea7db1" name = "github.com/prometheus/procfs" packages = [ ".", "internal/util", "nfs", - "xfs", + "xfs" ] - pruneopts = "UT" revision = "ae68e2d4c00fed4943b5f6698d504a5fe083da8a" [[projects]] - digest = "1:9424f440bba8f7508b69414634aef3b2b3a877e522d8a4624692412805407bb7" name = "github.com/spf13/pflag" packages = ["."] - pruneopts = "UT" revision = "583c0c0531f06d5278b7d917446061adc344b5cd" version = "v1.0.1" [[projects]] - digest = "1:03aa6e485e528acb119fb32901cf99582c380225fc7d5a02758e08b180cb56c3" name = "github.com/ugorji/go" packages = ["codec"] - pruneopts = "UT" revision = "b4c50a2b199d93b13dc15e78929cfb23bfdf21ab" version = "v1.1.1" [[projects]] branch = "master" - digest = "1:670ac353e434afad9b6d96ba9735f243c5808c58ed67fdce9768e160d84389ba" name = "golang.org/x/crypto" packages = [ "pkcs12", "pkcs12/internal/rc2", - "ssh/terminal", + "ssh/terminal" ] - pruneopts = "UT" revision = "a2144134853fc9a27a7b1e3eb4f19f1a76df13c9" [[projects]] branch = "master" - digest = "1:0f06c679b9bc22304b591aa836804800d093c00b99af62c437d3989eacafdd97" name = "golang.org/x/net" packages = [ "context", @@ -514,35 +409,29 @@ "idna", "internal/timeseries", "trace", - "websocket", + "websocket" ] - pruneopts = "UT" revision = "a680a1efc54dd51c040b3b5ce4939ea3cf2ea0d1" [[projects]] branch = "master" - digest = "1:5276e08fe6a1dfdb65b4f46a2e5d5c9e00be6e499105e441049c3c04a0c83b36" name = "golang.org/x/oauth2" packages = [ ".", - "internal", + "internal" ] - pruneopts = "UT" revision = "d668ce993890a79bda886613ee587a69dd5da7a6" [[projects]] branch = "master" - digest = "1:3364d01296ce7eeca363e3d530ae63a2092d6f8efb85fb3d101e8f6d7de83452" name = "golang.org/x/sys" packages = [ "unix", - "windows", + "windows" ] - pruneopts = "UT" revision = "ac767d655b305d4e9612f5f6e33120b9176c4ad4" [[projects]] - digest = "1:0c56024909189aee3364b7f21a95a27459f718aa7c199a5c111c36cfffd9eaef" name = "golang.org/x/text" packages = [ "collate", @@ -559,22 +448,18 @@ "unicode/cldr", "unicode/norm", "unicode/rangetable", - "width", + "width" ] - pruneopts = "UT" revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0" version = "v0.3.0" [[projects]] branch = "master" - digest = "1:c9e7a4b4d47c0ed205d257648b0e5b0440880cb728506e318f8ac7cd36270bc4" name = "golang.org/x/time" packages = ["rate"] - pruneopts = "UT" revision = "fbb02b2291d28baffd63558aa44b4b56f178d650" [[projects]] - digest = "1:6f3bd49ddf2e104e52062774d797714371fac1b8bddfd8e124ce78e6b2264a10" name = "google.golang.org/appengine" packages = [ "internal", @@ -583,22 +468,18 @@ "internal/log", "internal/remote_api", "internal/urlfetch", - "urlfetch", + "urlfetch" ] - pruneopts = "UT" revision = "e9657d882bb81064595ca3b56cbe2546bbabf7b1" version = "v1.4.0" [[projects]] branch = "master" - digest = "1:601e63e7d4577f907118bec825902505291918859d223bce015539e79f1160e3" name = "google.golang.org/genproto" packages = ["googleapis/rpc/status"] - pruneopts = "UT" revision = "02b4e95473316948020af0b7a4f0f22c73929b0e" [[projects]] - digest = "1:3a98314fd2e43bbd905b33125dad80b10111ba6e5e541db8ed2a953fe01fbb31" name = "google.golang.org/grpc" packages = [ ".", @@ -626,39 +507,31 @@ "stats", "status", "tap", - "transport", + "transport" ] - pruneopts = "UT" revision = "168a6198bcb0ef175f7dacec0b8691fc141dc9b8" version = "v1.13.0" [[projects]] - digest = "1:2d1fbdc6777e5408cabeb02bf336305e724b925ff4546ded0fa8715a7267922a" name = "gopkg.in/inf.v0" packages = ["."] - pruneopts = "UT" revision = "d2d2541c53f18d2a059457998ce2876cc8e67cbf" version = "v0.9.1" [[projects]] - digest = "1:c805e517269b0ba4c21ded5836019ed7d16953d4026cb7d00041d039c7906be9" name = "gopkg.in/natefinch/lumberjack.v2" packages = ["."] - pruneopts = "UT" revision = "a96e63847dc3c67d17befa69c303767e2f84e54f" version = "v2.1" [[projects]] - digest = "1:342378ac4dcb378a5448dd723f0784ae519383532f5e70ade24132c4c8693202" name = "gopkg.in/yaml.v2" packages = ["."] - pruneopts = "UT" revision = "5420a8b6744d3b0345ab293f6fcba19c978f1183" version = "v2.2.1" [[projects]] branch = "master" - digest = "1:f6582c0dead2901b25e333078b23886a79ab39b4ddbfd0c34c93fcc151afedf3" name = "k8s.io/api" packages = [ "admission/v1beta1", @@ -692,14 +565,12 @@ "settings/v1alpha1", "storage/v1", "storage/v1alpha1", - "storage/v1beta1", + "storage/v1beta1" ] - pruneopts = "UT" revision = "173ce66c1e39d1d0f56e0b3347ff2988068aecd0" [[projects]] branch = "release-1.12" - digest = "1:e2428b67674275b9407fa9d9a91a8646e0bb513ec9fb7c51d20ee28051b0caaa" name = "k8s.io/apimachinery" packages = [ "pkg/api/equality", @@ -750,14 +621,12 @@ "pkg/version", "pkg/watch", "third_party/forked/golang/json", - "third_party/forked/golang/reflect", + "third_party/forked/golang/reflect" ] - pruneopts = "UT" revision = "49ce2735e5074ffc3f8190c8406cf51a96302dad" [[projects]] branch = "release-1.12" - digest = "1:7c4173a49a022735e412768f36e7feb8bd2aaae28b011f6c7c51ed1f8bde177b" name = "k8s.io/apiserver" packages = [ "pkg/admission", @@ -852,14 +721,12 @@ "plugin/pkg/audit/truncate", "plugin/pkg/audit/webhook", "plugin/pkg/authenticator/token/webhook", - "plugin/pkg/authorizer/webhook", + "plugin/pkg/authorizer/webhook" ] - pruneopts = "UT" revision = "9601a7bf41efece7e12a8f9f74d2c3b10cdd998e" [[projects]] branch = "release-9.0" - digest = "1:78499369c6276bf1c5d4faea152d7937cf32e3dc186b1953f391af7c909351c3" name = "k8s.io/client-go" packages = [ "discovery", @@ -996,28 +863,24 @@ "util/homedir", "util/integer", "util/retry", - "util/workqueue", + "util/workqueue" ] - pruneopts = "UT" revision = "5e6a3d4e34f694e895b13ae728111e726a5b69df" [[projects]] branch = "master" - digest = "1:a8a0fdd623b2a37c433d137bddfab6b155e988efbc7cd68c18f9923dce6c8742" name = "k8s.io/kube-openapi" packages = [ "pkg/builder", "pkg/common", "pkg/handler", "pkg/util", - "pkg/util/proto", + "pkg/util/proto" ] - pruneopts = "UT" revision = "d8ea2fe547a448256204cfc68dfee7b26c720acb" [[projects]] branch = "release-1.12" - digest = "1:17509b6226298c901915cca5a1024565b0636a8c46a96887642870fdd3d33c1b" name = "k8s.io/metrics" packages = [ "pkg/apis/custom_metrics", @@ -1026,51 +889,13 @@ "pkg/apis/custom_metrics/v1beta2", "pkg/apis/external_metrics", "pkg/apis/external_metrics/install", - "pkg/apis/external_metrics/v1beta1", + "pkg/apis/external_metrics/v1beta1" ] - pruneopts = "UT" revision = "3954d62a524dad50e7c4bcf91a26eeef011040e2" [solve-meta] analyzer-name = "dep" analyzer-version = 1 - input-imports = [ - "github.com/Azure/azure-sdk-for-go/services/appinsights/v1/insights", - "github.com/Azure/azure-sdk-for-go/services/preview/monitor/mgmt/2018-03-01/insights", - "github.com/Azure/azure-sdk-for-go/services/servicebus/mgmt/2017-04-01/servicebus", - "github.com/Azure/go-autorest/autorest/azure/auth", - "github.com/golang/glog", - "github.com/kubernetes-incubator/custom-metrics-apiserver/pkg/cmd", - "github.com/kubernetes-incubator/custom-metrics-apiserver/pkg/dynamicmapper", - "github.com/kubernetes-incubator/custom-metrics-apiserver/pkg/provider", - "github.com/kubernetes-incubator/custom-metrics-apiserver/pkg/provider/helpers", - "k8s.io/api/core/v1", - "k8s.io/apimachinery/pkg/api/errors", - "k8s.io/apimachinery/pkg/api/meta", - "k8s.io/apimachinery/pkg/api/resource", - "k8s.io/apimachinery/pkg/apis/meta/v1", - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured", - "k8s.io/apimachinery/pkg/labels", - "k8s.io/apimachinery/pkg/runtime", - "k8s.io/apimachinery/pkg/runtime/schema", - "k8s.io/apimachinery/pkg/runtime/serializer", - "k8s.io/apimachinery/pkg/selection", - "k8s.io/apimachinery/pkg/types", - "k8s.io/apimachinery/pkg/util/runtime", - "k8s.io/apimachinery/pkg/util/wait", - "k8s.io/apimachinery/pkg/watch", - "k8s.io/apiserver/pkg/util/logs", - "k8s.io/client-go/discovery", - "k8s.io/client-go/discovery/fake", - "k8s.io/client-go/dynamic", - "k8s.io/client-go/dynamic/fake", - "k8s.io/client-go/rest", - "k8s.io/client-go/testing", - "k8s.io/client-go/tools/cache", - "k8s.io/client-go/util/flowcontrol", - "k8s.io/client-go/util/workqueue", - "k8s.io/metrics/pkg/apis/custom_metrics", - "k8s.io/metrics/pkg/apis/external_metrics", - ] + inputs-digest = "fa7184f3a501cd91f1bcedacc6dafcf9c39fecd0dfb8557f4249ff99c19f11fe" solver-name = "gps-cdcl" solver-version = 1 diff --git a/hack/codegen-repo-fix.sh b/hack/codegen-repo-fix.sh index ea82abb5..a2a15690 100755 --- a/hack/codegen-repo-fix.sh +++ b/hack/codegen-repo-fix.sh @@ -6,9 +6,15 @@ set -o pipefail # make sure we have correct version of code generator cd $GOPATH/src/k8s.io/code-generator/ -git fetch --all -git checkout tags/kubernetes-1.12.9 -b kubernetes-1.12.9 +# https://stackoverflow.com/a/6245587/697126 +currentbranch=$(git branch | grep \* | cut -d ' ' -f2) + +if [[ $currentbranch != "release-1.14" ]] +then + git fetch --all + git checkout -t origin/release-1.14 +fi diff --git a/pkg/client/clientset/versioned/clientset.go b/pkg/client/clientset/versioned/clientset.go index 00f5b803..ad435db2 100644 --- a/pkg/client/clientset/versioned/clientset.go +++ b/pkg/client/clientset/versioned/clientset.go @@ -28,8 +28,6 @@ import ( type Interface interface { Discovery() discovery.DiscoveryInterface AzureV1alpha2() azurev1alpha2.AzureV1alpha2Interface - // Deprecated: please explicitly pick a version if possible. - Azure() azurev1alpha2.AzureV1alpha2Interface } // Clientset contains the clients for groups. Each group has exactly one @@ -44,12 +42,6 @@ func (c *Clientset) AzureV1alpha2() azurev1alpha2.AzureV1alpha2Interface { return c.azureV1alpha2 } -// Deprecated: Azure retrieves the default version of AzureClient. -// Please explicitly pick a version. -func (c *Clientset) Azure() azurev1alpha2.AzureV1alpha2Interface { - return c.azureV1alpha2 -} - // Discovery retrieves the DiscoveryClient func (c *Clientset) Discovery() discovery.DiscoveryInterface { if c == nil { diff --git a/pkg/client/clientset/versioned/fake/clientset_generated.go b/pkg/client/clientset/versioned/fake/clientset_generated.go index 9f194956..01f35aa1 100644 --- a/pkg/client/clientset/versioned/fake/clientset_generated.go +++ b/pkg/client/clientset/versioned/fake/clientset_generated.go @@ -75,8 +75,3 @@ var _ clientset.Interface = &Clientset{} func (c *Clientset) AzureV1alpha2() azurev1alpha2.AzureV1alpha2Interface { return &fakeazurev1alpha2.FakeAzureV1alpha2{Fake: &c.Fake} } - -// Azure retrieves the AzureV1alpha2Client -func (c *Clientset) Azure() azurev1alpha2.AzureV1alpha2Interface { - return &fakeazurev1alpha2.FakeAzureV1alpha2{Fake: &c.Fake} -} diff --git a/pkg/client/clientset/versioned/typed/metrics/v1alpha2/custommetric.go b/pkg/client/clientset/versioned/typed/metrics/v1alpha2/custommetric.go index 21bad765..24d2d089 100644 --- a/pkg/client/clientset/versioned/typed/metrics/v1alpha2/custommetric.go +++ b/pkg/client/clientset/versioned/typed/metrics/v1alpha2/custommetric.go @@ -19,6 +19,8 @@ limitations under the License. package v1alpha2 import ( + "time" + v1alpha2 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha2" scheme "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned/scheme" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -73,11 +75,16 @@ func (c *customMetrics) Get(name string, options v1.GetOptions) (result *v1alpha // List takes label and field selectors, and returns the list of CustomMetrics that match those selectors. func (c *customMetrics) List(opts v1.ListOptions) (result *v1alpha2.CustomMetricList, err error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } result = &v1alpha2.CustomMetricList{} err = c.client.Get(). Namespace(c.ns). Resource("custommetrics"). VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). Do(). Into(result) return @@ -85,11 +92,16 @@ func (c *customMetrics) List(opts v1.ListOptions) (result *v1alpha2.CustomMetric // Watch returns a watch.Interface that watches the requested customMetrics. func (c *customMetrics) Watch(opts v1.ListOptions) (watch.Interface, error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } opts.Watch = true return c.client.Get(). Namespace(c.ns). Resource("custommetrics"). VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). Watch() } @@ -131,10 +143,15 @@ func (c *customMetrics) Delete(name string, options *v1.DeleteOptions) error { // DeleteCollection deletes a collection of objects. func (c *customMetrics) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { + var timeout time.Duration + if listOptions.TimeoutSeconds != nil { + timeout = time.Duration(*listOptions.TimeoutSeconds) * time.Second + } return c.client.Delete(). Namespace(c.ns). Resource("custommetrics"). VersionedParams(&listOptions, scheme.ParameterCodec). + Timeout(timeout). Body(options). Do(). Error() diff --git a/pkg/client/clientset/versioned/typed/metrics/v1alpha2/externalmetric.go b/pkg/client/clientset/versioned/typed/metrics/v1alpha2/externalmetric.go index b7539ee6..2c42089a 100644 --- a/pkg/client/clientset/versioned/typed/metrics/v1alpha2/externalmetric.go +++ b/pkg/client/clientset/versioned/typed/metrics/v1alpha2/externalmetric.go @@ -19,6 +19,8 @@ limitations under the License. package v1alpha2 import ( + "time" + v1alpha2 "github.com/Azure/azure-k8s-metrics-adapter/pkg/apis/metrics/v1alpha2" scheme "github.com/Azure/azure-k8s-metrics-adapter/pkg/client/clientset/versioned/scheme" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -73,11 +75,16 @@ func (c *externalMetrics) Get(name string, options v1.GetOptions) (result *v1alp // List takes label and field selectors, and returns the list of ExternalMetrics that match those selectors. func (c *externalMetrics) List(opts v1.ListOptions) (result *v1alpha2.ExternalMetricList, err error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } result = &v1alpha2.ExternalMetricList{} err = c.client.Get(). Namespace(c.ns). Resource("externalmetrics"). VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). Do(). Into(result) return @@ -85,11 +92,16 @@ func (c *externalMetrics) List(opts v1.ListOptions) (result *v1alpha2.ExternalMe // Watch returns a watch.Interface that watches the requested externalMetrics. func (c *externalMetrics) Watch(opts v1.ListOptions) (watch.Interface, error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } opts.Watch = true return c.client.Get(). Namespace(c.ns). Resource("externalmetrics"). VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). Watch() } @@ -131,10 +143,15 @@ func (c *externalMetrics) Delete(name string, options *v1.DeleteOptions) error { // DeleteCollection deletes a collection of objects. func (c *externalMetrics) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { + var timeout time.Duration + if listOptions.TimeoutSeconds != nil { + timeout = time.Duration(*listOptions.TimeoutSeconds) * time.Second + } return c.client.Delete(). Namespace(c.ns). Resource("externalmetrics"). VersionedParams(&listOptions, scheme.ParameterCodec). + Timeout(timeout). Body(options). Do(). Error() diff --git a/pkg/client/informers/externalversions/internalinterfaces/factory_interfaces.go b/pkg/client/informers/externalversions/internalinterfaces/factory_interfaces.go index 6f86a7b1..185b3f38 100644 --- a/pkg/client/informers/externalversions/internalinterfaces/factory_interfaces.go +++ b/pkg/client/informers/externalversions/internalinterfaces/factory_interfaces.go @@ -27,6 +27,7 @@ import ( cache "k8s.io/client-go/tools/cache" ) +// NewInformerFunc takes versioned.Interface and time.Duration to return a SharedIndexInformer. type NewInformerFunc func(versioned.Interface, time.Duration) cache.SharedIndexInformer // SharedInformerFactory a small interface to allow for adding an informer without an import cycle @@ -35,4 +36,5 @@ type SharedInformerFactory interface { InformerFor(obj runtime.Object, newFunc NewInformerFunc) cache.SharedIndexInformer } +// TweakListOptionsFunc is a function that transforms a v1.ListOptions. type TweakListOptionsFunc func(*v1.ListOptions)